@open-mercato/cli 0.10.1-develop.8279.1.7d4003fb64 → 0.10.1-develop.8287.1.7313a0fe67

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.
Files changed (148) hide show
  1. package/dist/agentic/guides/ai-workflows.md +1 -0
  2. package/dist/agentic/guides/module-facts.json +2670 -269
  3. package/dist/agentic/guides/module-facts.v2.json +2673 -269
  4. package/dist/agentic/guides/modules/agent_orchestrator/acl-features.md +2 -1
  5. package/dist/agentic/guides/modules/agent_orchestrator/active-extension-bindings.md +1 -1
  6. package/dist/agentic/guides/modules/agent_orchestrator/backend-pages.md +3 -0
  7. package/dist/agentic/guides/modules/agent_orchestrator/cli-commands.md +4 -0
  8. package/dist/agentic/guides/modules/agent_orchestrator/contribution-resolutions.md +6 -0
  9. package/dist/agentic/guides/modules/agent_orchestrator/di-registrations-rich.md +32 -32
  10. package/dist/agentic/guides/modules/agent_orchestrator/di-service-tokens.md +14 -14
  11. package/dist/agentic/guides/modules/agent_orchestrator/domain-commands.md +3 -0
  12. package/dist/agentic/guides/modules/agent_orchestrator/events.md +2 -1
  13. package/dist/agentic/guides/modules/agent_orchestrator/exact-override-targets.md +104 -35
  14. package/dist/agentic/guides/modules/agent_orchestrator/index.md +18 -7
  15. package/dist/agentic/guides/modules/agent_orchestrator/setup.md +1 -1
  16. package/dist/agentic/guides/modules/agent_orchestrator/umes-contributions.md +6 -0
  17. package/dist/agentic/guides/modules/agent_orchestrator/umes-hosts.md +2 -1
  18. package/dist/agentic/guides/modules/agent_orchestrator/workers.md +2 -0
  19. package/dist/agentic/guides/modules/ai_assistant/acl-features.md +4 -1
  20. package/dist/agentic/guides/modules/ai_assistant/ai-tools-mcp-capabilities.md +1 -0
  21. package/dist/agentic/guides/modules/ai_assistant/backend-pages.md +4 -0
  22. package/dist/agentic/guides/modules/ai_assistant/cli-commands.md +1 -0
  23. package/dist/agentic/guides/modules/ai_assistant/contribution-resolutions.md +3 -0
  24. package/dist/agentic/guides/modules/ai_assistant/di-registrations-rich.md +5 -4
  25. package/dist/agentic/guides/modules/ai_assistant/di-service-tokens.md +4 -3
  26. package/dist/agentic/guides/modules/ai_assistant/encryption.md +3 -0
  27. package/dist/agentic/guides/modules/ai_assistant/entities.md +3 -0
  28. package/dist/agentic/guides/modules/ai_assistant/events.md +2 -1
  29. package/dist/agentic/guides/modules/ai_assistant/exact-override-targets.md +23 -7
  30. package/dist/agentic/guides/modules/ai_assistant/index.md +9 -9
  31. package/dist/agentic/guides/modules/ai_assistant/notifications.md +1 -0
  32. package/dist/agentic/guides/modules/ai_assistant/setup.md +1 -1
  33. package/dist/agentic/guides/modules/ai_assistant/umes-contributions.md +3 -0
  34. package/dist/agentic/guides/modules/ai_assistant/umes-hosts.md +4 -0
  35. package/dist/agentic/guides/modules/ai_assistant/workers.md +2 -1
  36. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  37. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  38. package/dist/agentic/guides/modules/attachments/active-extension-bindings.md +1 -0
  39. package/dist/agentic/guides/modules/attachments/ai-tools-mcp-capabilities.md +11 -0
  40. package/dist/agentic/guides/modules/attachments/backend-pages.md +1 -0
  41. package/dist/agentic/guides/modules/attachments/cli-commands.md +1 -0
  42. package/dist/agentic/guides/modules/attachments/contribution-resolutions.md +13 -0
  43. package/dist/agentic/guides/modules/attachments/di-registrations-rich.md +6 -6
  44. package/dist/agentic/guides/modules/attachments/di-service-tokens.md +5 -5
  45. package/dist/agentic/guides/modules/attachments/domain-commands.md +11 -0
  46. package/dist/agentic/guides/modules/attachments/encryption.md +12 -0
  47. package/dist/agentic/guides/modules/attachments/entities.md +2 -0
  48. package/dist/agentic/guides/modules/attachments/exact-override-targets.md +14 -6
  49. package/dist/agentic/guides/modules/attachments/index.md +11 -5
  50. package/dist/agentic/guides/modules/attachments/search-entities.md +11 -0
  51. package/dist/agentic/guides/modules/attachments/umes-contributions.md +13 -0
  52. package/dist/agentic/guides/modules/attachments/umes-hosts.md +4 -0
  53. package/dist/agentic/guides/modules/attachments/workers.md +2 -0
  54. package/dist/agentic/guides/modules/audit_logs/active-extension-bindings.md +11 -0
  55. package/dist/agentic/guides/modules/audit_logs/incoming-installed-contributions.md +12 -0
  56. package/dist/agentic/guides/modules/audit_logs/index.md +4 -2
  57. package/dist/agentic/guides/modules/auth/index.md +1 -1
  58. package/dist/agentic/guides/modules/availability/index.md +1 -1
  59. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  60. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  61. package/dist/agentic/guides/modules/cart/index.md +1 -1
  62. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  63. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  64. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  65. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  66. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  67. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  68. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  69. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  70. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  71. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  72. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  73. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  74. package/dist/agentic/guides/modules/configs/index.md +1 -1
  75. package/dist/agentic/guides/modules/content/index.md +1 -1
  76. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  77. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  78. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  79. package/dist/agentic/guides/modules/customers/index.md +1 -1
  80. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  81. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  82. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  83. package/dist/agentic/guides/modules/devices/index.md +1 -1
  84. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  85. package/dist/agentic/guides/modules/directory/index.md +1 -1
  86. package/dist/agentic/guides/modules/documents/index.md +1 -1
  87. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  88. package/dist/agentic/guides/modules/entities/index.md +1 -1
  89. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  90. package/dist/agentic/guides/modules/events/index.md +1 -1
  91. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  92. package/dist/agentic/guides/modules/forms/index.md +1 -1
  93. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  94. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  95. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  96. package/dist/agentic/guides/modules/generators/index.md +1 -1
  97. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  98. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  99. package/dist/agentic/guides/modules/messages/index.md +1 -1
  100. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  101. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  102. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  103. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  104. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  105. package/dist/agentic/guides/modules/planner/index.md +1 -1
  106. package/dist/agentic/guides/modules/portal/index.md +1 -1
  107. package/dist/agentic/guides/modules/progress/index.md +1 -1
  108. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  109. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  110. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  111. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  112. package/dist/agentic/guides/modules/resources/index.md +1 -1
  113. package/dist/agentic/guides/modules/sales/index.md +1 -1
  114. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  115. package/dist/agentic/guides/modules/search/index.md +1 -1
  116. package/dist/agentic/guides/modules/security/index.md +1 -1
  117. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  118. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  119. package/dist/agentic/guides/modules/sso/index.md +1 -1
  120. package/dist/agentic/guides/modules/staff/index.md +1 -1
  121. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  122. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  123. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  124. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  125. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  126. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  127. package/dist/agentic/guides/modules/translations/index.md +1 -1
  128. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  129. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  130. package/dist/agentic/guides/modules/wms/index.md +1 -1
  131. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  132. package/dist/agentic/guides/reference-module-facts.json +1 -1
  133. package/dist/agentic/guides/upstream/manifest.json +1 -1
  134. package/dist/agentic/shared/ai/harness/README.md +3 -3
  135. package/dist/agentic/shared/ai/harness/RELEASE.md +4 -4
  136. package/dist/agentic/shared/ai/harness/cases.json +95 -2
  137. package/dist/agentic/shared/ai/harness/cases.schema.json +4 -4
  138. package/dist/agentic/shared/ai/harness/validators.json +1 -1
  139. package/dist/agentic/shared/ai/skills/om-create-ai-agent/SKILL.md +6 -5
  140. package/dist/agentic/shared/ai/skills/om-create-ai-agent/references/surface-selector.md +27 -0
  141. package/dist/lib/generators/extensions/agent-files.js +119 -4
  142. package/dist/lib/generators/extensions/agent-files.js.map +2 -2
  143. package/dist/lib/generators/module-facts.js +6 -4
  144. package/dist/lib/generators/module-facts.js.map +2 -2
  145. package/package.json +7 -7
  146. package/src/lib/generators/__tests__/agent-files-extension.test.ts +178 -0
  147. package/src/lib/generators/extensions/agent-files.ts +154 -4
  148. package/src/lib/generators/module-facts.ts +8 -4
@@ -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 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,CAAC,GAAG,cAAc,KAAK,KAAK,EAAE;AACjG,QAAM,QAAQ,iBAAiB,MAAM,IAAI;AAC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,UAAU,CAAC,OAAO,GAAG,MAAM,gBAAgB,CAAC;AAK9E,YAAM,gBAAgB,CAAC,UAAmC,MAAM,OAAO;AACvE,YAAM,oBAAoB,oBAAI,IAAY;AAC1C,iBAAW,SAAS,WAAW;AAC7B,mBAAW,SAAS,MAAM,eAAe;AACvC,cAAI,cAAc,KAAK,EAAG,mBAAkB,IAAI,MAAM,iBAAiB;AAAA,QACzE;AAAA,MACF;AACA,UAAI,kBAAkB,OAAO,EAAG,IAAG,UAAU,iBAAiB,EAAE,WAAW,KAAK,CAAC;AACjF,UAAI,GAAG,WAAW,eAAe,GAAG;AAClC,mBAAW,YAAY,GAAG,YAAY,iBAAiB,EAAE,eAAe,KAAK,CAAC,GAAG;AAC/E,cAAI,SAAS,YAAY,KAAK,CAAC,kBAAkB,IAAI,SAAS,IAAI,GAAG;AACnE,eAAG,OAAO,KAAK,KAAK,iBAAiB,SAAS,IAAI,GAAG,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,UACvF;AAAA,QACF;AAAA,MACF;AACA,YAAM,qBAAqB,oBAAI,IAAY;AAC3C,iBAAW,SAAS,WAAW;AAC7B,mBAAW,SAAS,MAAM,eAAe;AACvC,cAAI,CAAC,cAAc,KAAK,EAAG;AAG3B,cAAI,mBAAmB,IAAI,MAAM,iBAAiB,EAAG;AACrD,6BAAmB,IAAI,MAAM,iBAAiB;AAC9C,gBAAM,WAAW,KAAK,KAAK,iBAAiB,MAAM,iBAAiB;AACnE,aAAG,UAAU,UAAU,EAAE,WAAW,KAAK,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 /** Invoker ACL features from AGENT.md `requiredFeatures` (deduped; empty when undeclared). */\n requiredFeatures: 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 /** Optional `GOVERNANCE.json` declarations, validated in full when the agent loads. */\n governance?: DiscoveredGovernance\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 DiscoveredGovernance = {\n principal?: Record<string, unknown>\n integrity?: unknown[]\n untrustedInputs?: unknown[]\n modelSettings?: Record<string, unknown>\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', 'requiredFeatures'] as const\nconst REQUIRED_FEATURE_RE = /^[A-Za-z0-9_][A-Za-z0-9_.*:-]*$/\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 requiredFeatures: 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 = {\n tools: [],\n skills: [],\n subAgents: [],\n requiredFeatures: [],\n instructions: body.trim(),\n }\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 meta.requiredFeatures = Array.from(new Set(meta.requiredFeatures))\n return meta\n}\n\nfunction assertRequiredFeaturesValid(features: string[], dir: string): void {\n const invalid = features.find((feature) => feature.length > 200 || !REQUIRED_FEATURE_RE.test(feature))\n if (invalid !== undefined) {\n throw new Error(`[internal] invalid requiredFeatures entry \"${invalid}\" in AGENT.md at ${dir}`)\n }\n if (features.length > 50) {\n throw new Error(`[internal] too many requiredFeatures (max 50) in AGENT.md at ${dir}`)\n }\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\n/**\n * JSON paths of the objects in an OUTCOME schema that declare no properties.\n * The runtime compiles such an object to an empty, stripping one, so whatever the\n * model puts in it is dropped on every runtime \u2014 an author almost certainly meant\n * to list its properties. Generation warns rather than fails: the schema is valid.\n */\nfunction findOpenOutcomeObjects(node: unknown, path = '$'): string[] {\n if (typeof node !== 'object' || node === null || Array.isArray(node)) return []\n const schema = node as Record<string, unknown>\n if (schema.type === 'object') {\n const properties =\n typeof schema.properties === 'object' && schema.properties !== null && !Array.isArray(schema.properties)\n ? (schema.properties as Record<string, unknown>)\n : {}\n const keys = Object.keys(properties)\n if (keys.length === 0) return [path]\n return keys.flatMap((key) => findOpenOutcomeObjects(properties[key], `${path}.${key}`))\n }\n if (schema.type === 'array') return findOpenOutcomeObjects(schema.items, `${path}[]`)\n return []\n}\n\nfunction warnOpenOutcomeObjects(schema: Record<string, unknown> | undefined, where: string): void {\n if (!schema) return\n for (const openPath of findOpenOutcomeObjects(schema)) {\n console.warn(\n `[internal] OUTCOME.md at ${where}: the object at ${openPath} declares no properties, so it always validates to {} and any content the agent returns there is dropped. List its properties.`,\n )\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\nconst GOVERNANCE_FILE = 'GOVERNANCE.json'\nconst GOVERNANCE_OBJECT_KEYS = ['principal', 'modelSettings'] as const\nconst GOVERNANCE_LIST_KEYS = ['integrity', 'untrustedInputs'] as const\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Read the optional `agents/<id>/GOVERNANCE.json`: the same `principal`,\n * `integrity`, `untrustedInputs` and `modelSettings` declarations `defineAgent`\n * accepts. Only the top-level shape is checked here \u2014 an unknown key, a key of\n * the wrong type, or invalid JSON fails generation LOUDLY. The agent loader\n * validates every declaration with the `defineAgent` parsers and refuses to\n * register an agent whose declaration does not parse.\n */\nfunction discoverGovernance(dir: string): DiscoveredGovernance | undefined {\n const governancePath = path.join(dir, GOVERNANCE_FILE)\n if (!fs.existsSync(governancePath)) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(fs.readFileSync(governancePath, 'utf8'))\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new Error(`[internal] malformed ${GOVERNANCE_FILE} at ${dir}: ${detail}`)\n }\n if (!isPlainObject(parsed)) {\n throw new Error(`[internal] malformed ${GOVERNANCE_FILE} at ${dir}: expected a JSON object`)\n }\n const allowed = [...GOVERNANCE_OBJECT_KEYS, ...GOVERNANCE_LIST_KEYS] as readonly string[]\n const unknownKey = Object.keys(parsed).find((key) => !allowed.includes(key))\n if (unknownKey) {\n throw new Error(\n `[internal] malformed ${GOVERNANCE_FILE} at ${dir}: unknown key \"${unknownKey}\" (allowed: ${allowed.join(', ')})`,\n )\n }\n const governance: DiscoveredGovernance = {}\n for (const key of GOVERNANCE_OBJECT_KEYS) {\n const value = parsed[key]\n if (value === undefined) continue\n if (!isPlainObject(value)) {\n throw new Error(`[internal] malformed ${GOVERNANCE_FILE} at ${dir}: \"${key}\" must be an object`)\n }\n governance[key] = value\n }\n for (const key of GOVERNANCE_LIST_KEYS) {\n const value = parsed[key]\n if (value === undefined) continue\n if (!Array.isArray(value)) {\n throw new Error(`[internal] malformed ${GOVERNANCE_FILE} at ${dir}: \"${key}\" must be an array`)\n }\n governance[key] = value\n }\n return Object.keys(governance).length > 0 ? governance : undefined\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 assertRequiredFeaturesValid(agent.requiredFeatures, dir)\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 warnOpenOutcomeObjects(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 requiredFeatures: agent.requiredFeatures,\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 governance: discoverGovernance(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', GOVERNANCE_FILE]\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.requiredFeatures.length > 0) {\n optional.push(`${indent} requiredFeatures: ${JSON.stringify(agent.requiredFeatures)},`)\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 if (agent.governance !== undefined) {\n optional.push(`${indent} governance: ${JSON.stringify(agent.governance)},`)\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 FileAgentGovernance = {\n principal?: Record<string, unknown>\n integrity?: unknown[]\n untrustedInputs?: unknown[]\n modelSettings?: Record<string, unknown>\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/GOVERNANCE.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 /**\n * ACL features the invoker must hold to run this agent, from AGENT.md\n * \\`requiredFeatures\\`. Absent when the agent declares none.\n */\n requiredFeatures?: string[]\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 * Optional governance declarations read from \\`agents/<id>/GOVERNANCE.json\\`:\n * the same \\`principal\\`, \\`integrity\\`, \\`untrustedInputs\\` and\n * \\`modelSettings\\` keys \\`defineAgent\\` accepts, as plain JSON. The loader\n * validates them with the \\`defineAgent\\` parsers.\n */\n governance?: FileAgentGovernance\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 assertRequiredFeaturesValid(agent.requiredFeatures, dir)\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 warnOpenOutcomeObjects(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 requiredFeatures: agent.requiredFeatures,\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 governance: discoverGovernance(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 }\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AAG;AAG3B,cAAI,mBAAmB,IAAI,MAAM,iBAAiB,EAAG;AACrD,6BAAmB,IAAI,MAAM,iBAAiB;AAC9C,gBAAM,WAAW,KAAK,KAAK,iBAAiB,MAAM,iBAAiB;AACnE,aAAG,UAAU,UAAU,EAAE,WAAW,KAAK,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;",
6
6
  "names": ["path"]
7
7
  }
@@ -1724,6 +1724,8 @@ function extractModuleFacts(options) {
1724
1724
  }
1725
1725
  const EMPTY_SECTION_MARKER = "_none_";
1726
1726
  const MAX_ANCHORED_SECTION_BYTES = 32 * 1024;
1727
+ const ANCHORED_SECTION_WRAPPER_RESERVE_BYTES = 512;
1728
+ const MAX_COMPACT_SECTION_BYTES = MAX_ANCHORED_SECTION_BYTES - ANCHORED_SECTION_WRAPPER_RESERVE_BYTES;
1727
1729
  function renderGroupedTableSection(sectionHeading, header, divider, groups) {
1728
1730
  const renderedGroups = [];
1729
1731
  for (const group of groups) {
@@ -1735,7 +1737,7 @@ function renderGroupedTableSection(sectionHeading, header, divider, groups) {
1735
1737
  };
1736
1738
  for (const row of group.rows) {
1737
1739
  const candidateRows = [...currentRows, row];
1738
- if (Buffer.byteLength(renderChunk(candidateRows, chunks.length)) <= MAX_ANCHORED_SECTION_BYTES) {
1740
+ if (Buffer.byteLength(renderChunk(candidateRows, chunks.length)) <= MAX_COMPACT_SECTION_BYTES) {
1739
1741
  currentRows = candidateRows;
1740
1742
  continue;
1741
1743
  }
@@ -1744,7 +1746,7 @@ function renderGroupedTableSection(sectionHeading, header, divider, groups) {
1744
1746
  }
1745
1747
  chunks.push(currentRows);
1746
1748
  currentRows = [row];
1747
- if (Buffer.byteLength(renderChunk(currentRows, chunks.length)) > MAX_ANCHORED_SECTION_BYTES) {
1749
+ if (Buffer.byteLength(renderChunk(currentRows, chunks.length)) > MAX_COMPACT_SECTION_BYTES) {
1748
1750
  throw new Error(`[module-facts] ${sectionHeading} group "${group.title}" contains a row larger than the anchored read cap`);
1749
1751
  }
1750
1752
  }
@@ -1923,7 +1925,7 @@ ${EMPTY_SECTION_MARKER}`;
1923
1925
  (host) => `| ${host.id} | ${host.family} | ${host.capabilities.join(", ") || "\u2014"} | ${renderExtensionHostContext(host)} | ${host.stability.toUpperCase()} | ${renderExtensionHostSource(host, context)} |`
1924
1926
  );
1925
1927
  const compact = [...header, ...renderRows(boundHosts)].join("\n");
1926
- if (Buffer.byteLength(compact) <= MAX_ANCHORED_SECTION_BYTES) return compact;
1928
+ if (Buffer.byteLength(compact) <= MAX_COMPACT_SECTION_BYTES) return compact;
1927
1929
  const families = [...new Set(boundHosts.map((host) => host.family))];
1928
1930
  return renderGroupedTableSection(
1929
1931
  "## UMES hosts",
@@ -2061,7 +2063,7 @@ ${EMPTY_SECTION_MARKER}`;
2061
2063
  return `| ${target.domain} | ${path2} | ${modes} | ${fact} | ${renderSourceRefLink(target.source, context)} |`;
2062
2064
  });
2063
2065
  const compact = ["## Exact override targets", "", header, divider, ...renderRows(targets)].join("\n");
2064
- if (Buffer.byteLength(compact) <= MAX_ANCHORED_SECTION_BYTES) return compact;
2066
+ if (Buffer.byteLength(compact) <= MAX_COMPACT_SECTION_BYTES) return compact;
2065
2067
  const domains = [...new Set(targets.map((target) => target.domain))];
2066
2068
  return renderGroupedTableSection(
2067
2069
  "## Exact override targets",