@agimon-ai/po-config 0.0.0-alpha.3 → 0.0.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -9
- package/dist/agentPluginMcp.cjs.map +1 -1
- package/dist/agentPluginMcp.d.mts +4 -4
- package/dist/agentPluginMcp.d.mts.map +1 -1
- package/dist/agentPluginMcp.mjs.map +1 -1
- package/dist/apiContracts.cjs.map +1 -1
- package/dist/apiContracts.mjs.map +1 -1
- package/dist/{completion-D2lm3W76.d.mts → completion-Ba0TiBHa.d.mts} +3 -3
- package/dist/{completion-D2lm3W76.d.mts.map → completion-Ba0TiBHa.d.mts.map} +1 -1
- package/dist/config-BBvn_ZLP.mjs +1 -0
- package/dist/{config-CzD87B5t.cjs → config-Cdybp9rT.cjs} +41 -41
- package/dist/config-Cdybp9rT.cjs.map +1 -0
- package/dist/{config-CW-wChAT.mjs → config-Cxc2xw54.mjs} +28 -28
- package/dist/config-Cxc2xw54.mjs.map +1 -0
- package/dist/{config-D2HbBLzo.d.mts → config-pxC7FyUJ.d.mts} +33 -33
- package/dist/config-pxC7FyUJ.d.mts.map +1 -0
- package/dist/config.cjs +20 -20
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +4 -4
- package/dist/{configPolicy-Ce1QKDxa.cjs → configPolicy-CowlLhK1.cjs} +99 -99
- package/dist/configPolicy-CowlLhK1.cjs.map +1 -0
- package/dist/{configPolicy-DCQgF5-f.mjs → configPolicy-DueX0k6i.mjs} +84 -84
- package/dist/configPolicy-DueX0k6i.mjs.map +1 -0
- package/dist/configSchema.d.mts +2 -2
- package/dist/{configWriter-DXaci8le.mjs → configWriter-DCASRzr-.mjs} +24 -24
- package/dist/configWriter-DCASRzr-.mjs.map +1 -0
- package/dist/{configWriter-crMObKDH.cjs → configWriter-DGO0gmXo.cjs} +35 -35
- package/dist/configWriter-DGO0gmXo.cjs.map +1 -0
- package/dist/configWriter.cjs +7 -7
- package/dist/configWriter.d.mts +2 -2
- package/dist/configWriter.mjs +1 -1
- package/dist/{core-DeEKLC4l.cjs → core-B0Qg0Qq2.cjs} +29 -29
- package/dist/core-B0Qg0Qq2.cjs.map +1 -0
- package/dist/{core-Slanr8K3.mjs → core-DKWW9gkh.mjs} +20 -20
- package/dist/core-DKWW9gkh.mjs.map +1 -0
- package/dist/{domains-9Vl18yDq.cjs → domains-CiDUsRiX.cjs} +10 -10
- package/dist/domains-CiDUsRiX.cjs.map +1 -0
- package/dist/{domains-BkLewDJd.mjs → domains-IlieGHaY.mjs} +10 -10
- package/dist/domains-IlieGHaY.mjs.map +1 -0
- package/dist/domains.cjs +3 -3
- package/dist/domains.d.mts +3 -3
- package/dist/domains.mjs +3 -3
- package/dist/extensions/mcp-ui.mjs +1 -1
- package/dist/extensions/mcp-ui.mjs.map +1 -1
- package/dist/extensions/mcp.cjs +1 -1
- package/dist/extensions/mcp.cjs.map +1 -1
- package/dist/extensions/mcp.d.mts +1 -1
- package/dist/extensions/mcp.mjs +1 -1
- package/dist/extensions/mcp.mjs.map +1 -1
- package/dist/extensions/server.cjs +27 -27
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.d.mts +1 -1
- package/dist/extensions/server.mjs +32 -32
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/{harnessState-Dn_S7fB9.mjs → harnessState-8lZda_8r.mjs} +2 -2
- package/dist/{harnessState-Dn_S7fB9.mjs.map → harnessState-8lZda_8r.mjs.map} +1 -1
- package/dist/{harnessState-CCyBeutB.cjs → harnessState-BrmH0lG5.cjs} +2 -2
- package/dist/{harnessState-CCyBeutB.cjs.map → harnessState-BrmH0lG5.cjs.map} +1 -1
- package/dist/harnessState.cjs +1 -1
- package/dist/harnessState.d.mts +1 -1
- package/dist/harnessState.mjs +1 -1
- package/dist/{harnessStore-Bfn9XDXN.cjs → harnessStore-BinxGITh.cjs} +6 -6
- package/dist/harnessStore-BinxGITh.cjs.map +1 -0
- package/dist/{harnessStore-CuC3vDid.mjs → harnessStore-w8zHmJ_H.mjs} +7 -7
- package/dist/harnessStore-w8zHmJ_H.mjs.map +1 -0
- package/dist/harnessStore.cjs +1 -1
- package/dist/harnessStore.d.mts +1 -1
- package/dist/harnessStore.mjs +1 -1
- package/dist/{index-CDRGCYkg.d.mts → index-7RuIAWX1.d.mts} +2 -2
- package/dist/{index-CDRGCYkg.d.mts.map → index-7RuIAWX1.d.mts.map} +1 -1
- package/dist/{index-Dy_-m7gx.d.mts → index-BTOU4XiI.d.mts} +3 -3
- package/dist/{index-Dy_-m7gx.d.mts.map → index-BTOU4XiI.d.mts.map} +1 -1
- package/dist/{index-CQipJUsY.d.mts → index-CE5g27J6.d.mts} +5 -5
- package/dist/{index-CQipJUsY.d.mts.map → index-CE5g27J6.d.mts.map} +1 -1
- package/dist/{index-BYAK_Joy.d.mts → index-COokUToB.d.mts} +18 -18
- package/dist/index-COokUToB.d.mts.map +1 -0
- package/dist/{index-MN_Ps3my.d.mts → index-D3vGEYup.d.mts} +32 -32
- package/dist/index-D3vGEYup.d.mts.map +1 -0
- package/dist/{index-DlghOAkS.d.mts → index-DNEK9W6n.d.mts} +8 -8
- package/dist/index-DNEK9W6n.d.mts.map +1 -0
- package/dist/index-D_OtYtsl.d.mts +37 -0
- package/dist/index-D_OtYtsl.d.mts.map +1 -0
- package/dist/{index-DLThbP-M.d.mts → index-dYgF03lE.d.mts} +6 -6
- package/dist/{index-DLThbP-M.d.mts.map → index-dYgF03lE.d.mts.map} +1 -1
- package/dist/index-nVcEC1jO.d.mts +62 -0
- package/dist/index-nVcEC1jO.d.mts.map +1 -0
- package/dist/index.cjs +73 -62
- package/dist/index.d.mts +13 -13
- package/dist/index.mjs +14 -14
- package/dist/{init-CQzOIEMT.cjs → init-BTb1iBES.cjs} +48 -48
- package/dist/init-BTb1iBES.cjs.map +1 -0
- package/dist/{init-D25hkpDv.mjs → init-CuxfAN8g.mjs} +35 -35
- package/dist/init-CuxfAN8g.mjs.map +1 -0
- package/dist/init.cjs +8 -8
- package/dist/init.d.mts +2 -2
- package/dist/init.mjs +1 -1
- package/dist/{layeredConfig-BiomuF27.mjs → layeredConfig-BbkoIEfM.mjs} +12 -12
- package/dist/layeredConfig-BbkoIEfM.mjs.map +1 -0
- package/dist/{layeredConfig-DXyWwdIx.cjs → layeredConfig-Bs18dXQG.cjs} +21 -21
- package/dist/layeredConfig-Bs18dXQG.cjs.map +1 -0
- package/dist/layeredConfig.cjs +5 -5
- package/dist/layeredConfig.d.mts +4 -4
- package/dist/layeredConfig.d.mts.map +1 -1
- package/dist/layeredConfig.mjs +1 -1
- package/dist/{majorModes-kf1SVCev.cjs → majorModes-Ctsdi8QW.cjs} +6 -6
- package/dist/majorModes-Ctsdi8QW.cjs.map +1 -0
- package/dist/{majorModes-CXukUA3s.mjs → majorModes-Ddx975MG.mjs} +6 -6
- package/dist/majorModes-Ddx975MG.mjs.map +1 -0
- package/dist/majorModes.cjs +1 -1
- package/dist/majorModes.d.mts +1 -1
- package/dist/majorModes.mjs +1 -1
- package/dist/piConfig-Bq36PQFF.mjs.map +1 -1
- package/dist/{piConfig-Bx26HMb_.d.mts → piConfig-C9rGUqPe.d.mts} +3 -3
- package/dist/{piConfig-Bx26HMb_.d.mts.map → piConfig-C9rGUqPe.d.mts.map} +1 -1
- package/dist/piConfig-cluCie5i.cjs.map +1 -1
- package/dist/piConfig.d.mts +1 -1
- package/dist/piContext.cjs +27 -16
- package/dist/piContext.d.mts +3 -3
- package/dist/piContext.mjs +1 -1
- package/dist/{profiles-C5eiCYkU.mjs → profiles-CHict0x-.mjs} +4 -4
- package/dist/profiles-CHict0x-.mjs.map +1 -0
- package/dist/{profiles-DOBDxq4l.cjs → profiles-t2EUj0aB.cjs} +4 -4
- package/dist/profiles-t2EUj0aB.cjs.map +1 -0
- package/dist/profiles.cjs +1 -1
- package/dist/profiles.mjs +1 -1
- package/dist/selectionSwitch.cjs +3 -3
- package/dist/selectionSwitch.cjs.map +1 -1
- package/dist/selectionSwitch.d.mts +8 -8
- package/dist/selectionSwitch.d.mts.map +1 -1
- package/dist/selectionSwitch.mjs +3 -3
- package/dist/selectionSwitch.mjs.map +1 -1
- package/dist/{sessionConfig-Zl9gn98o.mjs → sessionConfig-DFQF618G.mjs} +46 -47
- package/dist/sessionConfig-DFQF618G.mjs.map +1 -0
- package/dist/{sessionConfig-CzKj6yBN.cjs → sessionConfig-DeP6pplT.cjs} +72 -85
- package/dist/sessionConfig-DeP6pplT.cjs.map +1 -0
- package/dist/types.cjs +2 -2
- package/dist/types.d.mts +2 -2
- package/dist/types.mjs +1 -1
- package/llms.txt +1 -1
- package/package.json +10 -10
- package/src/prompts/po-author-config/SKILL.md +4 -4
- package/src/prompts/po-author-config/agents/openai.yaml +1 -1
- package/src/prompts/po-author-config/references/config-contract.md +5 -5
- package/dist/config-CW-wChAT.mjs.map +0 -1
- package/dist/config-CzD87B5t.cjs.map +0 -1
- package/dist/config-D2HbBLzo.d.mts.map +0 -1
- package/dist/config-Hofqp1uK.mjs +0 -1
- package/dist/configPolicy-Ce1QKDxa.cjs.map +0 -1
- package/dist/configPolicy-DCQgF5-f.mjs.map +0 -1
- package/dist/configWriter-DXaci8le.mjs.map +0 -1
- package/dist/configWriter-crMObKDH.cjs.map +0 -1
- package/dist/core-DeEKLC4l.cjs.map +0 -1
- package/dist/core-Slanr8K3.mjs.map +0 -1
- package/dist/domains-9Vl18yDq.cjs.map +0 -1
- package/dist/domains-BkLewDJd.mjs.map +0 -1
- package/dist/harnessStore-Bfn9XDXN.cjs.map +0 -1
- package/dist/harnessStore-CuC3vDid.mjs.map +0 -1
- package/dist/index-3EALF8Jr.d.mts +0 -38
- package/dist/index-3EALF8Jr.d.mts.map +0 -1
- package/dist/index-BCC2y2XT.d.mts +0 -62
- package/dist/index-BCC2y2XT.d.mts.map +0 -1
- package/dist/index-BYAK_Joy.d.mts.map +0 -1
- package/dist/index-DlghOAkS.d.mts.map +0 -1
- package/dist/index-MN_Ps3my.d.mts.map +0 -1
- package/dist/init-CQzOIEMT.cjs.map +0 -1
- package/dist/init-D25hkpDv.mjs.map +0 -1
- package/dist/layeredConfig-BiomuF27.mjs.map +0 -1
- package/dist/layeredConfig-DXyWwdIx.cjs.map +0 -1
- package/dist/majorModes-CXukUA3s.mjs.map +0 -1
- package/dist/majorModes-kf1SVCev.cjs.map +0 -1
- package/dist/profiles-C5eiCYkU.mjs.map +0 -1
- package/dist/profiles-DOBDxq4l.cjs.map +0 -1
- package/dist/sessionConfig-CzKj6yBN.cjs.map +0 -1
- package/dist/sessionConfig-Zl9gn98o.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Typed runtime configuration and immutable session context for
|
|
|
4
4
|
[Po](https://www.npmjs.com/package/@agimon-ai/po).
|
|
5
5
|
|
|
6
6
|
This package is fixed core in the Po distribution. It loads `config.yaml`, validates supported
|
|
7
|
-
runtime settings, publishes the `
|
|
7
|
+
runtime settings, publishes the `po/config` Cordis service, and maintains selection state shared
|
|
8
8
|
by the major-mode, domain, and profile transition flows.
|
|
9
9
|
|
|
10
10
|
> **Alpha:** configuration contracts may change between releases.
|
|
@@ -66,15 +66,15 @@ the complete runtime schema and additional configuration details.
|
|
|
66
66
|
## Typed session context
|
|
67
67
|
|
|
68
68
|
The native session server root provides
|
|
69
|
-
`
|
|
69
|
+
`PO_CONFIG_SERVICE`. Consumers must access it under an owning service injection:
|
|
70
70
|
|
|
71
71
|
```ts
|
|
72
|
-
import {
|
|
72
|
+
import { PO_CONFIG_SERVICE, type PoConfigContext, requirePoConfigContext } from '@agimon-ai/po-config';
|
|
73
73
|
import type { Context } from '@deepseek-ai/cordis';
|
|
74
74
|
|
|
75
|
-
export function
|
|
76
|
-
context.inject([
|
|
77
|
-
consume(
|
|
75
|
+
export function consumePoConfig(context: Context, consume: (snapshot: PoConfigContext) => void): void {
|
|
76
|
+
context.inject([PO_CONFIG_SERVICE], (configContext) => {
|
|
77
|
+
consume(requirePoConfigContext(configContext));
|
|
78
78
|
});
|
|
79
79
|
}
|
|
80
80
|
```
|
|
@@ -108,9 +108,9 @@ The root and focused `/config` and `/piContext` exports provide runtime parsing,
|
|
|
108
108
|
session integration:
|
|
109
109
|
|
|
110
110
|
```ts
|
|
111
|
-
import {
|
|
111
|
+
import { loadPoConfig } from '@agimon-ai/po-config';
|
|
112
112
|
|
|
113
|
-
const settings =
|
|
113
|
+
const settings = loadPoConfig(process.cwd());
|
|
114
114
|
```
|
|
115
115
|
|
|
116
116
|
Pi-specific JSON settings are exposed through `/pi-config`; their types are exposed through `/config-schema`. The removed `/config/piConfig` and `/config/schema` paths have no aliases.
|
|
@@ -122,7 +122,7 @@ runtime Config authoring skill.
|
|
|
122
122
|
## Help
|
|
123
123
|
|
|
124
124
|
The package publishes `src/prompts/po-author-config`, links it from `llms.txt`, and registers
|
|
125
|
-
`po-author-config` with the `
|
|
125
|
+
`po-author-config` with the `po/help` Cordis service. The guidance is visible to the AI only
|
|
126
126
|
while the parent Help minor mode is active.
|
|
127
127
|
|
|
128
128
|
## Remote session app
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agentPluginMcp.cjs","names":["path","createHash","AGENT_PLUGIN_MCP_SCHEMA_URL","realContainedPath","fs","normalizeCommand","path","normalizeWorkingDirectory","normalizeServer","writeStagedInternalConfig","randomUUID","path","getOrThrow","nodeHost","writeFileAtomic"],"sources":["../src/services/agentPluginMcp/normalize.ts","../src/services/agentPluginMcp/sync.ts","../src/services/agentPluginMcp/index.ts"],"sourcesContent":["/** Pure Agent Plugin MCP normalisation shared by the async API and the deprecated Node-only sync shim. */\nimport { createHash } from 'node:crypto';\nimport path from 'node:path';\n\nimport { AGENT_PLUGIN_MCP_SCHEMA_URL, type DoomMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\n\n/** Same token grammar as node:http `validateHeaderName` (RFC 9110 tchar). */\nconst HTTP_TOKEN = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/u;\n/** Same rejected characters as node:http `validateHeaderValue`. */\nconst INVALID_HEADER_VALUE_CHARACTER = /[^\\t\\x20-\\x7e\\x80-\\xff]/u;\nconst IPV4_OCTET = '(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)';\nconst IPV4_ADDRESS = new RegExp(`^${IPV4_OCTET}(?:\\\\.${IPV4_OCTET}){3}$`, 'u');\n\nfunction isIPv4(value: string): boolean {\n return IPV4_ADDRESS.test(value);\n}\n\nexport const PRIVATE_FILE_MODE = 0o600;\nexport const PRIVATE_DIRECTORY_MODE = 0o700;\nexport const RESERVED_ENVIRONMENT_KEYS = new Set(['PLUGIN_ROOT', 'PLUGIN_DATA']);\nexport const PROXY_SERVER_ALIASES = new Set(['mcp-proxy', 'agiflow-proxy']);\n\nexport type JsonObject = Record<string, unknown>;\n\nexport interface AgentPluginMcpConfigSource {\n path: string;\n format: 'internal';\n cacheKey: string;\n}\n\nexport interface NormalizedAgentPluginMcpSource {\n /** Owner-only, content-addressed layer that bypasses Claude env interpolation. */\n configSource?: AgentPluginMcpConfigSource;\n /** Claude-compatible definitions for an external merged config. */\n claudeConfig: { mcpServers: Record<string, JsonObject> };\n serverNames: string[];\n droppedServers: string[];\n diagnostics: string[];\n}\n\nexport interface NormalizeAgentPluginMcpOptions {\n stagingDirectory: string;\n /** Empty and absent lists both mean keep every server. */\n allowedServers?: readonly string[];\n /** Doom strips nested wrappers; external-only callers may opt out. */\n stripProxyWrappers?: boolean;\n}\n\nexport interface NormalizedServer {\n internal: JsonObject;\n claude: JsonObject;\n}\n\nexport function isObject(value: unknown): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function onlyKeys(value: JsonObject, allowed: readonly string[], label: string): void {\n const unexpected = Object.keys(value).find((key) => !allowed.includes(key));\n if (unexpected) throw new Error(`${label} contains unsupported field \"${unexpected}\"`);\n}\n\nexport function nonEmptyString(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.length === 0) throw new Error(`${label} must be a non-empty string`);\n return value;\n}\n\nexport function optionalStringArray(value: unknown, label: string): string[] | undefined {\n if (value === undefined) return undefined;\n if (!Array.isArray(value)) throw new Error(`${label} must be an array of strings`);\n return value.map((item, index) => {\n if (typeof item !== 'string') throw new Error(`${label}[${index}] must be a string`);\n return item;\n });\n}\n\nfunction optionalStringRecord(value: unknown, label: string): Record<string, string> | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) throw new Error(`${label} must be an object of string values`);\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => {\n if (typeof item !== 'string') throw new Error(`${label}.${key} must be a string`);\n return [key, item];\n }),\n );\n}\n\nexport function expandPluginPlaceholders(value: string, pluginRoot: string, pluginDataDirectory: string): string {\n // The portable contract is a single, non-recursive replacement pass. An\n // unrecognised placeholder remains literal and mcp-proxy must not reinterpret it.\n return value.replace(/\\$\\{PLUGIN_(ROOT|DATA)\\}/gu, (placeholder) =>\n placeholder === '${PLUGIN_ROOT}' ? pluginRoot : pluginDataDirectory,\n );\n}\n\nexport function isInside(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\n}\n\nexport function normalizeEnvironment(\n value: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n): Record<string, string> {\n const declared = optionalStringRecord(value, 'env') ?? {};\n for (const key of Object.keys(declared)) {\n const reservedKey = process.platform === 'win32' ? key.toUpperCase() : key;\n if (RESERVED_ENVIRONMENT_KEYS.has(reservedKey)) {\n throw new Error(`env key \"${key}\" is reserved by Agent Plugins`);\n }\n }\n return {\n ...Object.fromEntries(\n Object.entries(declared).map(([key, item]) => [\n key,\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n ]),\n ),\n PLUGIN_ROOT: pluginRoot,\n PLUGIN_DATA: pluginDataDirectory,\n };\n}\n\nfunction isLoopbackHost(hostname: string): boolean {\n const bareHostname = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n if (bareHostname.toLowerCase() === 'localhost') return true;\n if (isIPv4(bareHostname)) return bareHostname.split('.')[0] === '127';\n return bareHostname === '::1';\n}\n\nexport function normalizeUrl(value: unknown): string {\n const raw = nonEmptyString(value, 'url');\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw new Error('url must be an absolute HTTP(S) URL');\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error('url must use http or https');\n }\n if (parsed.username || parsed.password) throw new Error('url must not contain user information');\n if (parsed.hash) throw new Error('url must not contain a fragment');\n if (parsed.protocol === 'http:' && !isLoopbackHost(parsed.hostname)) {\n throw new Error('non-loopback MCP URLs must use https');\n }\n return raw;\n}\n\nexport function normalizeHeaders(value: unknown): Record<string, string> | undefined {\n const headers = optionalStringRecord(value, 'headers');\n if (!headers) return undefined;\n const seen = new Set<string>();\n for (const [name, item] of Object.entries(headers)) {\n const canonical = name.toLowerCase();\n if (seen.has(canonical)) throw new Error(`headers contain duplicate name \"${name}\"`);\n seen.add(canonical);\n if (!HTTP_TOKEN.test(name) || INVALID_HEADER_VALUE_CHARACTER.test(item)) {\n throw new Error(`header \"${name}\" is invalid`);\n }\n }\n return headers;\n}\n\nexport function stagedInternalPath(\n source: DoomMcpAgentPluginProjectionSource,\n contents: string,\n stagingDirectory: string,\n): string {\n const digest = createHash('sha256')\n .update(source.sourceId)\n .update('\\0')\n .update(source.contentDigest)\n .update('\\0')\n .update(contents)\n .digest('hex')\n .slice(0, 20);\n return path.join(stagingDirectory, `agent-plugin-mcp-${digest}.internal.json`);\n}\n\nexport function emptyResult(diagnostic: string): NormalizedAgentPluginMcpSource {\n return {\n claudeConfig: { mcpServers: {} },\n serverNames: [],\n droppedServers: [],\n diagnostics: [diagnostic],\n };\n}\n\nexport function sourceLabel(source: DoomMcpAgentPluginProjectionSource): string {\n return `Agent Plugin MCP source \"${source.sourceId}\"`;\n}\n\n/** Checks the projection identity before any file is touched. */\nexport function assertProjectionSource(source: DoomMcpAgentPluginProjectionSource): void {\n if (source.mcpSchemaUrl !== AGENT_PLUGIN_MCP_SCHEMA_URL) {\n throw new Error(`unsupported schema \"${String(source.mcpSchemaUrl)}\"`);\n }\n if (!path.isAbsolute(source.pluginRoot) || !path.isAbsolute(source.pluginDataDirectory)) {\n throw new Error('pluginRoot and pluginDataDirectory must be absolute');\n }\n}\n\nexport function assertRootConfigPath(configPath: string, pluginRoot: string): void {\n if (path.dirname(configPath) !== pluginRoot || path.basename(configPath) !== 'mcp.json') {\n throw new Error('portable plugin config must be root mcp.json');\n }\n}\n\n/** Verifies the digest and document shape of the raw mcp.json bytes; returns its server map. */\nexport function parseMcpDocument(\n source: DoomMcpAgentPluginProjectionSource,\n bytes: Uint8Array,\n label: string,\n): Record<string, unknown> {\n const digest = createHash('sha256').update(bytes).digest('hex');\n if (digest !== source.contentDigest) throw new Error('content digest does not match the projection');\n const parsed: unknown = JSON.parse(new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes));\n if (!isObject(parsed)) throw new Error('document must be an object');\n onlyKeys(parsed, ['$schema', 'mcpServers'], label);\n if (parsed.$schema !== source.mcpSchemaUrl) throw new Error('$schema does not match the projected schema');\n if (!isObject(parsed.mcpServers)) throw new Error('mcpServers must be an object');\n return parsed.mcpServers;\n}\n\n/** Whether a declared server is skipped (empty name), dropped by the allowlist or wrapper rule, or normalised. */\nexport function serverDisposition(name: string, options: NormalizeAgentPluginMcpOptions): 'empty' | 'dropped' | 'keep' {\n if (!name) return 'empty';\n const allowed = options.allowedServers;\n const keepAll = !allowed || allowed.length === 0;\n const stripProxyWrappers = options.stripProxyWrappers ?? true;\n if ((!keepAll && !allowed.includes(name)) || (stripProxyWrappers && PROXY_SERVER_ALIASES.has(name))) return 'dropped';\n return 'keep';\n}\n\nexport function emptyServerDiagnostic(label: string): string {\n return `${label} contains an empty server name; that entry was skipped.`;\n}\n\nexport function skippedServerDiagnostic(label: string, name: string, error: unknown): string {\n return `${label} skipped server \"${name}\": ${error instanceof Error ? error.message : String(error)}`;\n}\n\nexport function disabledResult(label: string, error: unknown): NormalizedAgentPluginMcpSource {\n return emptyResult(`${label} was disabled: ${error instanceof Error ? error.message : String(error)}`);\n}\n\n/** The declared transport of one server; stdio declarations are also checked for unsupported fields. */\nexport function serverType(raw: unknown, name: string): string {\n if (!isObject(raw)) throw new Error('definition must be an object');\n const type = nonEmptyString(raw.type, 'type');\n if (type === 'stdio') onlyKeys(raw, ['type', 'command', 'args', 'env', 'cwd'], `server \"${name}\"`);\n return type;\n}\n\nexport function stdioServer(\n name: string,\n config: { command: string; args?: string[]; env: Record<string, string>; cwd: string },\n): NormalizedServer {\n return {\n internal: { name, transport: 'stdio', config },\n claude: { type: 'stdio', ...config },\n };\n}\n\n/** A streamable-http or sse server; any other type is unsupported. */\nexport function remoteServer(raw: JsonObject, name: string, type: string): NormalizedServer {\n if (type === 'streamable-http' || type === 'sse') {\n onlyKeys(raw, ['type', 'url', 'headers'], `server \"${name}\"`);\n const url = normalizeUrl(raw.url);\n const headers = normalizeHeaders(raw.headers);\n const transport = type === 'streamable-http' ? 'http' : 'sse';\n const config = { url, ...(headers ? { headers } : {}) };\n return {\n internal: { name, transport, config },\n claude: { type: transport, ...config },\n };\n }\n throw new Error(`unsupported transport type \"${type}\"`);\n}\n\nexport function stagedContents(internalServers: Record<string, JsonObject>): string {\n return `${JSON.stringify({ mcpServers: internalServers }, null, 2)}\\n`;\n}\n\nexport function stagedCacheKey(\n source: DoomMcpAgentPluginProjectionSource,\n configPath: string,\n contents: string,\n): string {\n return createHash('sha256')\n .update('agent-plugin-v1\\0')\n .update(source.sourceId)\n .update('\\0')\n .update(source.contentDigest)\n .update('\\0')\n .update(configPath)\n .update('\\0')\n .update(contents)\n .digest('hex');\n}\n\n/** The containment base and expanded path of a declared cwd, or undefined when the plugin root is the default. */\nexport function workingDirectoryCandidate(\n declared: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n): { base: string; candidate: string } | undefined {\n if (declared === undefined) return undefined;\n const cwd = nonEmptyString(declared, 'cwd');\n if (cwd.startsWith('./')) return { base: pluginRoot, candidate: path.resolve(pluginRoot, cwd) };\n const expanded = expandPluginPlaceholders(cwd, pluginRoot, pluginDataDirectory);\n if (cwd === '${PLUGIN_ROOT}' || cwd.startsWith('${PLUGIN_ROOT}/')) {\n return { base: pluginRoot, candidate: path.resolve(expanded) };\n }\n if (cwd === '${PLUGIN_DATA}' || cwd.startsWith('${PLUGIN_DATA}/')) {\n return { base: pluginDataDirectory, candidate: path.resolve(expanded) };\n }\n throw new Error('cwd must start with ./, ${PLUGIN_ROOT}, or ${PLUGIN_DATA}');\n}\n\n/** Rejects a command that is neither a bare executable name nor a ./ path; true when it must be resolved. */\nexport function isPluginRelativeCommand(command: string): boolean {\n if (command.startsWith('./')) return true;\n if (command === '.' || command === '..' || /[\\s/\\\\]/u.test(command)) {\n throw new Error('command must be a bare executable name or a ./ path inside the plugin');\n }\n return false;\n}\n","import { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { DoomMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\n\nimport {\n type JsonObject,\n type NormalizeAgentPluginMcpOptions,\n type NormalizedAgentPluginMcpSource,\n type NormalizedServer,\n PRIVATE_DIRECTORY_MODE,\n PRIVATE_FILE_MODE,\n assertProjectionSource,\n assertRootConfigPath,\n disabledResult,\n emptyServerDiagnostic,\n expandPluginPlaceholders,\n isInside,\n isPluginRelativeCommand,\n nonEmptyString,\n normalizeEnvironment,\n optionalStringArray,\n parseMcpDocument,\n remoteServer,\n serverDisposition,\n serverType,\n skippedServerDiagnostic,\n sourceLabel,\n stagedCacheKey,\n stagedContents,\n stagedInternalPath,\n stdioServer,\n workingDirectoryCandidate,\n} from './normalize';\n\nfunction realContainedPath(root: string, candidate: string, label: string): string {\n let realCandidate: string;\n try {\n realCandidate = fs.realpathSync(candidate);\n } catch {\n throw new Error(`${label} does not exist`);\n }\n if (!isInside(root, realCandidate)) throw new Error(`${label} escapes its allowed plugin directory`);\n return realCandidate;\n}\n\nfunction normalizeCommand(command: string, pluginRoot: string): string {\n if (!isPluginRelativeCommand(command)) return command;\n const resolved = realContainedPath(pluginRoot, path.resolve(pluginRoot, command), 'command');\n if (!fs.statSync(resolved).isFile()) throw new Error('command must resolve to a regular file');\n try {\n fs.accessSync(resolved, fs.constants.X_OK);\n } catch {\n throw new Error('command must resolve to an executable file');\n }\n return resolved;\n}\n\nfunction normalizeWorkingDirectory(declared: unknown, pluginRoot: string, pluginDataDirectory: string): string {\n const declaredCwd = workingDirectoryCandidate(declared, pluginRoot, pluginDataDirectory);\n if (!declaredCwd) return pluginRoot;\n const resolved = realContainedPath(declaredCwd.base, declaredCwd.candidate, 'cwd');\n if (!fs.statSync(resolved).isDirectory()) throw new Error('cwd must resolve to a directory');\n return resolved;\n}\n\nfunction normalizeServer(\n raw: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n name: string,\n): NormalizedServer {\n const type = serverType(raw, name);\n const declaration = raw as JsonObject;\n if (type !== 'stdio') return remoteServer(declaration, name, type);\n const command = normalizeCommand(nonEmptyString(declaration.command, 'command'), pluginRoot);\n const args = optionalStringArray(declaration.args, 'args')?.map((item) =>\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n );\n const env = normalizeEnvironment(declaration.env, pluginRoot, pluginDataDirectory);\n const cwd = normalizeWorkingDirectory(declaration.cwd, pluginRoot, pluginDataDirectory);\n return stdioServer(name, { command, ...(args ? { args } : {}), env, cwd });\n}\n\nfunction writeStagedInternalConfig(target: string, contents: string, stagingDirectory: string): void {\n fs.mkdirSync(stagingDirectory, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n fs.chmodSync(stagingDirectory, PRIVATE_DIRECTORY_MODE);\n const temporaryPath = `${target}.${process.pid}-${randomUUID()}.tmp`;\n try {\n fs.writeFileSync(temporaryPath, contents, { flag: 'wx', mode: PRIVATE_FILE_MODE });\n try {\n fs.renameSync(temporaryPath, target);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== 'EEXIST' && code !== 'EPERM') throw error;\n const stat = fs.lstatSync(target);\n if (stat.isSymbolicLink() || !stat.isFile() || fs.readFileSync(target, 'utf8') !== contents) {\n throw new Error('content-addressed staging path is occupied by different content');\n }\n }\n fs.chmodSync(target, PRIVATE_FILE_MODE);\n } finally {\n fs.rmSync(temporaryPath, { force: true });\n }\n}\n\n/**\n * Validates one Agent Plugins v1 `mcp.json` and stages a native mcp-proxy layer.\n *\n * Server validation is isolated: one malformed server is diagnosed and skipped.\n * Document/schema, source identity, or plugin-boundary failures reject the whole\n * source. Only the two portable plugin placeholders are expanded; the staged\n * layer is tagged `internal`, so legacy `${ENV}` interpolation cannot run again.\n *\n * @deprecated Node-only sync shim; use normalizeAgentPluginMcpSourceAsync. Removed in M2.\n */\nexport function normalizeAgentPluginMcpSource(\n source: DoomMcpAgentPluginProjectionSource,\n options: NormalizeAgentPluginMcpOptions,\n): NormalizedAgentPluginMcpSource {\n const label = sourceLabel(source);\n try {\n assertProjectionSource(source);\n const pluginRoot = fs.realpathSync(source.pluginRoot);\n try {\n const dataStat = fs.lstatSync(source.pluginDataDirectory);\n if (dataStat.isSymbolicLink() || !dataStat.isDirectory()) {\n throw new Error('pluginDataDirectory must be a real directory');\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n fs.mkdirSync(source.pluginDataDirectory, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n }\n fs.chmodSync(source.pluginDataDirectory, PRIVATE_DIRECTORY_MODE);\n fs.accessSync(source.pluginDataDirectory, fs.constants.W_OK);\n const pluginDataDirectory = fs.realpathSync(source.pluginDataDirectory);\n const configPath = realContainedPath(pluginRoot, source.configPath, 'mcp.json');\n assertRootConfigPath(configPath, pluginRoot);\n\n const servers = parseMcpDocument(source, fs.readFileSync(configPath), label);\n const internalServers = Object.create(null) as Record<string, JsonObject>;\n const claudeServers = Object.create(null) as Record<string, JsonObject>;\n const droppedServers: string[] = [];\n const diagnostics: string[] = [];\n\n for (const [name, rawServer] of Object.entries(servers)) {\n const disposition = serverDisposition(name, options);\n if (disposition === 'empty') {\n diagnostics.push(emptyServerDiagnostic(label));\n continue;\n }\n if (disposition === 'dropped') {\n droppedServers.push(name);\n continue;\n }\n try {\n const normalized = normalizeServer(rawServer, pluginRoot, pluginDataDirectory, name);\n internalServers[name] = normalized.internal;\n claudeServers[name] = normalized.claude;\n } catch (error) {\n droppedServers.push(name);\n diagnostics.push(skippedServerDiagnostic(label, name, error));\n }\n }\n\n const contents = stagedContents(internalServers);\n const target = stagedInternalPath(source, contents, options.stagingDirectory);\n writeStagedInternalConfig(target, contents, options.stagingDirectory);\n return {\n configSource: { path: target, format: 'internal', cacheKey: stagedCacheKey(source, configPath, contents) },\n claudeConfig: { mcpServers: claudeServers },\n serverNames: Object.keys(internalServers),\n droppedServers,\n diagnostics,\n };\n } catch (error) {\n return disabledResult(label, error);\n }\n}\n","import path from 'node:path';\n\nimport type { DoomMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\nimport { type FileSystem, getOrThrow, nodeHost, writeFileAtomic } from '@agimon-ai/po-core/platform';\n\nimport {\n type JsonObject,\n type NormalizeAgentPluginMcpOptions,\n type NormalizedAgentPluginMcpSource,\n type NormalizedServer,\n PRIVATE_DIRECTORY_MODE,\n PRIVATE_FILE_MODE,\n assertProjectionSource,\n assertRootConfigPath,\n disabledResult,\n emptyServerDiagnostic,\n expandPluginPlaceholders,\n isInside,\n isPluginRelativeCommand,\n nonEmptyString,\n normalizeEnvironment,\n optionalStringArray,\n parseMcpDocument,\n remoteServer,\n serverDisposition,\n serverType,\n skippedServerDiagnostic,\n sourceLabel,\n stagedCacheKey,\n stagedContents,\n stagedInternalPath,\n stdioServer,\n workingDirectoryCandidate,\n} from './normalize';\n\nexport type {\n AgentPluginMcpConfigSource,\n NormalizeAgentPluginMcpOptions,\n NormalizedAgentPluginMcpSource,\n} from './normalize';\nexport { normalizeAgentPluginMcpSource } from './sync';\n\ntype Context = Parameters<FileSystem['readTextFile']>[1];\n\nasync function realContainedPath(\n fs: FileSystem,\n root: string,\n candidate: string,\n label: string,\n context: Context,\n): Promise<string> {\n const real = await fs.canonicalPath(candidate, context);\n if (!real.ok) throw new Error(`${label} does not exist`);\n if (!isInside(root, real.value)) throw new Error(`${label} escapes its allowed plugin directory`);\n return real.value;\n}\n\nasync function normalizeCommand(\n fs: FileSystem,\n command: string,\n pluginRoot: string,\n context: Context,\n): Promise<string> {\n if (!isPluginRelativeCommand(command)) return command;\n const resolved = await realContainedPath(fs, pluginRoot, path.resolve(pluginRoot, command), 'command', context);\n if (getOrThrow(await fs.fileInfo(resolved, context)).kind !== 'file') {\n throw new Error('command must resolve to a regular file');\n }\n // Execute bits stand in for access(X_OK); the edge has no modes, so nodeHost reports none and the check is skipped.\n const mode = await nodeHost.fileMode(resolved);\n if (mode !== undefined && (mode & 0o111) === 0) throw new Error('command must resolve to an executable file');\n return resolved;\n}\n\nasync function normalizeWorkingDirectory(\n fs: FileSystem,\n declared: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n context: Context,\n): Promise<string> {\n const declaredCwd = workingDirectoryCandidate(declared, pluginRoot, pluginDataDirectory);\n if (!declaredCwd) return pluginRoot;\n const resolved = await realContainedPath(fs, declaredCwd.base, declaredCwd.candidate, 'cwd', context);\n if (getOrThrow(await fs.fileInfo(resolved, context)).kind !== 'directory') {\n throw new Error('cwd must resolve to a directory');\n }\n return resolved;\n}\n\nasync function normalizeServer(\n fs: FileSystem,\n raw: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n name: string,\n context: Context,\n): Promise<NormalizedServer> {\n const type = serverType(raw, name);\n const declaration = raw as JsonObject;\n if (type !== 'stdio') return remoteServer(declaration, name, type);\n const command = await normalizeCommand(fs, nonEmptyString(declaration.command, 'command'), pluginRoot, context);\n const args = optionalStringArray(declaration.args, 'args')?.map((item) =>\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n );\n const env = normalizeEnvironment(declaration.env, pluginRoot, pluginDataDirectory);\n const cwd = await normalizeWorkingDirectory(fs, declaration.cwd, pluginRoot, pluginDataDirectory, context);\n return stdioServer(name, { command, ...(args ? { args } : {}), env, cwd });\n}\n\n/** Owner-only plugin data directory; a symbolic link or non-directory rejects the source. */\nasync function preparePluginDataDirectory(fs: FileSystem, directory: string, context: Context): Promise<string> {\n const info = await fs.fileInfo(directory, context);\n if (info.ok) {\n if (info.value.kind !== 'directory') throw new Error('pluginDataDirectory must be a real directory');\n } else if (info.error.code === 'not_found') {\n getOrThrow(await fs.createDir(directory, { recursive: true }, context));\n } else {\n throw info.error;\n }\n await nodeHost.setMode(directory, PRIVATE_DIRECTORY_MODE);\n return getOrThrow(await fs.canonicalPath(directory, context));\n}\n\n/**\n * Content-addressed and owner-only. The name hashes the contents, so replacing an\n * existing staged file through a uniquely named temporary file never changes what it holds.\n */\nasync function writeStagedInternalConfig(\n fs: FileSystem,\n target: string,\n contents: string,\n stagingDirectory: string,\n context: Context,\n): Promise<void> {\n getOrThrow(await fs.createDir(stagingDirectory, { recursive: true }, context));\n await nodeHost.setMode(stagingDirectory, PRIVATE_DIRECTORY_MODE);\n await writeFileAtomic(fs, target, contents, context);\n await nodeHost.setMode(target, PRIVATE_FILE_MODE);\n}\n\n/**\n * Validates one Agent Plugins v1 `mcp.json` and stages a native mcp-proxy layer,\n * reading and writing through the injected file system.\n *\n * Server validation is isolated: one malformed server is diagnosed and skipped.\n * Document/schema, source identity, or plugin-boundary failures reject the whole\n * source. Only the two portable plugin placeholders are expanded; the staged\n * layer is tagged `internal`, so legacy `${ENV}` interpolation cannot run again.\n */\nexport async function normalizeAgentPluginMcpSourceAsync(\n fs: FileSystem,\n source: DoomMcpAgentPluginProjectionSource,\n options: NormalizeAgentPluginMcpOptions,\n context: Context,\n): Promise<NormalizedAgentPluginMcpSource> {\n const label = sourceLabel(source);\n try {\n assertProjectionSource(source);\n const pluginRoot = getOrThrow(await fs.canonicalPath(source.pluginRoot, context));\n const pluginDataDirectory = await preparePluginDataDirectory(fs, source.pluginDataDirectory, context);\n const configPath = await realContainedPath(fs, pluginRoot, source.configPath, 'mcp.json', context);\n assertRootConfigPath(configPath, pluginRoot);\n\n const bytes = getOrThrow(await fs.readBinaryFile(configPath, context));\n const servers = parseMcpDocument(source, bytes, label);\n const internalServers = Object.create(null) as Record<string, JsonObject>;\n const claudeServers = Object.create(null) as Record<string, JsonObject>;\n const droppedServers: string[] = [];\n const diagnostics: string[] = [];\n\n for (const [name, rawServer] of Object.entries(servers)) {\n const disposition = serverDisposition(name, options);\n if (disposition === 'empty') {\n diagnostics.push(emptyServerDiagnostic(label));\n continue;\n }\n if (disposition === 'dropped') {\n droppedServers.push(name);\n continue;\n }\n try {\n const normalized = await normalizeServer(fs, rawServer, pluginRoot, pluginDataDirectory, name, context);\n internalServers[name] = normalized.internal;\n claudeServers[name] = normalized.claude;\n } catch (error) {\n droppedServers.push(name);\n diagnostics.push(skippedServerDiagnostic(label, name, error));\n }\n }\n\n const contents = stagedContents(internalServers);\n const target = stagedInternalPath(source, contents, options.stagingDirectory);\n await writeStagedInternalConfig(fs, target, contents, options.stagingDirectory, context);\n return {\n configSource: { path: target, format: 'internal', cacheKey: stagedCacheKey(source, configPath, contents) },\n claudeConfig: { mcpServers: claudeServers },\n serverNames: Object.keys(internalServers),\n droppedServers,\n diagnostics,\n };\n } catch (error) {\n return disabledResult(label, error);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAOA,MAAM,aAAa;;AAEnB,MAAM,iCAAiC;AACvC,MAAM,aAAa;AACnB,MAAM,eAAe,IAAI,OAAO,IAAI,WAAW,QAAQ,WAAW,QAAQ,GAAG;AAE7E,SAAS,OAAO,OAAwB;CACtC,OAAO,aAAa,KAAK,KAAK;AAChC;AAIA,MAAa,4CAA4B,IAAI,IAAI,CAAC,eAAe,aAAa,CAAC;AAC/E,MAAa,uCAAuB,IAAI,IAAI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AAS,mBAAmB,QAAQ,UAAU,QAAQ,gBAAgB;EAC5E,MAAM,0BAA0B,IAAI,QAAQ,UAAU,QAAQ,kBAAkB,OAAO;EACvF,OAAO;GACL,cAAc;IAAE,MAAM;IAAQ,QAAQ;IAAY,UAAU,eAAe,QAAQ,YAAY,QAAQ;GAAE;GACzG,cAAc,EAAE,YAAY,cAAc;GAC1C,aAAa,OAAO,KAAK,eAAe;GACxC;GACA;EACF;CACF,SAAS,OAAO;EACd,OAAO,eAAe,OAAO,KAAK;CACpC;AACF"}
|
|
1
|
+
{"version":3,"file":"agentPluginMcp.cjs","names":["path","createHash","AGENT_PLUGIN_MCP_SCHEMA_URL","realContainedPath","fs","normalizeCommand","path","normalizeWorkingDirectory","normalizeServer","writeStagedInternalConfig","randomUUID","path","getOrThrow","nodeHost","writeFileAtomic"],"sources":["../src/services/agentPluginMcp/normalize.ts","../src/services/agentPluginMcp/sync.ts","../src/services/agentPluginMcp/index.ts"],"sourcesContent":["/** Pure Agent Plugin MCP normalisation shared by the async API and the deprecated Node-only sync shim. */\nimport { createHash } from 'node:crypto';\nimport path from 'node:path';\n\nimport { AGENT_PLUGIN_MCP_SCHEMA_URL, type PoMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\n\n/** Same token grammar as node:http `validateHeaderName` (RFC 9110 tchar). */\nconst HTTP_TOKEN = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/u;\n/** Same rejected characters as node:http `validateHeaderValue`. */\nconst INVALID_HEADER_VALUE_CHARACTER = /[^\\t\\x20-\\x7e\\x80-\\xff]/u;\nconst IPV4_OCTET = '(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)';\nconst IPV4_ADDRESS = new RegExp(`^${IPV4_OCTET}(?:\\\\.${IPV4_OCTET}){3}$`, 'u');\n\nfunction isIPv4(value: string): boolean {\n return IPV4_ADDRESS.test(value);\n}\n\nexport const PRIVATE_FILE_MODE = 0o600;\nexport const PRIVATE_DIRECTORY_MODE = 0o700;\nexport const RESERVED_ENVIRONMENT_KEYS = new Set(['PLUGIN_ROOT', 'PLUGIN_DATA']);\nexport const PROXY_SERVER_ALIASES = new Set(['mcp-proxy', 'agiflow-proxy']);\n\nexport type JsonObject = Record<string, unknown>;\n\nexport interface AgentPluginMcpConfigSource {\n path: string;\n format: 'internal';\n cacheKey: string;\n}\n\nexport interface NormalizedAgentPluginMcpSource {\n /** Owner-only, content-addressed layer that bypasses Claude env interpolation. */\n configSource?: AgentPluginMcpConfigSource;\n /** Claude-compatible definitions for an external merged config. */\n claudeConfig: { mcpServers: Record<string, JsonObject> };\n serverNames: string[];\n droppedServers: string[];\n diagnostics: string[];\n}\n\nexport interface NormalizeAgentPluginMcpOptions {\n stagingDirectory: string;\n /** Empty and absent lists both mean keep every server. */\n allowedServers?: readonly string[];\n /** Po strips nested wrappers; external-only callers may opt out. */\n stripProxyWrappers?: boolean;\n}\n\nexport interface NormalizedServer {\n internal: JsonObject;\n claude: JsonObject;\n}\n\nexport function isObject(value: unknown): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function onlyKeys(value: JsonObject, allowed: readonly string[], label: string): void {\n const unexpected = Object.keys(value).find((key) => !allowed.includes(key));\n if (unexpected) throw new Error(`${label} contains unsupported field \"${unexpected}\"`);\n}\n\nexport function nonEmptyString(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.length === 0) throw new Error(`${label} must be a non-empty string`);\n return value;\n}\n\nexport function optionalStringArray(value: unknown, label: string): string[] | undefined {\n if (value === undefined) return undefined;\n if (!Array.isArray(value)) throw new Error(`${label} must be an array of strings`);\n return value.map((item, index) => {\n if (typeof item !== 'string') throw new Error(`${label}[${index}] must be a string`);\n return item;\n });\n}\n\nfunction optionalStringRecord(value: unknown, label: string): Record<string, string> | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) throw new Error(`${label} must be an object of string values`);\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => {\n if (typeof item !== 'string') throw new Error(`${label}.${key} must be a string`);\n return [key, item];\n }),\n );\n}\n\nexport function expandPluginPlaceholders(value: string, pluginRoot: string, pluginDataDirectory: string): string {\n // The portable contract is a single, non-recursive replacement pass. An\n // unrecognised placeholder remains literal and mcp-proxy must not reinterpret it.\n return value.replace(/\\$\\{PLUGIN_(ROOT|DATA)\\}/gu, (placeholder) =>\n placeholder === '${PLUGIN_ROOT}' ? pluginRoot : pluginDataDirectory,\n );\n}\n\nexport function isInside(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\n}\n\nexport function normalizeEnvironment(\n value: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n): Record<string, string> {\n const declared = optionalStringRecord(value, 'env') ?? {};\n for (const key of Object.keys(declared)) {\n const reservedKey = process.platform === 'win32' ? key.toUpperCase() : key;\n if (RESERVED_ENVIRONMENT_KEYS.has(reservedKey)) {\n throw new Error(`env key \"${key}\" is reserved by Agent Plugins`);\n }\n }\n return {\n ...Object.fromEntries(\n Object.entries(declared).map(([key, item]) => [\n key,\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n ]),\n ),\n PLUGIN_ROOT: pluginRoot,\n PLUGIN_DATA: pluginDataDirectory,\n };\n}\n\nfunction isLoopbackHost(hostname: string): boolean {\n const bareHostname = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n if (bareHostname.toLowerCase() === 'localhost') return true;\n if (isIPv4(bareHostname)) return bareHostname.split('.')[0] === '127';\n return bareHostname === '::1';\n}\n\nexport function normalizeUrl(value: unknown): string {\n const raw = nonEmptyString(value, 'url');\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw new Error('url must be an absolute HTTP(S) URL');\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error('url must use http or https');\n }\n if (parsed.username || parsed.password) throw new Error('url must not contain user information');\n if (parsed.hash) throw new Error('url must not contain a fragment');\n if (parsed.protocol === 'http:' && !isLoopbackHost(parsed.hostname)) {\n throw new Error('non-loopback MCP URLs must use https');\n }\n return raw;\n}\n\nexport function normalizeHeaders(value: unknown): Record<string, string> | undefined {\n const headers = optionalStringRecord(value, 'headers');\n if (!headers) return undefined;\n const seen = new Set<string>();\n for (const [name, item] of Object.entries(headers)) {\n const canonical = name.toLowerCase();\n if (seen.has(canonical)) throw new Error(`headers contain duplicate name \"${name}\"`);\n seen.add(canonical);\n if (!HTTP_TOKEN.test(name) || INVALID_HEADER_VALUE_CHARACTER.test(item)) {\n throw new Error(`header \"${name}\" is invalid`);\n }\n }\n return headers;\n}\n\nexport function stagedInternalPath(\n source: PoMcpAgentPluginProjectionSource,\n contents: string,\n stagingDirectory: string,\n): string {\n const digest = createHash('sha256')\n .update(source.sourceId)\n .update('\\0')\n .update(source.contentDigest)\n .update('\\0')\n .update(contents)\n .digest('hex')\n .slice(0, 20);\n return path.join(stagingDirectory, `agent-plugin-mcp-${digest}.internal.json`);\n}\n\nexport function emptyResult(diagnostic: string): NormalizedAgentPluginMcpSource {\n return {\n claudeConfig: { mcpServers: {} },\n serverNames: [],\n droppedServers: [],\n diagnostics: [diagnostic],\n };\n}\n\nexport function sourceLabel(source: PoMcpAgentPluginProjectionSource): string {\n return `Agent Plugin MCP source \"${source.sourceId}\"`;\n}\n\n/** Checks the projection identity before any file is touched. */\nexport function assertProjectionSource(source: PoMcpAgentPluginProjectionSource): void {\n if (source.mcpSchemaUrl !== AGENT_PLUGIN_MCP_SCHEMA_URL) {\n throw new Error(`unsupported schema \"${String(source.mcpSchemaUrl)}\"`);\n }\n if (!path.isAbsolute(source.pluginRoot) || !path.isAbsolute(source.pluginDataDirectory)) {\n throw new Error('pluginRoot and pluginDataDirectory must be absolute');\n }\n}\n\nexport function assertRootConfigPath(configPath: string, pluginRoot: string): void {\n if (path.dirname(configPath) !== pluginRoot || path.basename(configPath) !== 'mcp.json') {\n throw new Error('portable plugin config must be root mcp.json');\n }\n}\n\n/** Verifies the digest and document shape of the raw mcp.json bytes; returns its server map. */\nexport function parseMcpDocument(\n source: PoMcpAgentPluginProjectionSource,\n bytes: Uint8Array,\n label: string,\n): Record<string, unknown> {\n const digest = createHash('sha256').update(bytes).digest('hex');\n if (digest !== source.contentDigest) throw new Error('content digest does not match the projection');\n const parsed: unknown = JSON.parse(new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes));\n if (!isObject(parsed)) throw new Error('document must be an object');\n onlyKeys(parsed, ['$schema', 'mcpServers'], label);\n if (parsed.$schema !== source.mcpSchemaUrl) throw new Error('$schema does not match the projected schema');\n if (!isObject(parsed.mcpServers)) throw new Error('mcpServers must be an object');\n return parsed.mcpServers;\n}\n\n/** Whether a declared server is skipped (empty name), dropped by the allowlist or wrapper rule, or normalised. */\nexport function serverDisposition(name: string, options: NormalizeAgentPluginMcpOptions): 'empty' | 'dropped' | 'keep' {\n if (!name) return 'empty';\n const allowed = options.allowedServers;\n const keepAll = !allowed || allowed.length === 0;\n const stripProxyWrappers = options.stripProxyWrappers ?? true;\n if ((!keepAll && !allowed.includes(name)) || (stripProxyWrappers && PROXY_SERVER_ALIASES.has(name))) return 'dropped';\n return 'keep';\n}\n\nexport function emptyServerDiagnostic(label: string): string {\n return `${label} contains an empty server name; that entry was skipped.`;\n}\n\nexport function skippedServerDiagnostic(label: string, name: string, error: unknown): string {\n return `${label} skipped server \"${name}\": ${error instanceof Error ? error.message : String(error)}`;\n}\n\nexport function disabledResult(label: string, error: unknown): NormalizedAgentPluginMcpSource {\n return emptyResult(`${label} was disabled: ${error instanceof Error ? error.message : String(error)}`);\n}\n\n/** The declared transport of one server; stdio declarations are also checked for unsupported fields. */\nexport function serverType(raw: unknown, name: string): string {\n if (!isObject(raw)) throw new Error('definition must be an object');\n const type = nonEmptyString(raw.type, 'type');\n if (type === 'stdio') onlyKeys(raw, ['type', 'command', 'args', 'env', 'cwd'], `server \"${name}\"`);\n return type;\n}\n\nexport function stdioServer(\n name: string,\n config: { command: string; args?: string[]; env: Record<string, string>; cwd: string },\n): NormalizedServer {\n return {\n internal: { name, transport: 'stdio', config },\n claude: { type: 'stdio', ...config },\n };\n}\n\n/** A streamable-http or sse server; any other type is unsupported. */\nexport function remoteServer(raw: JsonObject, name: string, type: string): NormalizedServer {\n if (type === 'streamable-http' || type === 'sse') {\n onlyKeys(raw, ['type', 'url', 'headers'], `server \"${name}\"`);\n const url = normalizeUrl(raw.url);\n const headers = normalizeHeaders(raw.headers);\n const transport = type === 'streamable-http' ? 'http' : 'sse';\n const config = { url, ...(headers ? { headers } : {}) };\n return {\n internal: { name, transport, config },\n claude: { type: transport, ...config },\n };\n }\n throw new Error(`unsupported transport type \"${type}\"`);\n}\n\nexport function stagedContents(internalServers: Record<string, JsonObject>): string {\n return `${JSON.stringify({ mcpServers: internalServers }, null, 2)}\\n`;\n}\n\nexport function stagedCacheKey(source: PoMcpAgentPluginProjectionSource, configPath: string, contents: string): string {\n return createHash('sha256')\n .update('agent-plugin-v1\\0')\n .update(source.sourceId)\n .update('\\0')\n .update(source.contentDigest)\n .update('\\0')\n .update(configPath)\n .update('\\0')\n .update(contents)\n .digest('hex');\n}\n\n/** The containment base and expanded path of a declared cwd, or undefined when the plugin root is the default. */\nexport function workingDirectoryCandidate(\n declared: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n): { base: string; candidate: string } | undefined {\n if (declared === undefined) return undefined;\n const cwd = nonEmptyString(declared, 'cwd');\n if (cwd.startsWith('./')) return { base: pluginRoot, candidate: path.resolve(pluginRoot, cwd) };\n const expanded = expandPluginPlaceholders(cwd, pluginRoot, pluginDataDirectory);\n if (cwd === '${PLUGIN_ROOT}' || cwd.startsWith('${PLUGIN_ROOT}/')) {\n return { base: pluginRoot, candidate: path.resolve(expanded) };\n }\n if (cwd === '${PLUGIN_DATA}' || cwd.startsWith('${PLUGIN_DATA}/')) {\n return { base: pluginDataDirectory, candidate: path.resolve(expanded) };\n }\n throw new Error('cwd must start with ./, ${PLUGIN_ROOT}, or ${PLUGIN_DATA}');\n}\n\n/** Rejects a command that is neither a bare executable name nor a ./ path; true when it must be resolved. */\nexport function isPluginRelativeCommand(command: string): boolean {\n if (command.startsWith('./')) return true;\n if (command === '.' || command === '..' || /[\\s/\\\\]/u.test(command)) {\n throw new Error('command must be a bare executable name or a ./ path inside the plugin');\n }\n return false;\n}\n","import { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { PoMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\n\nimport {\n type JsonObject,\n type NormalizeAgentPluginMcpOptions,\n type NormalizedAgentPluginMcpSource,\n type NormalizedServer,\n PRIVATE_DIRECTORY_MODE,\n PRIVATE_FILE_MODE,\n assertProjectionSource,\n assertRootConfigPath,\n disabledResult,\n emptyServerDiagnostic,\n expandPluginPlaceholders,\n isInside,\n isPluginRelativeCommand,\n nonEmptyString,\n normalizeEnvironment,\n optionalStringArray,\n parseMcpDocument,\n remoteServer,\n serverDisposition,\n serverType,\n skippedServerDiagnostic,\n sourceLabel,\n stagedCacheKey,\n stagedContents,\n stagedInternalPath,\n stdioServer,\n workingDirectoryCandidate,\n} from './normalize';\n\nfunction realContainedPath(root: string, candidate: string, label: string): string {\n let realCandidate: string;\n try {\n realCandidate = fs.realpathSync(candidate);\n } catch {\n throw new Error(`${label} does not exist`);\n }\n if (!isInside(root, realCandidate)) throw new Error(`${label} escapes its allowed plugin directory`);\n return realCandidate;\n}\n\nfunction normalizeCommand(command: string, pluginRoot: string): string {\n if (!isPluginRelativeCommand(command)) return command;\n const resolved = realContainedPath(pluginRoot, path.resolve(pluginRoot, command), 'command');\n if (!fs.statSync(resolved).isFile()) throw new Error('command must resolve to a regular file');\n try {\n fs.accessSync(resolved, fs.constants.X_OK);\n } catch {\n throw new Error('command must resolve to an executable file');\n }\n return resolved;\n}\n\nfunction normalizeWorkingDirectory(declared: unknown, pluginRoot: string, pluginDataDirectory: string): string {\n const declaredCwd = workingDirectoryCandidate(declared, pluginRoot, pluginDataDirectory);\n if (!declaredCwd) return pluginRoot;\n const resolved = realContainedPath(declaredCwd.base, declaredCwd.candidate, 'cwd');\n if (!fs.statSync(resolved).isDirectory()) throw new Error('cwd must resolve to a directory');\n return resolved;\n}\n\nfunction normalizeServer(\n raw: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n name: string,\n): NormalizedServer {\n const type = serverType(raw, name);\n const declaration = raw as JsonObject;\n if (type !== 'stdio') return remoteServer(declaration, name, type);\n const command = normalizeCommand(nonEmptyString(declaration.command, 'command'), pluginRoot);\n const args = optionalStringArray(declaration.args, 'args')?.map((item) =>\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n );\n const env = normalizeEnvironment(declaration.env, pluginRoot, pluginDataDirectory);\n const cwd = normalizeWorkingDirectory(declaration.cwd, pluginRoot, pluginDataDirectory);\n return stdioServer(name, { command, ...(args ? { args } : {}), env, cwd });\n}\n\nfunction writeStagedInternalConfig(target: string, contents: string, stagingDirectory: string): void {\n fs.mkdirSync(stagingDirectory, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n fs.chmodSync(stagingDirectory, PRIVATE_DIRECTORY_MODE);\n const temporaryPath = `${target}.${process.pid}-${randomUUID()}.tmp`;\n try {\n fs.writeFileSync(temporaryPath, contents, { flag: 'wx', mode: PRIVATE_FILE_MODE });\n try {\n fs.renameSync(temporaryPath, target);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== 'EEXIST' && code !== 'EPERM') throw error;\n const stat = fs.lstatSync(target);\n if (stat.isSymbolicLink() || !stat.isFile() || fs.readFileSync(target, 'utf8') !== contents) {\n throw new Error('content-addressed staging path is occupied by different content');\n }\n }\n fs.chmodSync(target, PRIVATE_FILE_MODE);\n } finally {\n fs.rmSync(temporaryPath, { force: true });\n }\n}\n\n/**\n * Validates one Agent Plugins v1 `mcp.json` and stages a native mcp-proxy layer.\n *\n * Server validation is isolated: one malformed server is diagnosed and skipped.\n * Document/schema, source identity, or plugin-boundary failures reject the whole\n * source. Only the two portable plugin placeholders are expanded; the staged\n * layer is tagged `internal`, so legacy `${ENV}` interpolation cannot run again.\n *\n * @deprecated Node-only sync shim; use normalizeAgentPluginMcpSourceAsync. Removed in M2.\n */\nexport function normalizeAgentPluginMcpSource(\n source: PoMcpAgentPluginProjectionSource,\n options: NormalizeAgentPluginMcpOptions,\n): NormalizedAgentPluginMcpSource {\n const label = sourceLabel(source);\n try {\n assertProjectionSource(source);\n const pluginRoot = fs.realpathSync(source.pluginRoot);\n try {\n const dataStat = fs.lstatSync(source.pluginDataDirectory);\n if (dataStat.isSymbolicLink() || !dataStat.isDirectory()) {\n throw new Error('pluginDataDirectory must be a real directory');\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n fs.mkdirSync(source.pluginDataDirectory, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n }\n fs.chmodSync(source.pluginDataDirectory, PRIVATE_DIRECTORY_MODE);\n fs.accessSync(source.pluginDataDirectory, fs.constants.W_OK);\n const pluginDataDirectory = fs.realpathSync(source.pluginDataDirectory);\n const configPath = realContainedPath(pluginRoot, source.configPath, 'mcp.json');\n assertRootConfigPath(configPath, pluginRoot);\n\n const servers = parseMcpDocument(source, fs.readFileSync(configPath), label);\n const internalServers = Object.create(null) as Record<string, JsonObject>;\n const claudeServers = Object.create(null) as Record<string, JsonObject>;\n const droppedServers: string[] = [];\n const diagnostics: string[] = [];\n\n for (const [name, rawServer] of Object.entries(servers)) {\n const disposition = serverDisposition(name, options);\n if (disposition === 'empty') {\n diagnostics.push(emptyServerDiagnostic(label));\n continue;\n }\n if (disposition === 'dropped') {\n droppedServers.push(name);\n continue;\n }\n try {\n const normalized = normalizeServer(rawServer, pluginRoot, pluginDataDirectory, name);\n internalServers[name] = normalized.internal;\n claudeServers[name] = normalized.claude;\n } catch (error) {\n droppedServers.push(name);\n diagnostics.push(skippedServerDiagnostic(label, name, error));\n }\n }\n\n const contents = stagedContents(internalServers);\n const target = stagedInternalPath(source, contents, options.stagingDirectory);\n writeStagedInternalConfig(target, contents, options.stagingDirectory);\n return {\n configSource: { path: target, format: 'internal', cacheKey: stagedCacheKey(source, configPath, contents) },\n claudeConfig: { mcpServers: claudeServers },\n serverNames: Object.keys(internalServers),\n droppedServers,\n diagnostics,\n };\n } catch (error) {\n return disabledResult(label, error);\n }\n}\n","import path from 'node:path';\n\nimport type { PoMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\nimport { type FileSystem, getOrThrow, nodeHost, writeFileAtomic } from '@agimon-ai/po-core/platform';\n\nimport {\n type JsonObject,\n type NormalizeAgentPluginMcpOptions,\n type NormalizedAgentPluginMcpSource,\n type NormalizedServer,\n PRIVATE_DIRECTORY_MODE,\n PRIVATE_FILE_MODE,\n assertProjectionSource,\n assertRootConfigPath,\n disabledResult,\n emptyServerDiagnostic,\n expandPluginPlaceholders,\n isInside,\n isPluginRelativeCommand,\n nonEmptyString,\n normalizeEnvironment,\n optionalStringArray,\n parseMcpDocument,\n remoteServer,\n serverDisposition,\n serverType,\n skippedServerDiagnostic,\n sourceLabel,\n stagedCacheKey,\n stagedContents,\n stagedInternalPath,\n stdioServer,\n workingDirectoryCandidate,\n} from './normalize';\n\nexport type {\n AgentPluginMcpConfigSource,\n NormalizeAgentPluginMcpOptions,\n NormalizedAgentPluginMcpSource,\n} from './normalize';\nexport { normalizeAgentPluginMcpSource } from './sync';\n\ntype Context = Parameters<FileSystem['readTextFile']>[1];\n\nasync function realContainedPath(\n fs: FileSystem,\n root: string,\n candidate: string,\n label: string,\n context: Context,\n): Promise<string> {\n const real = await fs.canonicalPath(candidate, context);\n if (!real.ok) throw new Error(`${label} does not exist`);\n if (!isInside(root, real.value)) throw new Error(`${label} escapes its allowed plugin directory`);\n return real.value;\n}\n\nasync function normalizeCommand(\n fs: FileSystem,\n command: string,\n pluginRoot: string,\n context: Context,\n): Promise<string> {\n if (!isPluginRelativeCommand(command)) return command;\n const resolved = await realContainedPath(fs, pluginRoot, path.resolve(pluginRoot, command), 'command', context);\n if (getOrThrow(await fs.fileInfo(resolved, context)).kind !== 'file') {\n throw new Error('command must resolve to a regular file');\n }\n // Execute bits stand in for access(X_OK); the edge has no modes, so nodeHost reports none and the check is skipped.\n const mode = await nodeHost.fileMode(resolved);\n if (mode !== undefined && (mode & 0o111) === 0) throw new Error('command must resolve to an executable file');\n return resolved;\n}\n\nasync function normalizeWorkingDirectory(\n fs: FileSystem,\n declared: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n context: Context,\n): Promise<string> {\n const declaredCwd = workingDirectoryCandidate(declared, pluginRoot, pluginDataDirectory);\n if (!declaredCwd) return pluginRoot;\n const resolved = await realContainedPath(fs, declaredCwd.base, declaredCwd.candidate, 'cwd', context);\n if (getOrThrow(await fs.fileInfo(resolved, context)).kind !== 'directory') {\n throw new Error('cwd must resolve to a directory');\n }\n return resolved;\n}\n\nasync function normalizeServer(\n fs: FileSystem,\n raw: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n name: string,\n context: Context,\n): Promise<NormalizedServer> {\n const type = serverType(raw, name);\n const declaration = raw as JsonObject;\n if (type !== 'stdio') return remoteServer(declaration, name, type);\n const command = await normalizeCommand(fs, nonEmptyString(declaration.command, 'command'), pluginRoot, context);\n const args = optionalStringArray(declaration.args, 'args')?.map((item) =>\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n );\n const env = normalizeEnvironment(declaration.env, pluginRoot, pluginDataDirectory);\n const cwd = await normalizeWorkingDirectory(fs, declaration.cwd, pluginRoot, pluginDataDirectory, context);\n return stdioServer(name, { command, ...(args ? { args } : {}), env, cwd });\n}\n\n/** Owner-only plugin data directory; a symbolic link or non-directory rejects the source. */\nasync function preparePluginDataDirectory(fs: FileSystem, directory: string, context: Context): Promise<string> {\n const info = await fs.fileInfo(directory, context);\n if (info.ok) {\n if (info.value.kind !== 'directory') throw new Error('pluginDataDirectory must be a real directory');\n } else if (info.error.code === 'not_found') {\n getOrThrow(await fs.createDir(directory, { recursive: true }, context));\n } else {\n throw info.error;\n }\n await nodeHost.setMode(directory, PRIVATE_DIRECTORY_MODE);\n return getOrThrow(await fs.canonicalPath(directory, context));\n}\n\n/**\n * Content-addressed and owner-only. The name hashes the contents, so replacing an\n * existing staged file through a uniquely named temporary file never changes what it holds.\n */\nasync function writeStagedInternalConfig(\n fs: FileSystem,\n target: string,\n contents: string,\n stagingDirectory: string,\n context: Context,\n): Promise<void> {\n getOrThrow(await fs.createDir(stagingDirectory, { recursive: true }, context));\n await nodeHost.setMode(stagingDirectory, PRIVATE_DIRECTORY_MODE);\n await writeFileAtomic(fs, target, contents, context);\n await nodeHost.setMode(target, PRIVATE_FILE_MODE);\n}\n\n/**\n * Validates one Agent Plugins v1 `mcp.json` and stages a native mcp-proxy layer,\n * reading and writing through the injected file system.\n *\n * Server validation is isolated: one malformed server is diagnosed and skipped.\n * Document/schema, source identity, or plugin-boundary failures reject the whole\n * source. Only the two portable plugin placeholders are expanded; the staged\n * layer is tagged `internal`, so legacy `${ENV}` interpolation cannot run again.\n */\nexport async function normalizeAgentPluginMcpSourceAsync(\n fs: FileSystem,\n source: PoMcpAgentPluginProjectionSource,\n options: NormalizeAgentPluginMcpOptions,\n context: Context,\n): Promise<NormalizedAgentPluginMcpSource> {\n const label = sourceLabel(source);\n try {\n assertProjectionSource(source);\n const pluginRoot = getOrThrow(await fs.canonicalPath(source.pluginRoot, context));\n const pluginDataDirectory = await preparePluginDataDirectory(fs, source.pluginDataDirectory, context);\n const configPath = await realContainedPath(fs, pluginRoot, source.configPath, 'mcp.json', context);\n assertRootConfigPath(configPath, pluginRoot);\n\n const bytes = getOrThrow(await fs.readBinaryFile(configPath, context));\n const servers = parseMcpDocument(source, bytes, label);\n const internalServers = Object.create(null) as Record<string, JsonObject>;\n const claudeServers = Object.create(null) as Record<string, JsonObject>;\n const droppedServers: string[] = [];\n const diagnostics: string[] = [];\n\n for (const [name, rawServer] of Object.entries(servers)) {\n const disposition = serverDisposition(name, options);\n if (disposition === 'empty') {\n diagnostics.push(emptyServerDiagnostic(label));\n continue;\n }\n if (disposition === 'dropped') {\n droppedServers.push(name);\n continue;\n }\n try {\n const normalized = await normalizeServer(fs, rawServer, pluginRoot, pluginDataDirectory, name, context);\n internalServers[name] = normalized.internal;\n claudeServers[name] = normalized.claude;\n } catch (error) {\n droppedServers.push(name);\n diagnostics.push(skippedServerDiagnostic(label, name, error));\n }\n }\n\n const contents = stagedContents(internalServers);\n const target = stagedInternalPath(source, contents, options.stagingDirectory);\n await writeStagedInternalConfig(fs, target, contents, options.stagingDirectory, context);\n return {\n configSource: { path: target, format: 'internal', cacheKey: stagedCacheKey(source, configPath, contents) },\n claudeConfig: { mcpServers: claudeServers },\n serverNames: Object.keys(internalServers),\n droppedServers,\n diagnostics,\n };\n } catch (error) {\n return disabledResult(label, error);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAOA,MAAM,aAAa;;AAEnB,MAAM,iCAAiC;AACvC,MAAM,aAAa;AACnB,MAAM,eAAe,IAAI,OAAO,IAAI,WAAW,QAAQ,WAAW,QAAQ,GAAG;AAE7E,SAAS,OAAO,OAAwB;CACtC,OAAO,aAAa,KAAK,KAAK;AAChC;AAIA,MAAa,4CAA4B,IAAI,IAAI,CAAC,eAAe,aAAa,CAAC;AAC/E,MAAa,uCAAuB,IAAI,IAAI,CAAC,aAAa,eAAe,CAAC;AAiC1E,SAAgB,SAAS,OAAqC;CAC5D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,SAAS,OAAmB,SAA4B,OAAqB;CAC3F,MAAM,aAAa,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,QAAQ,CAAC,QAAQ,SAAS,GAAG,CAAC;CAC1E,IAAI,YAAY,MAAM,IAAI,MAAM,GAAG,MAAM,+BAA+B,WAAW,EAAE;AACvF;AAE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|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { FileSystem } from "@agimon-ai/po-core/platform";
|
|
2
|
-
import {
|
|
2
|
+
import { PoMcpAgentPluginProjectionSource } from "@agimon-ai/po-core/mcpProjection";
|
|
3
3
|
//#region src/services/agentPluginMcp/normalize.d.ts
|
|
4
4
|
type JsonObject = Record<string, unknown>;
|
|
5
5
|
interface AgentPluginMcpConfigSource {
|
|
@@ -22,7 +22,7 @@ interface NormalizeAgentPluginMcpOptions {
|
|
|
22
22
|
stagingDirectory: string;
|
|
23
23
|
/** Empty and absent lists both mean keep every server. */
|
|
24
24
|
allowedServers?: readonly string[];
|
|
25
|
-
/**
|
|
25
|
+
/** Po strips nested wrappers; external-only callers may opt out. */
|
|
26
26
|
stripProxyWrappers?: boolean;
|
|
27
27
|
}
|
|
28
28
|
//#endregion
|
|
@@ -37,7 +37,7 @@ interface NormalizeAgentPluginMcpOptions {
|
|
|
37
37
|
*
|
|
38
38
|
* @deprecated Node-only sync shim; use normalizeAgentPluginMcpSourceAsync. Removed in M2.
|
|
39
39
|
*/
|
|
40
|
-
export declare function normalizeAgentPluginMcpSource(source:
|
|
40
|
+
export declare function normalizeAgentPluginMcpSource(source: PoMcpAgentPluginProjectionSource, options: NormalizeAgentPluginMcpOptions): NormalizedAgentPluginMcpSource;
|
|
41
41
|
//#endregion
|
|
42
42
|
//#region src/services/agentPluginMcp/index.d.ts
|
|
43
43
|
type Context = Parameters<FileSystem['readTextFile']>[1];
|
|
@@ -50,7 +50,7 @@ type Context = Parameters<FileSystem['readTextFile']>[1];
|
|
|
50
50
|
* source. Only the two portable plugin placeholders are expanded; the staged
|
|
51
51
|
* layer is tagged `internal`, so legacy `${ENV}` interpolation cannot run again.
|
|
52
52
|
*/
|
|
53
|
-
export declare function normalizeAgentPluginMcpSourceAsync(fs: FileSystem, source:
|
|
53
|
+
export declare function normalizeAgentPluginMcpSourceAsync(fs: FileSystem, source: PoMcpAgentPluginProjectionSource, options: NormalizeAgentPluginMcpOptions, context: Context): Promise<NormalizedAgentPluginMcpSource>;
|
|
54
54
|
//#endregion
|
|
55
55
|
export type { AgentPluginMcpConfigSource, NormalizeAgentPluginMcpOptions, NormalizedAgentPluginMcpSource };
|
|
56
56
|
//# sourceMappingURL=agentPluginMcp.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agentPluginMcp.d.mts","names":[],"sources":["../src/services/agentPluginMcp/normalize.ts","../src/services/agentPluginMcp/sync.ts","../src/services/agentPluginMcp/index.ts"],"mappings":";;;KAsBY,aAAa;UAER;EACf;EACA;EACA;;UAGe;;EAEf,eAAe;;EAEf;IAAgB,YAAY,eAAe;;EAC3C;EACA;EACA;;UAGe;EACf;;EAEA;;EAEA;;;;;;;;;;;;;;wBCwEc,8BACd,QAAQ,
|
|
1
|
+
{"version":3,"file":"agentPluginMcp.d.mts","names":[],"sources":["../src/services/agentPluginMcp/normalize.ts","../src/services/agentPluginMcp/sync.ts","../src/services/agentPluginMcp/index.ts"],"mappings":";;;KAsBY,aAAa;UAER;EACf;EACA;EACA;;UAGe;;EAEf,eAAe;;EAEf;IAAgB,YAAY,eAAe;;EAC3C;EACA;EACA;;UAGe;EACf;;EAEA;;EAEA;;;;;;;;;;;;;;wBCwEc,8BACd,QAAQ,kCACR,SAAS,iCACR;;;KC9EE,UAAU,WAAW;;;;;;;;;;wBA4GJ,mCACpB,IAAI,YACJ,QAAQ,kCACR,SAAS,gCACT,SAAS,UACR,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agentPluginMcp.mjs","names":["realContainedPath","normalizeCommand","normalizeWorkingDirectory","normalizeServer","writeStagedInternalConfig"],"sources":["../src/services/agentPluginMcp/normalize.ts","../src/services/agentPluginMcp/sync.ts","../src/services/agentPluginMcp/index.ts"],"sourcesContent":["/** Pure Agent Plugin MCP normalisation shared by the async API and the deprecated Node-only sync shim. */\nimport { createHash } from 'node:crypto';\nimport path from 'node:path';\n\nimport { AGENT_PLUGIN_MCP_SCHEMA_URL, type DoomMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\n\n/** Same token grammar as node:http `validateHeaderName` (RFC 9110 tchar). */\nconst HTTP_TOKEN = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/u;\n/** Same rejected characters as node:http `validateHeaderValue`. */\nconst INVALID_HEADER_VALUE_CHARACTER = /[^\\t\\x20-\\x7e\\x80-\\xff]/u;\nconst IPV4_OCTET = '(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)';\nconst IPV4_ADDRESS = new RegExp(`^${IPV4_OCTET}(?:\\\\.${IPV4_OCTET}){3}$`, 'u');\n\nfunction isIPv4(value: string): boolean {\n return IPV4_ADDRESS.test(value);\n}\n\nexport const PRIVATE_FILE_MODE = 0o600;\nexport const PRIVATE_DIRECTORY_MODE = 0o700;\nexport const RESERVED_ENVIRONMENT_KEYS = new Set(['PLUGIN_ROOT', 'PLUGIN_DATA']);\nexport const PROXY_SERVER_ALIASES = new Set(['mcp-proxy', 'agiflow-proxy']);\n\nexport type JsonObject = Record<string, unknown>;\n\nexport interface AgentPluginMcpConfigSource {\n path: string;\n format: 'internal';\n cacheKey: string;\n}\n\nexport interface NormalizedAgentPluginMcpSource {\n /** Owner-only, content-addressed layer that bypasses Claude env interpolation. */\n configSource?: AgentPluginMcpConfigSource;\n /** Claude-compatible definitions for an external merged config. */\n claudeConfig: { mcpServers: Record<string, JsonObject> };\n serverNames: string[];\n droppedServers: string[];\n diagnostics: string[];\n}\n\nexport interface NormalizeAgentPluginMcpOptions {\n stagingDirectory: string;\n /** Empty and absent lists both mean keep every server. */\n allowedServers?: readonly string[];\n /** Doom strips nested wrappers; external-only callers may opt out. */\n stripProxyWrappers?: boolean;\n}\n\nexport interface NormalizedServer {\n internal: JsonObject;\n claude: JsonObject;\n}\n\nexport function isObject(value: unknown): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function onlyKeys(value: JsonObject, allowed: readonly string[], label: string): void {\n const unexpected = Object.keys(value).find((key) => !allowed.includes(key));\n if (unexpected) throw new Error(`${label} contains unsupported field \"${unexpected}\"`);\n}\n\nexport function nonEmptyString(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.length === 0) throw new Error(`${label} must be a non-empty string`);\n return value;\n}\n\nexport function optionalStringArray(value: unknown, label: string): string[] | undefined {\n if (value === undefined) return undefined;\n if (!Array.isArray(value)) throw new Error(`${label} must be an array of strings`);\n return value.map((item, index) => {\n if (typeof item !== 'string') throw new Error(`${label}[${index}] must be a string`);\n return item;\n });\n}\n\nfunction optionalStringRecord(value: unknown, label: string): Record<string, string> | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) throw new Error(`${label} must be an object of string values`);\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => {\n if (typeof item !== 'string') throw new Error(`${label}.${key} must be a string`);\n return [key, item];\n }),\n );\n}\n\nexport function expandPluginPlaceholders(value: string, pluginRoot: string, pluginDataDirectory: string): string {\n // The portable contract is a single, non-recursive replacement pass. An\n // unrecognised placeholder remains literal and mcp-proxy must not reinterpret it.\n return value.replace(/\\$\\{PLUGIN_(ROOT|DATA)\\}/gu, (placeholder) =>\n placeholder === '${PLUGIN_ROOT}' ? pluginRoot : pluginDataDirectory,\n );\n}\n\nexport function isInside(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\n}\n\nexport function normalizeEnvironment(\n value: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n): Record<string, string> {\n const declared = optionalStringRecord(value, 'env') ?? {};\n for (const key of Object.keys(declared)) {\n const reservedKey = process.platform === 'win32' ? key.toUpperCase() : key;\n if (RESERVED_ENVIRONMENT_KEYS.has(reservedKey)) {\n throw new Error(`env key \"${key}\" is reserved by Agent Plugins`);\n }\n }\n return {\n ...Object.fromEntries(\n Object.entries(declared).map(([key, item]) => [\n key,\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n ]),\n ),\n PLUGIN_ROOT: pluginRoot,\n PLUGIN_DATA: pluginDataDirectory,\n };\n}\n\nfunction isLoopbackHost(hostname: string): boolean {\n const bareHostname = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n if (bareHostname.toLowerCase() === 'localhost') return true;\n if (isIPv4(bareHostname)) return bareHostname.split('.')[0] === '127';\n return bareHostname === '::1';\n}\n\nexport function normalizeUrl(value: unknown): string {\n const raw = nonEmptyString(value, 'url');\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw new Error('url must be an absolute HTTP(S) URL');\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error('url must use http or https');\n }\n if (parsed.username || parsed.password) throw new Error('url must not contain user information');\n if (parsed.hash) throw new Error('url must not contain a fragment');\n if (parsed.protocol === 'http:' && !isLoopbackHost(parsed.hostname)) {\n throw new Error('non-loopback MCP URLs must use https');\n }\n return raw;\n}\n\nexport function normalizeHeaders(value: unknown): Record<string, string> | undefined {\n const headers = optionalStringRecord(value, 'headers');\n if (!headers) return undefined;\n const seen = new Set<string>();\n for (const [name, item] of Object.entries(headers)) {\n const canonical = name.toLowerCase();\n if (seen.has(canonical)) throw new Error(`headers contain duplicate name \"${name}\"`);\n seen.add(canonical);\n if (!HTTP_TOKEN.test(name) || INVALID_HEADER_VALUE_CHARACTER.test(item)) {\n throw new Error(`header \"${name}\" is invalid`);\n }\n }\n return headers;\n}\n\nexport function stagedInternalPath(\n source: DoomMcpAgentPluginProjectionSource,\n contents: string,\n stagingDirectory: string,\n): string {\n const digest = createHash('sha256')\n .update(source.sourceId)\n .update('\\0')\n .update(source.contentDigest)\n .update('\\0')\n .update(contents)\n .digest('hex')\n .slice(0, 20);\n return path.join(stagingDirectory, `agent-plugin-mcp-${digest}.internal.json`);\n}\n\nexport function emptyResult(diagnostic: string): NormalizedAgentPluginMcpSource {\n return {\n claudeConfig: { mcpServers: {} },\n serverNames: [],\n droppedServers: [],\n diagnostics: [diagnostic],\n };\n}\n\nexport function sourceLabel(source: DoomMcpAgentPluginProjectionSource): string {\n return `Agent Plugin MCP source \"${source.sourceId}\"`;\n}\n\n/** Checks the projection identity before any file is touched. */\nexport function assertProjectionSource(source: DoomMcpAgentPluginProjectionSource): void {\n if (source.mcpSchemaUrl !== AGENT_PLUGIN_MCP_SCHEMA_URL) {\n throw new Error(`unsupported schema \"${String(source.mcpSchemaUrl)}\"`);\n }\n if (!path.isAbsolute(source.pluginRoot) || !path.isAbsolute(source.pluginDataDirectory)) {\n throw new Error('pluginRoot and pluginDataDirectory must be absolute');\n }\n}\n\nexport function assertRootConfigPath(configPath: string, pluginRoot: string): void {\n if (path.dirname(configPath) !== pluginRoot || path.basename(configPath) !== 'mcp.json') {\n throw new Error('portable plugin config must be root mcp.json');\n }\n}\n\n/** Verifies the digest and document shape of the raw mcp.json bytes; returns its server map. */\nexport function parseMcpDocument(\n source: DoomMcpAgentPluginProjectionSource,\n bytes: Uint8Array,\n label: string,\n): Record<string, unknown> {\n const digest = createHash('sha256').update(bytes).digest('hex');\n if (digest !== source.contentDigest) throw new Error('content digest does not match the projection');\n const parsed: unknown = JSON.parse(new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes));\n if (!isObject(parsed)) throw new Error('document must be an object');\n onlyKeys(parsed, ['$schema', 'mcpServers'], label);\n if (parsed.$schema !== source.mcpSchemaUrl) throw new Error('$schema does not match the projected schema');\n if (!isObject(parsed.mcpServers)) throw new Error('mcpServers must be an object');\n return parsed.mcpServers;\n}\n\n/** Whether a declared server is skipped (empty name), dropped by the allowlist or wrapper rule, or normalised. */\nexport function serverDisposition(name: string, options: NormalizeAgentPluginMcpOptions): 'empty' | 'dropped' | 'keep' {\n if (!name) return 'empty';\n const allowed = options.allowedServers;\n const keepAll = !allowed || allowed.length === 0;\n const stripProxyWrappers = options.stripProxyWrappers ?? true;\n if ((!keepAll && !allowed.includes(name)) || (stripProxyWrappers && PROXY_SERVER_ALIASES.has(name))) return 'dropped';\n return 'keep';\n}\n\nexport function emptyServerDiagnostic(label: string): string {\n return `${label} contains an empty server name; that entry was skipped.`;\n}\n\nexport function skippedServerDiagnostic(label: string, name: string, error: unknown): string {\n return `${label} skipped server \"${name}\": ${error instanceof Error ? error.message : String(error)}`;\n}\n\nexport function disabledResult(label: string, error: unknown): NormalizedAgentPluginMcpSource {\n return emptyResult(`${label} was disabled: ${error instanceof Error ? error.message : String(error)}`);\n}\n\n/** The declared transport of one server; stdio declarations are also checked for unsupported fields. */\nexport function serverType(raw: unknown, name: string): string {\n if (!isObject(raw)) throw new Error('definition must be an object');\n const type = nonEmptyString(raw.type, 'type');\n if (type === 'stdio') onlyKeys(raw, ['type', 'command', 'args', 'env', 'cwd'], `server \"${name}\"`);\n return type;\n}\n\nexport function stdioServer(\n name: string,\n config: { command: string; args?: string[]; env: Record<string, string>; cwd: string },\n): NormalizedServer {\n return {\n internal: { name, transport: 'stdio', config },\n claude: { type: 'stdio', ...config },\n };\n}\n\n/** A streamable-http or sse server; any other type is unsupported. */\nexport function remoteServer(raw: JsonObject, name: string, type: string): NormalizedServer {\n if (type === 'streamable-http' || type === 'sse') {\n onlyKeys(raw, ['type', 'url', 'headers'], `server \"${name}\"`);\n const url = normalizeUrl(raw.url);\n const headers = normalizeHeaders(raw.headers);\n const transport = type === 'streamable-http' ? 'http' : 'sse';\n const config = { url, ...(headers ? { headers } : {}) };\n return {\n internal: { name, transport, config },\n claude: { type: transport, ...config },\n };\n }\n throw new Error(`unsupported transport type \"${type}\"`);\n}\n\nexport function stagedContents(internalServers: Record<string, JsonObject>): string {\n return `${JSON.stringify({ mcpServers: internalServers }, null, 2)}\\n`;\n}\n\nexport function stagedCacheKey(\n source: DoomMcpAgentPluginProjectionSource,\n configPath: string,\n contents: string,\n): string {\n return createHash('sha256')\n .update('agent-plugin-v1\\0')\n .update(source.sourceId)\n .update('\\0')\n .update(source.contentDigest)\n .update('\\0')\n .update(configPath)\n .update('\\0')\n .update(contents)\n .digest('hex');\n}\n\n/** The containment base and expanded path of a declared cwd, or undefined when the plugin root is the default. */\nexport function workingDirectoryCandidate(\n declared: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n): { base: string; candidate: string } | undefined {\n if (declared === undefined) return undefined;\n const cwd = nonEmptyString(declared, 'cwd');\n if (cwd.startsWith('./')) return { base: pluginRoot, candidate: path.resolve(pluginRoot, cwd) };\n const expanded = expandPluginPlaceholders(cwd, pluginRoot, pluginDataDirectory);\n if (cwd === '${PLUGIN_ROOT}' || cwd.startsWith('${PLUGIN_ROOT}/')) {\n return { base: pluginRoot, candidate: path.resolve(expanded) };\n }\n if (cwd === '${PLUGIN_DATA}' || cwd.startsWith('${PLUGIN_DATA}/')) {\n return { base: pluginDataDirectory, candidate: path.resolve(expanded) };\n }\n throw new Error('cwd must start with ./, ${PLUGIN_ROOT}, or ${PLUGIN_DATA}');\n}\n\n/** Rejects a command that is neither a bare executable name nor a ./ path; true when it must be resolved. */\nexport function isPluginRelativeCommand(command: string): boolean {\n if (command.startsWith('./')) return true;\n if (command === '.' || command === '..' || /[\\s/\\\\]/u.test(command)) {\n throw new Error('command must be a bare executable name or a ./ path inside the plugin');\n }\n return false;\n}\n","import { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { DoomMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\n\nimport {\n type JsonObject,\n type NormalizeAgentPluginMcpOptions,\n type NormalizedAgentPluginMcpSource,\n type NormalizedServer,\n PRIVATE_DIRECTORY_MODE,\n PRIVATE_FILE_MODE,\n assertProjectionSource,\n assertRootConfigPath,\n disabledResult,\n emptyServerDiagnostic,\n expandPluginPlaceholders,\n isInside,\n isPluginRelativeCommand,\n nonEmptyString,\n normalizeEnvironment,\n optionalStringArray,\n parseMcpDocument,\n remoteServer,\n serverDisposition,\n serverType,\n skippedServerDiagnostic,\n sourceLabel,\n stagedCacheKey,\n stagedContents,\n stagedInternalPath,\n stdioServer,\n workingDirectoryCandidate,\n} from './normalize';\n\nfunction realContainedPath(root: string, candidate: string, label: string): string {\n let realCandidate: string;\n try {\n realCandidate = fs.realpathSync(candidate);\n } catch {\n throw new Error(`${label} does not exist`);\n }\n if (!isInside(root, realCandidate)) throw new Error(`${label} escapes its allowed plugin directory`);\n return realCandidate;\n}\n\nfunction normalizeCommand(command: string, pluginRoot: string): string {\n if (!isPluginRelativeCommand(command)) return command;\n const resolved = realContainedPath(pluginRoot, path.resolve(pluginRoot, command), 'command');\n if (!fs.statSync(resolved).isFile()) throw new Error('command must resolve to a regular file');\n try {\n fs.accessSync(resolved, fs.constants.X_OK);\n } catch {\n throw new Error('command must resolve to an executable file');\n }\n return resolved;\n}\n\nfunction normalizeWorkingDirectory(declared: unknown, pluginRoot: string, pluginDataDirectory: string): string {\n const declaredCwd = workingDirectoryCandidate(declared, pluginRoot, pluginDataDirectory);\n if (!declaredCwd) return pluginRoot;\n const resolved = realContainedPath(declaredCwd.base, declaredCwd.candidate, 'cwd');\n if (!fs.statSync(resolved).isDirectory()) throw new Error('cwd must resolve to a directory');\n return resolved;\n}\n\nfunction normalizeServer(\n raw: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n name: string,\n): NormalizedServer {\n const type = serverType(raw, name);\n const declaration = raw as JsonObject;\n if (type !== 'stdio') return remoteServer(declaration, name, type);\n const command = normalizeCommand(nonEmptyString(declaration.command, 'command'), pluginRoot);\n const args = optionalStringArray(declaration.args, 'args')?.map((item) =>\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n );\n const env = normalizeEnvironment(declaration.env, pluginRoot, pluginDataDirectory);\n const cwd = normalizeWorkingDirectory(declaration.cwd, pluginRoot, pluginDataDirectory);\n return stdioServer(name, { command, ...(args ? { args } : {}), env, cwd });\n}\n\nfunction writeStagedInternalConfig(target: string, contents: string, stagingDirectory: string): void {\n fs.mkdirSync(stagingDirectory, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n fs.chmodSync(stagingDirectory, PRIVATE_DIRECTORY_MODE);\n const temporaryPath = `${target}.${process.pid}-${randomUUID()}.tmp`;\n try {\n fs.writeFileSync(temporaryPath, contents, { flag: 'wx', mode: PRIVATE_FILE_MODE });\n try {\n fs.renameSync(temporaryPath, target);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== 'EEXIST' && code !== 'EPERM') throw error;\n const stat = fs.lstatSync(target);\n if (stat.isSymbolicLink() || !stat.isFile() || fs.readFileSync(target, 'utf8') !== contents) {\n throw new Error('content-addressed staging path is occupied by different content');\n }\n }\n fs.chmodSync(target, PRIVATE_FILE_MODE);\n } finally {\n fs.rmSync(temporaryPath, { force: true });\n }\n}\n\n/**\n * Validates one Agent Plugins v1 `mcp.json` and stages a native mcp-proxy layer.\n *\n * Server validation is isolated: one malformed server is diagnosed and skipped.\n * Document/schema, source identity, or plugin-boundary failures reject the whole\n * source. Only the two portable plugin placeholders are expanded; the staged\n * layer is tagged `internal`, so legacy `${ENV}` interpolation cannot run again.\n *\n * @deprecated Node-only sync shim; use normalizeAgentPluginMcpSourceAsync. Removed in M2.\n */\nexport function normalizeAgentPluginMcpSource(\n source: DoomMcpAgentPluginProjectionSource,\n options: NormalizeAgentPluginMcpOptions,\n): NormalizedAgentPluginMcpSource {\n const label = sourceLabel(source);\n try {\n assertProjectionSource(source);\n const pluginRoot = fs.realpathSync(source.pluginRoot);\n try {\n const dataStat = fs.lstatSync(source.pluginDataDirectory);\n if (dataStat.isSymbolicLink() || !dataStat.isDirectory()) {\n throw new Error('pluginDataDirectory must be a real directory');\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n fs.mkdirSync(source.pluginDataDirectory, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n }\n fs.chmodSync(source.pluginDataDirectory, PRIVATE_DIRECTORY_MODE);\n fs.accessSync(source.pluginDataDirectory, fs.constants.W_OK);\n const pluginDataDirectory = fs.realpathSync(source.pluginDataDirectory);\n const configPath = realContainedPath(pluginRoot, source.configPath, 'mcp.json');\n assertRootConfigPath(configPath, pluginRoot);\n\n const servers = parseMcpDocument(source, fs.readFileSync(configPath), label);\n const internalServers = Object.create(null) as Record<string, JsonObject>;\n const claudeServers = Object.create(null) as Record<string, JsonObject>;\n const droppedServers: string[] = [];\n const diagnostics: string[] = [];\n\n for (const [name, rawServer] of Object.entries(servers)) {\n const disposition = serverDisposition(name, options);\n if (disposition === 'empty') {\n diagnostics.push(emptyServerDiagnostic(label));\n continue;\n }\n if (disposition === 'dropped') {\n droppedServers.push(name);\n continue;\n }\n try {\n const normalized = normalizeServer(rawServer, pluginRoot, pluginDataDirectory, name);\n internalServers[name] = normalized.internal;\n claudeServers[name] = normalized.claude;\n } catch (error) {\n droppedServers.push(name);\n diagnostics.push(skippedServerDiagnostic(label, name, error));\n }\n }\n\n const contents = stagedContents(internalServers);\n const target = stagedInternalPath(source, contents, options.stagingDirectory);\n writeStagedInternalConfig(target, contents, options.stagingDirectory);\n return {\n configSource: { path: target, format: 'internal', cacheKey: stagedCacheKey(source, configPath, contents) },\n claudeConfig: { mcpServers: claudeServers },\n serverNames: Object.keys(internalServers),\n droppedServers,\n diagnostics,\n };\n } catch (error) {\n return disabledResult(label, error);\n }\n}\n","import path from 'node:path';\n\nimport type { DoomMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\nimport { type FileSystem, getOrThrow, nodeHost, writeFileAtomic } from '@agimon-ai/po-core/platform';\n\nimport {\n type JsonObject,\n type NormalizeAgentPluginMcpOptions,\n type NormalizedAgentPluginMcpSource,\n type NormalizedServer,\n PRIVATE_DIRECTORY_MODE,\n PRIVATE_FILE_MODE,\n assertProjectionSource,\n assertRootConfigPath,\n disabledResult,\n emptyServerDiagnostic,\n expandPluginPlaceholders,\n isInside,\n isPluginRelativeCommand,\n nonEmptyString,\n normalizeEnvironment,\n optionalStringArray,\n parseMcpDocument,\n remoteServer,\n serverDisposition,\n serverType,\n skippedServerDiagnostic,\n sourceLabel,\n stagedCacheKey,\n stagedContents,\n stagedInternalPath,\n stdioServer,\n workingDirectoryCandidate,\n} from './normalize';\n\nexport type {\n AgentPluginMcpConfigSource,\n NormalizeAgentPluginMcpOptions,\n NormalizedAgentPluginMcpSource,\n} from './normalize';\nexport { normalizeAgentPluginMcpSource } from './sync';\n\ntype Context = Parameters<FileSystem['readTextFile']>[1];\n\nasync function realContainedPath(\n fs: FileSystem,\n root: string,\n candidate: string,\n label: string,\n context: Context,\n): Promise<string> {\n const real = await fs.canonicalPath(candidate, context);\n if (!real.ok) throw new Error(`${label} does not exist`);\n if (!isInside(root, real.value)) throw new Error(`${label} escapes its allowed plugin directory`);\n return real.value;\n}\n\nasync function normalizeCommand(\n fs: FileSystem,\n command: string,\n pluginRoot: string,\n context: Context,\n): Promise<string> {\n if (!isPluginRelativeCommand(command)) return command;\n const resolved = await realContainedPath(fs, pluginRoot, path.resolve(pluginRoot, command), 'command', context);\n if (getOrThrow(await fs.fileInfo(resolved, context)).kind !== 'file') {\n throw new Error('command must resolve to a regular file');\n }\n // Execute bits stand in for access(X_OK); the edge has no modes, so nodeHost reports none and the check is skipped.\n const mode = await nodeHost.fileMode(resolved);\n if (mode !== undefined && (mode & 0o111) === 0) throw new Error('command must resolve to an executable file');\n return resolved;\n}\n\nasync function normalizeWorkingDirectory(\n fs: FileSystem,\n declared: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n context: Context,\n): Promise<string> {\n const declaredCwd = workingDirectoryCandidate(declared, pluginRoot, pluginDataDirectory);\n if (!declaredCwd) return pluginRoot;\n const resolved = await realContainedPath(fs, declaredCwd.base, declaredCwd.candidate, 'cwd', context);\n if (getOrThrow(await fs.fileInfo(resolved, context)).kind !== 'directory') {\n throw new Error('cwd must resolve to a directory');\n }\n return resolved;\n}\n\nasync function normalizeServer(\n fs: FileSystem,\n raw: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n name: string,\n context: Context,\n): Promise<NormalizedServer> {\n const type = serverType(raw, name);\n const declaration = raw as JsonObject;\n if (type !== 'stdio') return remoteServer(declaration, name, type);\n const command = await normalizeCommand(fs, nonEmptyString(declaration.command, 'command'), pluginRoot, context);\n const args = optionalStringArray(declaration.args, 'args')?.map((item) =>\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n );\n const env = normalizeEnvironment(declaration.env, pluginRoot, pluginDataDirectory);\n const cwd = await normalizeWorkingDirectory(fs, declaration.cwd, pluginRoot, pluginDataDirectory, context);\n return stdioServer(name, { command, ...(args ? { args } : {}), env, cwd });\n}\n\n/** Owner-only plugin data directory; a symbolic link or non-directory rejects the source. */\nasync function preparePluginDataDirectory(fs: FileSystem, directory: string, context: Context): Promise<string> {\n const info = await fs.fileInfo(directory, context);\n if (info.ok) {\n if (info.value.kind !== 'directory') throw new Error('pluginDataDirectory must be a real directory');\n } else if (info.error.code === 'not_found') {\n getOrThrow(await fs.createDir(directory, { recursive: true }, context));\n } else {\n throw info.error;\n }\n await nodeHost.setMode(directory, PRIVATE_DIRECTORY_MODE);\n return getOrThrow(await fs.canonicalPath(directory, context));\n}\n\n/**\n * Content-addressed and owner-only. The name hashes the contents, so replacing an\n * existing staged file through a uniquely named temporary file never changes what it holds.\n */\nasync function writeStagedInternalConfig(\n fs: FileSystem,\n target: string,\n contents: string,\n stagingDirectory: string,\n context: Context,\n): Promise<void> {\n getOrThrow(await fs.createDir(stagingDirectory, { recursive: true }, context));\n await nodeHost.setMode(stagingDirectory, PRIVATE_DIRECTORY_MODE);\n await writeFileAtomic(fs, target, contents, context);\n await nodeHost.setMode(target, PRIVATE_FILE_MODE);\n}\n\n/**\n * Validates one Agent Plugins v1 `mcp.json` and stages a native mcp-proxy layer,\n * reading and writing through the injected file system.\n *\n * Server validation is isolated: one malformed server is diagnosed and skipped.\n * Document/schema, source identity, or plugin-boundary failures reject the whole\n * source. Only the two portable plugin placeholders are expanded; the staged\n * layer is tagged `internal`, so legacy `${ENV}` interpolation cannot run again.\n */\nexport async function normalizeAgentPluginMcpSourceAsync(\n fs: FileSystem,\n source: DoomMcpAgentPluginProjectionSource,\n options: NormalizeAgentPluginMcpOptions,\n context: Context,\n): Promise<NormalizedAgentPluginMcpSource> {\n const label = sourceLabel(source);\n try {\n assertProjectionSource(source);\n const pluginRoot = getOrThrow(await fs.canonicalPath(source.pluginRoot, context));\n const pluginDataDirectory = await preparePluginDataDirectory(fs, source.pluginDataDirectory, context);\n const configPath = await realContainedPath(fs, pluginRoot, source.configPath, 'mcp.json', context);\n assertRootConfigPath(configPath, pluginRoot);\n\n const bytes = getOrThrow(await fs.readBinaryFile(configPath, context));\n const servers = parseMcpDocument(source, bytes, label);\n const internalServers = Object.create(null) as Record<string, JsonObject>;\n const claudeServers = Object.create(null) as Record<string, JsonObject>;\n const droppedServers: string[] = [];\n const diagnostics: string[] = [];\n\n for (const [name, rawServer] of Object.entries(servers)) {\n const disposition = serverDisposition(name, options);\n if (disposition === 'empty') {\n diagnostics.push(emptyServerDiagnostic(label));\n continue;\n }\n if (disposition === 'dropped') {\n droppedServers.push(name);\n continue;\n }\n try {\n const normalized = await normalizeServer(fs, rawServer, pluginRoot, pluginDataDirectory, name, context);\n internalServers[name] = normalized.internal;\n claudeServers[name] = normalized.claude;\n } catch (error) {\n droppedServers.push(name);\n diagnostics.push(skippedServerDiagnostic(label, name, error));\n }\n }\n\n const contents = stagedContents(internalServers);\n const target = stagedInternalPath(source, contents, options.stagingDirectory);\n await writeStagedInternalConfig(fs, target, contents, options.stagingDirectory, context);\n return {\n configSource: { path: target, format: 'internal', cacheKey: stagedCacheKey(source, configPath, contents) },\n claudeConfig: { mcpServers: claudeServers },\n serverNames: Object.keys(internalServers),\n droppedServers,\n diagnostics,\n };\n } catch (error) {\n return disabledResult(label, error);\n }\n}\n"],"mappings":";;;;;;;;AAOA,MAAM,aAAa;;AAEnB,MAAM,iCAAiC;AACvC,MAAM,aAAa;AACnB,MAAM,eAAe,I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","names":["realContainedPath","normalizeCommand","normalizeWorkingDirectory","normalizeServer","writeStagedInternalConfig"],"sources":["../src/services/agentPluginMcp/normalize.ts","../src/services/agentPluginMcp/sync.ts","../src/services/agentPluginMcp/index.ts"],"sourcesContent":["/** Pure Agent Plugin MCP normalisation shared by the async API and the deprecated Node-only sync shim. */\nimport { createHash } from 'node:crypto';\nimport path from 'node:path';\n\nimport { AGENT_PLUGIN_MCP_SCHEMA_URL, type PoMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\n\n/** Same token grammar as node:http `validateHeaderName` (RFC 9110 tchar). */\nconst HTTP_TOKEN = /^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/u;\n/** Same rejected characters as node:http `validateHeaderValue`. */\nconst INVALID_HEADER_VALUE_CHARACTER = /[^\\t\\x20-\\x7e\\x80-\\xff]/u;\nconst IPV4_OCTET = '(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)';\nconst IPV4_ADDRESS = new RegExp(`^${IPV4_OCTET}(?:\\\\.${IPV4_OCTET}){3}$`, 'u');\n\nfunction isIPv4(value: string): boolean {\n return IPV4_ADDRESS.test(value);\n}\n\nexport const PRIVATE_FILE_MODE = 0o600;\nexport const PRIVATE_DIRECTORY_MODE = 0o700;\nexport const RESERVED_ENVIRONMENT_KEYS = new Set(['PLUGIN_ROOT', 'PLUGIN_DATA']);\nexport const PROXY_SERVER_ALIASES = new Set(['mcp-proxy', 'agiflow-proxy']);\n\nexport type JsonObject = Record<string, unknown>;\n\nexport interface AgentPluginMcpConfigSource {\n path: string;\n format: 'internal';\n cacheKey: string;\n}\n\nexport interface NormalizedAgentPluginMcpSource {\n /** Owner-only, content-addressed layer that bypasses Claude env interpolation. */\n configSource?: AgentPluginMcpConfigSource;\n /** Claude-compatible definitions for an external merged config. */\n claudeConfig: { mcpServers: Record<string, JsonObject> };\n serverNames: string[];\n droppedServers: string[];\n diagnostics: string[];\n}\n\nexport interface NormalizeAgentPluginMcpOptions {\n stagingDirectory: string;\n /** Empty and absent lists both mean keep every server. */\n allowedServers?: readonly string[];\n /** Po strips nested wrappers; external-only callers may opt out. */\n stripProxyWrappers?: boolean;\n}\n\nexport interface NormalizedServer {\n internal: JsonObject;\n claude: JsonObject;\n}\n\nexport function isObject(value: unknown): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function onlyKeys(value: JsonObject, allowed: readonly string[], label: string): void {\n const unexpected = Object.keys(value).find((key) => !allowed.includes(key));\n if (unexpected) throw new Error(`${label} contains unsupported field \"${unexpected}\"`);\n}\n\nexport function nonEmptyString(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.length === 0) throw new Error(`${label} must be a non-empty string`);\n return value;\n}\n\nexport function optionalStringArray(value: unknown, label: string): string[] | undefined {\n if (value === undefined) return undefined;\n if (!Array.isArray(value)) throw new Error(`${label} must be an array of strings`);\n return value.map((item, index) => {\n if (typeof item !== 'string') throw new Error(`${label}[${index}] must be a string`);\n return item;\n });\n}\n\nfunction optionalStringRecord(value: unknown, label: string): Record<string, string> | undefined {\n if (value === undefined) return undefined;\n if (!isObject(value)) throw new Error(`${label} must be an object of string values`);\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => {\n if (typeof item !== 'string') throw new Error(`${label}.${key} must be a string`);\n return [key, item];\n }),\n );\n}\n\nexport function expandPluginPlaceholders(value: string, pluginRoot: string, pluginDataDirectory: string): string {\n // The portable contract is a single, non-recursive replacement pass. An\n // unrecognised placeholder remains literal and mcp-proxy must not reinterpret it.\n return value.replace(/\\$\\{PLUGIN_(ROOT|DATA)\\}/gu, (placeholder) =>\n placeholder === '${PLUGIN_ROOT}' ? pluginRoot : pluginDataDirectory,\n );\n}\n\nexport function isInside(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\n}\n\nexport function normalizeEnvironment(\n value: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n): Record<string, string> {\n const declared = optionalStringRecord(value, 'env') ?? {};\n for (const key of Object.keys(declared)) {\n const reservedKey = process.platform === 'win32' ? key.toUpperCase() : key;\n if (RESERVED_ENVIRONMENT_KEYS.has(reservedKey)) {\n throw new Error(`env key \"${key}\" is reserved by Agent Plugins`);\n }\n }\n return {\n ...Object.fromEntries(\n Object.entries(declared).map(([key, item]) => [\n key,\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n ]),\n ),\n PLUGIN_ROOT: pluginRoot,\n PLUGIN_DATA: pluginDataDirectory,\n };\n}\n\nfunction isLoopbackHost(hostname: string): boolean {\n const bareHostname = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n if (bareHostname.toLowerCase() === 'localhost') return true;\n if (isIPv4(bareHostname)) return bareHostname.split('.')[0] === '127';\n return bareHostname === '::1';\n}\n\nexport function normalizeUrl(value: unknown): string {\n const raw = nonEmptyString(value, 'url');\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n throw new Error('url must be an absolute HTTP(S) URL');\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error('url must use http or https');\n }\n if (parsed.username || parsed.password) throw new Error('url must not contain user information');\n if (parsed.hash) throw new Error('url must not contain a fragment');\n if (parsed.protocol === 'http:' && !isLoopbackHost(parsed.hostname)) {\n throw new Error('non-loopback MCP URLs must use https');\n }\n return raw;\n}\n\nexport function normalizeHeaders(value: unknown): Record<string, string> | undefined {\n const headers = optionalStringRecord(value, 'headers');\n if (!headers) return undefined;\n const seen = new Set<string>();\n for (const [name, item] of Object.entries(headers)) {\n const canonical = name.toLowerCase();\n if (seen.has(canonical)) throw new Error(`headers contain duplicate name \"${name}\"`);\n seen.add(canonical);\n if (!HTTP_TOKEN.test(name) || INVALID_HEADER_VALUE_CHARACTER.test(item)) {\n throw new Error(`header \"${name}\" is invalid`);\n }\n }\n return headers;\n}\n\nexport function stagedInternalPath(\n source: PoMcpAgentPluginProjectionSource,\n contents: string,\n stagingDirectory: string,\n): string {\n const digest = createHash('sha256')\n .update(source.sourceId)\n .update('\\0')\n .update(source.contentDigest)\n .update('\\0')\n .update(contents)\n .digest('hex')\n .slice(0, 20);\n return path.join(stagingDirectory, `agent-plugin-mcp-${digest}.internal.json`);\n}\n\nexport function emptyResult(diagnostic: string): NormalizedAgentPluginMcpSource {\n return {\n claudeConfig: { mcpServers: {} },\n serverNames: [],\n droppedServers: [],\n diagnostics: [diagnostic],\n };\n}\n\nexport function sourceLabel(source: PoMcpAgentPluginProjectionSource): string {\n return `Agent Plugin MCP source \"${source.sourceId}\"`;\n}\n\n/** Checks the projection identity before any file is touched. */\nexport function assertProjectionSource(source: PoMcpAgentPluginProjectionSource): void {\n if (source.mcpSchemaUrl !== AGENT_PLUGIN_MCP_SCHEMA_URL) {\n throw new Error(`unsupported schema \"${String(source.mcpSchemaUrl)}\"`);\n }\n if (!path.isAbsolute(source.pluginRoot) || !path.isAbsolute(source.pluginDataDirectory)) {\n throw new Error('pluginRoot and pluginDataDirectory must be absolute');\n }\n}\n\nexport function assertRootConfigPath(configPath: string, pluginRoot: string): void {\n if (path.dirname(configPath) !== pluginRoot || path.basename(configPath) !== 'mcp.json') {\n throw new Error('portable plugin config must be root mcp.json');\n }\n}\n\n/** Verifies the digest and document shape of the raw mcp.json bytes; returns its server map. */\nexport function parseMcpDocument(\n source: PoMcpAgentPluginProjectionSource,\n bytes: Uint8Array,\n label: string,\n): Record<string, unknown> {\n const digest = createHash('sha256').update(bytes).digest('hex');\n if (digest !== source.contentDigest) throw new Error('content digest does not match the projection');\n const parsed: unknown = JSON.parse(new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes));\n if (!isObject(parsed)) throw new Error('document must be an object');\n onlyKeys(parsed, ['$schema', 'mcpServers'], label);\n if (parsed.$schema !== source.mcpSchemaUrl) throw new Error('$schema does not match the projected schema');\n if (!isObject(parsed.mcpServers)) throw new Error('mcpServers must be an object');\n return parsed.mcpServers;\n}\n\n/** Whether a declared server is skipped (empty name), dropped by the allowlist or wrapper rule, or normalised. */\nexport function serverDisposition(name: string, options: NormalizeAgentPluginMcpOptions): 'empty' | 'dropped' | 'keep' {\n if (!name) return 'empty';\n const allowed = options.allowedServers;\n const keepAll = !allowed || allowed.length === 0;\n const stripProxyWrappers = options.stripProxyWrappers ?? true;\n if ((!keepAll && !allowed.includes(name)) || (stripProxyWrappers && PROXY_SERVER_ALIASES.has(name))) return 'dropped';\n return 'keep';\n}\n\nexport function emptyServerDiagnostic(label: string): string {\n return `${label} contains an empty server name; that entry was skipped.`;\n}\n\nexport function skippedServerDiagnostic(label: string, name: string, error: unknown): string {\n return `${label} skipped server \"${name}\": ${error instanceof Error ? error.message : String(error)}`;\n}\n\nexport function disabledResult(label: string, error: unknown): NormalizedAgentPluginMcpSource {\n return emptyResult(`${label} was disabled: ${error instanceof Error ? error.message : String(error)}`);\n}\n\n/** The declared transport of one server; stdio declarations are also checked for unsupported fields. */\nexport function serverType(raw: unknown, name: string): string {\n if (!isObject(raw)) throw new Error('definition must be an object');\n const type = nonEmptyString(raw.type, 'type');\n if (type === 'stdio') onlyKeys(raw, ['type', 'command', 'args', 'env', 'cwd'], `server \"${name}\"`);\n return type;\n}\n\nexport function stdioServer(\n name: string,\n config: { command: string; args?: string[]; env: Record<string, string>; cwd: string },\n): NormalizedServer {\n return {\n internal: { name, transport: 'stdio', config },\n claude: { type: 'stdio', ...config },\n };\n}\n\n/** A streamable-http or sse server; any other type is unsupported. */\nexport function remoteServer(raw: JsonObject, name: string, type: string): NormalizedServer {\n if (type === 'streamable-http' || type === 'sse') {\n onlyKeys(raw, ['type', 'url', 'headers'], `server \"${name}\"`);\n const url = normalizeUrl(raw.url);\n const headers = normalizeHeaders(raw.headers);\n const transport = type === 'streamable-http' ? 'http' : 'sse';\n const config = { url, ...(headers ? { headers } : {}) };\n return {\n internal: { name, transport, config },\n claude: { type: transport, ...config },\n };\n }\n throw new Error(`unsupported transport type \"${type}\"`);\n}\n\nexport function stagedContents(internalServers: Record<string, JsonObject>): string {\n return `${JSON.stringify({ mcpServers: internalServers }, null, 2)}\\n`;\n}\n\nexport function stagedCacheKey(source: PoMcpAgentPluginProjectionSource, configPath: string, contents: string): string {\n return createHash('sha256')\n .update('agent-plugin-v1\\0')\n .update(source.sourceId)\n .update('\\0')\n .update(source.contentDigest)\n .update('\\0')\n .update(configPath)\n .update('\\0')\n .update(contents)\n .digest('hex');\n}\n\n/** The containment base and expanded path of a declared cwd, or undefined when the plugin root is the default. */\nexport function workingDirectoryCandidate(\n declared: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n): { base: string; candidate: string } | undefined {\n if (declared === undefined) return undefined;\n const cwd = nonEmptyString(declared, 'cwd');\n if (cwd.startsWith('./')) return { base: pluginRoot, candidate: path.resolve(pluginRoot, cwd) };\n const expanded = expandPluginPlaceholders(cwd, pluginRoot, pluginDataDirectory);\n if (cwd === '${PLUGIN_ROOT}' || cwd.startsWith('${PLUGIN_ROOT}/')) {\n return { base: pluginRoot, candidate: path.resolve(expanded) };\n }\n if (cwd === '${PLUGIN_DATA}' || cwd.startsWith('${PLUGIN_DATA}/')) {\n return { base: pluginDataDirectory, candidate: path.resolve(expanded) };\n }\n throw new Error('cwd must start with ./, ${PLUGIN_ROOT}, or ${PLUGIN_DATA}');\n}\n\n/** Rejects a command that is neither a bare executable name nor a ./ path; true when it must be resolved. */\nexport function isPluginRelativeCommand(command: string): boolean {\n if (command.startsWith('./')) return true;\n if (command === '.' || command === '..' || /[\\s/\\\\]/u.test(command)) {\n throw new Error('command must be a bare executable name or a ./ path inside the plugin');\n }\n return false;\n}\n","import { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { PoMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\n\nimport {\n type JsonObject,\n type NormalizeAgentPluginMcpOptions,\n type NormalizedAgentPluginMcpSource,\n type NormalizedServer,\n PRIVATE_DIRECTORY_MODE,\n PRIVATE_FILE_MODE,\n assertProjectionSource,\n assertRootConfigPath,\n disabledResult,\n emptyServerDiagnostic,\n expandPluginPlaceholders,\n isInside,\n isPluginRelativeCommand,\n nonEmptyString,\n normalizeEnvironment,\n optionalStringArray,\n parseMcpDocument,\n remoteServer,\n serverDisposition,\n serverType,\n skippedServerDiagnostic,\n sourceLabel,\n stagedCacheKey,\n stagedContents,\n stagedInternalPath,\n stdioServer,\n workingDirectoryCandidate,\n} from './normalize';\n\nfunction realContainedPath(root: string, candidate: string, label: string): string {\n let realCandidate: string;\n try {\n realCandidate = fs.realpathSync(candidate);\n } catch {\n throw new Error(`${label} does not exist`);\n }\n if (!isInside(root, realCandidate)) throw new Error(`${label} escapes its allowed plugin directory`);\n return realCandidate;\n}\n\nfunction normalizeCommand(command: string, pluginRoot: string): string {\n if (!isPluginRelativeCommand(command)) return command;\n const resolved = realContainedPath(pluginRoot, path.resolve(pluginRoot, command), 'command');\n if (!fs.statSync(resolved).isFile()) throw new Error('command must resolve to a regular file');\n try {\n fs.accessSync(resolved, fs.constants.X_OK);\n } catch {\n throw new Error('command must resolve to an executable file');\n }\n return resolved;\n}\n\nfunction normalizeWorkingDirectory(declared: unknown, pluginRoot: string, pluginDataDirectory: string): string {\n const declaredCwd = workingDirectoryCandidate(declared, pluginRoot, pluginDataDirectory);\n if (!declaredCwd) return pluginRoot;\n const resolved = realContainedPath(declaredCwd.base, declaredCwd.candidate, 'cwd');\n if (!fs.statSync(resolved).isDirectory()) throw new Error('cwd must resolve to a directory');\n return resolved;\n}\n\nfunction normalizeServer(\n raw: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n name: string,\n): NormalizedServer {\n const type = serverType(raw, name);\n const declaration = raw as JsonObject;\n if (type !== 'stdio') return remoteServer(declaration, name, type);\n const command = normalizeCommand(nonEmptyString(declaration.command, 'command'), pluginRoot);\n const args = optionalStringArray(declaration.args, 'args')?.map((item) =>\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n );\n const env = normalizeEnvironment(declaration.env, pluginRoot, pluginDataDirectory);\n const cwd = normalizeWorkingDirectory(declaration.cwd, pluginRoot, pluginDataDirectory);\n return stdioServer(name, { command, ...(args ? { args } : {}), env, cwd });\n}\n\nfunction writeStagedInternalConfig(target: string, contents: string, stagingDirectory: string): void {\n fs.mkdirSync(stagingDirectory, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n fs.chmodSync(stagingDirectory, PRIVATE_DIRECTORY_MODE);\n const temporaryPath = `${target}.${process.pid}-${randomUUID()}.tmp`;\n try {\n fs.writeFileSync(temporaryPath, contents, { flag: 'wx', mode: PRIVATE_FILE_MODE });\n try {\n fs.renameSync(temporaryPath, target);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== 'EEXIST' && code !== 'EPERM') throw error;\n const stat = fs.lstatSync(target);\n if (stat.isSymbolicLink() || !stat.isFile() || fs.readFileSync(target, 'utf8') !== contents) {\n throw new Error('content-addressed staging path is occupied by different content');\n }\n }\n fs.chmodSync(target, PRIVATE_FILE_MODE);\n } finally {\n fs.rmSync(temporaryPath, { force: true });\n }\n}\n\n/**\n * Validates one Agent Plugins v1 `mcp.json` and stages a native mcp-proxy layer.\n *\n * Server validation is isolated: one malformed server is diagnosed and skipped.\n * Document/schema, source identity, or plugin-boundary failures reject the whole\n * source. Only the two portable plugin placeholders are expanded; the staged\n * layer is tagged `internal`, so legacy `${ENV}` interpolation cannot run again.\n *\n * @deprecated Node-only sync shim; use normalizeAgentPluginMcpSourceAsync. Removed in M2.\n */\nexport function normalizeAgentPluginMcpSource(\n source: PoMcpAgentPluginProjectionSource,\n options: NormalizeAgentPluginMcpOptions,\n): NormalizedAgentPluginMcpSource {\n const label = sourceLabel(source);\n try {\n assertProjectionSource(source);\n const pluginRoot = fs.realpathSync(source.pluginRoot);\n try {\n const dataStat = fs.lstatSync(source.pluginDataDirectory);\n if (dataStat.isSymbolicLink() || !dataStat.isDirectory()) {\n throw new Error('pluginDataDirectory must be a real directory');\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n fs.mkdirSync(source.pluginDataDirectory, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n }\n fs.chmodSync(source.pluginDataDirectory, PRIVATE_DIRECTORY_MODE);\n fs.accessSync(source.pluginDataDirectory, fs.constants.W_OK);\n const pluginDataDirectory = fs.realpathSync(source.pluginDataDirectory);\n const configPath = realContainedPath(pluginRoot, source.configPath, 'mcp.json');\n assertRootConfigPath(configPath, pluginRoot);\n\n const servers = parseMcpDocument(source, fs.readFileSync(configPath), label);\n const internalServers = Object.create(null) as Record<string, JsonObject>;\n const claudeServers = Object.create(null) as Record<string, JsonObject>;\n const droppedServers: string[] = [];\n const diagnostics: string[] = [];\n\n for (const [name, rawServer] of Object.entries(servers)) {\n const disposition = serverDisposition(name, options);\n if (disposition === 'empty') {\n diagnostics.push(emptyServerDiagnostic(label));\n continue;\n }\n if (disposition === 'dropped') {\n droppedServers.push(name);\n continue;\n }\n try {\n const normalized = normalizeServer(rawServer, pluginRoot, pluginDataDirectory, name);\n internalServers[name] = normalized.internal;\n claudeServers[name] = normalized.claude;\n } catch (error) {\n droppedServers.push(name);\n diagnostics.push(skippedServerDiagnostic(label, name, error));\n }\n }\n\n const contents = stagedContents(internalServers);\n const target = stagedInternalPath(source, contents, options.stagingDirectory);\n writeStagedInternalConfig(target, contents, options.stagingDirectory);\n return {\n configSource: { path: target, format: 'internal', cacheKey: stagedCacheKey(source, configPath, contents) },\n claudeConfig: { mcpServers: claudeServers },\n serverNames: Object.keys(internalServers),\n droppedServers,\n diagnostics,\n };\n } catch (error) {\n return disabledResult(label, error);\n }\n}\n","import path from 'node:path';\n\nimport type { PoMcpAgentPluginProjectionSource } from '@agimon-ai/po-core/mcpProjection';\nimport { type FileSystem, getOrThrow, nodeHost, writeFileAtomic } from '@agimon-ai/po-core/platform';\n\nimport {\n type JsonObject,\n type NormalizeAgentPluginMcpOptions,\n type NormalizedAgentPluginMcpSource,\n type NormalizedServer,\n PRIVATE_DIRECTORY_MODE,\n PRIVATE_FILE_MODE,\n assertProjectionSource,\n assertRootConfigPath,\n disabledResult,\n emptyServerDiagnostic,\n expandPluginPlaceholders,\n isInside,\n isPluginRelativeCommand,\n nonEmptyString,\n normalizeEnvironment,\n optionalStringArray,\n parseMcpDocument,\n remoteServer,\n serverDisposition,\n serverType,\n skippedServerDiagnostic,\n sourceLabel,\n stagedCacheKey,\n stagedContents,\n stagedInternalPath,\n stdioServer,\n workingDirectoryCandidate,\n} from './normalize';\n\nexport type {\n AgentPluginMcpConfigSource,\n NormalizeAgentPluginMcpOptions,\n NormalizedAgentPluginMcpSource,\n} from './normalize';\nexport { normalizeAgentPluginMcpSource } from './sync';\n\ntype Context = Parameters<FileSystem['readTextFile']>[1];\n\nasync function realContainedPath(\n fs: FileSystem,\n root: string,\n candidate: string,\n label: string,\n context: Context,\n): Promise<string> {\n const real = await fs.canonicalPath(candidate, context);\n if (!real.ok) throw new Error(`${label} does not exist`);\n if (!isInside(root, real.value)) throw new Error(`${label} escapes its allowed plugin directory`);\n return real.value;\n}\n\nasync function normalizeCommand(\n fs: FileSystem,\n command: string,\n pluginRoot: string,\n context: Context,\n): Promise<string> {\n if (!isPluginRelativeCommand(command)) return command;\n const resolved = await realContainedPath(fs, pluginRoot, path.resolve(pluginRoot, command), 'command', context);\n if (getOrThrow(await fs.fileInfo(resolved, context)).kind !== 'file') {\n throw new Error('command must resolve to a regular file');\n }\n // Execute bits stand in for access(X_OK); the edge has no modes, so nodeHost reports none and the check is skipped.\n const mode = await nodeHost.fileMode(resolved);\n if (mode !== undefined && (mode & 0o111) === 0) throw new Error('command must resolve to an executable file');\n return resolved;\n}\n\nasync function normalizeWorkingDirectory(\n fs: FileSystem,\n declared: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n context: Context,\n): Promise<string> {\n const declaredCwd = workingDirectoryCandidate(declared, pluginRoot, pluginDataDirectory);\n if (!declaredCwd) return pluginRoot;\n const resolved = await realContainedPath(fs, declaredCwd.base, declaredCwd.candidate, 'cwd', context);\n if (getOrThrow(await fs.fileInfo(resolved, context)).kind !== 'directory') {\n throw new Error('cwd must resolve to a directory');\n }\n return resolved;\n}\n\nasync function normalizeServer(\n fs: FileSystem,\n raw: unknown,\n pluginRoot: string,\n pluginDataDirectory: string,\n name: string,\n context: Context,\n): Promise<NormalizedServer> {\n const type = serverType(raw, name);\n const declaration = raw as JsonObject;\n if (type !== 'stdio') return remoteServer(declaration, name, type);\n const command = await normalizeCommand(fs, nonEmptyString(declaration.command, 'command'), pluginRoot, context);\n const args = optionalStringArray(declaration.args, 'args')?.map((item) =>\n expandPluginPlaceholders(item, pluginRoot, pluginDataDirectory),\n );\n const env = normalizeEnvironment(declaration.env, pluginRoot, pluginDataDirectory);\n const cwd = await normalizeWorkingDirectory(fs, declaration.cwd, pluginRoot, pluginDataDirectory, context);\n return stdioServer(name, { command, ...(args ? { args } : {}), env, cwd });\n}\n\n/** Owner-only plugin data directory; a symbolic link or non-directory rejects the source. */\nasync function preparePluginDataDirectory(fs: FileSystem, directory: string, context: Context): Promise<string> {\n const info = await fs.fileInfo(directory, context);\n if (info.ok) {\n if (info.value.kind !== 'directory') throw new Error('pluginDataDirectory must be a real directory');\n } else if (info.error.code === 'not_found') {\n getOrThrow(await fs.createDir(directory, { recursive: true }, context));\n } else {\n throw info.error;\n }\n await nodeHost.setMode(directory, PRIVATE_DIRECTORY_MODE);\n return getOrThrow(await fs.canonicalPath(directory, context));\n}\n\n/**\n * Content-addressed and owner-only. The name hashes the contents, so replacing an\n * existing staged file through a uniquely named temporary file never changes what it holds.\n */\nasync function writeStagedInternalConfig(\n fs: FileSystem,\n target: string,\n contents: string,\n stagingDirectory: string,\n context: Context,\n): Promise<void> {\n getOrThrow(await fs.createDir(stagingDirectory, { recursive: true }, context));\n await nodeHost.setMode(stagingDirectory, PRIVATE_DIRECTORY_MODE);\n await writeFileAtomic(fs, target, contents, context);\n await nodeHost.setMode(target, PRIVATE_FILE_MODE);\n}\n\n/**\n * Validates one Agent Plugins v1 `mcp.json` and stages a native mcp-proxy layer,\n * reading and writing through the injected file system.\n *\n * Server validation is isolated: one malformed server is diagnosed and skipped.\n * Document/schema, source identity, or plugin-boundary failures reject the whole\n * source. Only the two portable plugin placeholders are expanded; the staged\n * layer is tagged `internal`, so legacy `${ENV}` interpolation cannot run again.\n */\nexport async function normalizeAgentPluginMcpSourceAsync(\n fs: FileSystem,\n source: PoMcpAgentPluginProjectionSource,\n options: NormalizeAgentPluginMcpOptions,\n context: Context,\n): Promise<NormalizedAgentPluginMcpSource> {\n const label = sourceLabel(source);\n try {\n assertProjectionSource(source);\n const pluginRoot = getOrThrow(await fs.canonicalPath(source.pluginRoot, context));\n const pluginDataDirectory = await preparePluginDataDirectory(fs, source.pluginDataDirectory, context);\n const configPath = await realContainedPath(fs, pluginRoot, source.configPath, 'mcp.json', context);\n assertRootConfigPath(configPath, pluginRoot);\n\n const bytes = getOrThrow(await fs.readBinaryFile(configPath, context));\n const servers = parseMcpDocument(source, bytes, label);\n const internalServers = Object.create(null) as Record<string, JsonObject>;\n const claudeServers = Object.create(null) as Record<string, JsonObject>;\n const droppedServers: string[] = [];\n const diagnostics: string[] = [];\n\n for (const [name, rawServer] of Object.entries(servers)) {\n const disposition = serverDisposition(name, options);\n if (disposition === 'empty') {\n diagnostics.push(emptyServerDiagnostic(label));\n continue;\n }\n if (disposition === 'dropped') {\n droppedServers.push(name);\n continue;\n }\n try {\n const normalized = await normalizeServer(fs, rawServer, pluginRoot, pluginDataDirectory, name, context);\n internalServers[name] = normalized.internal;\n claudeServers[name] = normalized.claude;\n } catch (error) {\n droppedServers.push(name);\n diagnostics.push(skippedServerDiagnostic(label, name, error));\n }\n }\n\n const contents = stagedContents(internalServers);\n const target = stagedInternalPath(source, contents, options.stagingDirectory);\n await writeStagedInternalConfig(fs, target, contents, options.stagingDirectory, context);\n return {\n configSource: { path: target, format: 'internal', cacheKey: stagedCacheKey(source, configPath, contents) },\n claudeConfig: { mcpServers: claudeServers },\n serverNames: Object.keys(internalServers),\n droppedServers,\n diagnostics,\n };\n } catch (error) {\n return disabledResult(label, error);\n }\n}\n"],"mappings":";;;;;;;;AAOA,MAAM,aAAa;;AAEnB,MAAM,iCAAiC;AACvC,MAAM,aAAa;AACnB,MAAM,eAAe,IAAI,OAAO,IAAI,WAAW,QAAQ,WAAW,QAAQ,GAAG;AAE7E,SAAS,OAAO,OAAwB;CACtC,OAAO,aAAa,KAAK,KAAK;AAChC;AAIA,MAAa,4CAA4B,IAAI,IAAI,CAAC,eAAe,aAAa,CAAC;AAC/E,MAAa,uCAAuB,IAAI,IAAI,CAAC,aAAa,eAAe,CAAC;AAiC1E,SAAgB,SAAS,OAAqC;CAC5D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,SAAS,OAAmB,SAA4B,OAAqB;CAC3F,MAAM,aAAa,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,QAAQ,CAAC,QAAQ,SAAS,GAAG,CAAC;CAC1E,IAAI,YAAY,MAAM,IAAI,MAAM,GAAG,MAAM,+BAA+B,WAAW,EAAE;AACvF;AAEA,SAAgB,eAAe,OAAgB,OAAuB;CACpE,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,MAAM,IAAI,MAAM,GAAG,MAAM,4BAA4B;CAC1G,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAAgB,OAAqC;CACvF,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,MAAM,IAAI,MAAM,GAAG,MAAM,6BAA6B;CACjF,OAAO,MAAM,KAAK,MAAM,UAAU;EAChC,IAAI,OAAO,SAAS,UAAU,MAAM,IAAI,MAAM,GAAG,MAAM,GAAG,MAAM,mBAAmB;EACnF,OAAO;CACT,CAAC;AACH;AAEA,SAAS,qBAAqB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M;IAAQ,QAAQ;IAAY,UAAU,eAAe,QAAQ,YAAY,QAAQ;GAAE;GACzG,cAAc,EAAE,YAAY,cAAc;GAC1C,aAAa,OAAO,KAAK,eAAe;GACxC;GACA;EACF;CACF,SAAS,OAAO;EACd,OAAO,eAAe,OAAO,KAAK;CACpC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiContracts.cjs","names":["Type","jsonApiResponses","defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract, jsonApiResponses, type
|
|
1
|
+
{"version":3,"file":"apiContracts.cjs","names":["Type","jsonApiResponses","defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract, jsonApiResponses, type PoHttpContract } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst Text = Type.String();\nconst Optional = Type.Optional;\nconst Strings = Type.Array(Text);\nconst NullableText = Type.Union([Text, Type.Null()]);\nconst Scope = Type.Union([Type.Literal('global'), Type.Literal('repository')]);\nconst Origin = Type.Union([Type.Literal('global'), Type.Literal('repository'), Type.Literal('default')]);\nexport const SettingsConfigSchema = Type.Object({\n repoRoot: Text,\n hashes: Type.Object({ global: Text, repository: Text }),\n values: Type.Record(\n Text,\n Type.Object({\n value: Optional(Text),\n origin: Origin,\n scope: Type.Union([Scope, Type.Literal('both')]),\n }),\n ),\n});\nconst SettingsEditSchema = Type.Object({ keyPath: Strings, value: Type.Union([Text, Type.Number(), Type.Null()]) });\nexport const SettingsWriteSchema = Type.Union([\n Type.Object({ repoRoot: Text, scope: Scope, ...SettingsEditSchema.properties, expectedHash: Text }),\n Type.Object({\n repoRoot: Text,\n scope: Scope,\n edits: Type.Array(SettingsEditSchema, { minItems: 1, maxItems: 100 }),\n expectedHash: Text,\n }),\n]);\n\nconst Repository = Type.Object({ id: Text, name: Text, path: Text, active: Type.Boolean() });\nconst Catalog = Type.Array(\n Type.Object({ name: Text, description: Optional(Text), expandsTo: Optional(Strings), layers: Optional(Strings) }),\n);\nconst SelectionText = Type.Object({ effective: Optional(Text), repository: Optional(Text), origin: Origin });\nconst SelectionStrings = Type.Object({ effective: Optional(Strings), repository: Optional(Strings), origin: Origin });\nexport const RepositorySettingsSchema = Type.Object({\n repository: Repository,\n hash: Text,\n catalogs: Type.Object({ majorModes: Catalog, domains: Catalog, profiles: Catalog }),\n selection: Type.Object({ majorMode: SelectionText, domains: SelectionStrings, profile: SelectionText }),\n});\nexport const RepositorySelectionWriteSchema = Type.Object({\n repositoryId: Text,\n expectedHash: Text,\n changes: Type.Object({\n majorMode: Optional(NullableText),\n domains: Optional(Type.Union([Strings, Type.Null()])),\n profile: Optional(NullableText),\n }),\n});\nconst Images = Type.Object({\n autoResize: Type.Boolean(),\n maxDimension: Type.Number(),\n minDimension: Type.Number(),\n maxAllowedDimension: Type.Number(),\n});\nconst http: PoHttpContract[] = (['global', 'workspace'] as const).flatMap((scope) => {\n const common = { scope, basePath: 'settings', authentication: 'owner' as const };\n return [\n {\n ...common,\n id: 'config',\n path: '/',\n method: 'GET',\n description: 'Read selected settings keys and file hashes.',\n parameters: [{ name: 'key', in: 'query', required: false, schema: Strings }],\n responses: jsonApiResponses(SettingsConfigSchema),\n },\n {\n ...common,\n id: 'value',\n path: '/value',\n method: 'PUT',\n description: 'Write a setting with an optimistic file hash.',\n body: { contentType: 'application/json', required: true, schema: SettingsWriteSchema },\n responses: jsonApiResponses(SettingsConfigSchema),\n },\n {\n ...common,\n id: 'repositories',\n path: '/repositories',\n method: 'GET',\n description: 'List admitted repositories.',\n responses: jsonApiResponses(Type.Object({ repositories: Type.Array(Repository) })),\n },\n {\n ...common,\n id: 'repository',\n path: '/repository',\n method: 'GET',\n description: 'Read the mounted workspace catalog and selection.',\n availability: 'Requires a workspace mount; global returns 404.',\n responses: jsonApiResponses(RepositorySettingsSchema),\n },\n {\n ...common,\n id: 'selection',\n path: '/repository/selection',\n method: 'PUT',\n description: 'Update the mounted workspace selection.',\n availability: 'Requires a workspace mount; global returns 404.',\n body: { contentType: 'application/json', required: true, schema: RepositorySelectionWriteSchema },\n responses: jsonApiResponses(RepositorySettingsSchema),\n },\n ...(scope === 'global'\n ? [\n {\n ...common,\n id: 'images.get',\n path: '/images',\n method: 'GET' as const,\n description: 'Read image resizing limits.',\n responses: jsonApiResponses(Images),\n },\n {\n ...common,\n id: 'images.put',\n path: '/images',\n method: 'PUT' as const,\n description: 'Update image resizing settings; dimensions are clamped.',\n body: {\n contentType: 'application/json',\n required: true,\n schema: Type.Object({ autoResize: Optional(Type.Boolean()), maxDimension: Optional(Type.Number()) }),\n },\n responses: jsonApiResponses(Images),\n },\n ]\n : []),\n ] satisfies PoHttpContract[];\n});\nexport const apiContracts = defineApiContract({ version: 1, http, sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;;;;;AAGA,MAAM,OAAOA,QAAAA,KAAK,OAAO;AACzB,MAAM,WAAWA,QAAAA,KAAK;AACtB,MAAM,UAAUA,QAAAA,KAAK,MAAM,IAAI;AAC/B,MAAM,eAAeA,QAAAA,KAAK,MAAM,CAAC,MAAMA,QAAAA,KAAK,KAAK,CAAC,CAAC;AACnD,MAAM,QAAQA,QAAAA,KAAK,MAAM,CAACA,QAAAA,KAAK,QAAQ,QAAQ,GAAGA,QAAAA,KAAK,QAAQ,YAAY,CAAC,CAAC;AAC7E,MAAM,SAASA,QAAAA,KAAK,MAAM;CAACA,QAAAA,KAAK,QAAQ,QAAQ;CAAGA,QAAAA,KAAK,QAAQ,YAAY;CAAGA,QAAAA,KAAK,QAAQ,SAAS;AAAC,CAAC;AACvG,MAAa,uBAAuBA,QAAAA,KAAK,OAAO;CAC9C,UAAU;CACV,QAAQA,QAAAA,KAAK,OAAO;EAAE,QAAQ;EAAM,YAAY;CAAK,CAAC;CACtD,QAAQA,QAAAA,KAAK,OACX,MACAA,QAAAA,KAAK,OAAO;EACV,OAAO,SAAS,IAAI;EACpB,QAAQ;EACR,OAAOA,QAAAA,KAAK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M;GACN,QAAQ;GACR,aAAa;GACb,cAAc;GACd,YAAA,GAAWC,gCAAAA,iBAAAA,CAAiB,wBAAwB;EACtD;EACA;GACE,GAAG;GACH,IAAI;GACJ,MAAM;GACN,QAAQ;GACR,aAAa;GACb,cAAc;GACd,MAAM;IAAE,aAAa;IAAoB,UAAU;IAAM,QAAQ;GAA+B;GAChG,YAAA,GAAWA,gCAAAA,iBAAAA,CAAiB,wBAAwB;EACtD;EACA,GAAI,UAAU,WACV,CACE;GACE,GAAG;GACH,IAAI;GACJ,MAAM;GACN,QAAQ;GACR,aAAa;GACb,YAAA,GAAWA,gCAAAA,iBAAAA,CAAiB,MAAM;EACpC,GACA;GACE,GAAG;GACH,IAAI;GACJ,MAAM;GACN,QAAQ;GACR,aAAa;GACb,MAAM;IACJ,aAAa;IACb,UAAU;IACV,QAAQD,QAAAA,KAAK,OAAO;KAAE,YAAY,SAASA,QAAAA,KAAK,QAAQ,CAAC;KAAG,cAAc,SAASA,QAAAA,KAAK,OAAO,CAAC;IAAE,CAAC;GACrG;GACA,YAAA,GAAWC,gCAAAA,iBAAAA,CAAiB,MAAM;EACpC,CACF,IACA,CAAC;CACP;AACF,CAAC;AACD,MAAa,gBAAA,GAAeC,gCAAAA,kBAAAA,CAAkB;CAAE,SAAS;CAAG;CAAM,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract, jsonApiResponses, type
|
|
1
|
+
{"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract, jsonApiResponses, type PoHttpContract } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst Text = Type.String();\nconst Optional = Type.Optional;\nconst Strings = Type.Array(Text);\nconst NullableText = Type.Union([Text, Type.Null()]);\nconst Scope = Type.Union([Type.Literal('global'), Type.Literal('repository')]);\nconst Origin = Type.Union([Type.Literal('global'), Type.Literal('repository'), Type.Literal('default')]);\nexport const SettingsConfigSchema = Type.Object({\n repoRoot: Text,\n hashes: Type.Object({ global: Text, repository: Text }),\n values: Type.Record(\n Text,\n Type.Object({\n value: Optional(Text),\n origin: Origin,\n scope: Type.Union([Scope, Type.Literal('both')]),\n }),\n ),\n});\nconst SettingsEditSchema = Type.Object({ keyPath: Strings, value: Type.Union([Text, Type.Number(), Type.Null()]) });\nexport const SettingsWriteSchema = Type.Union([\n Type.Object({ repoRoot: Text, scope: Scope, ...SettingsEditSchema.properties, expectedHash: Text }),\n Type.Object({\n repoRoot: Text,\n scope: Scope,\n edits: Type.Array(SettingsEditSchema, { minItems: 1, maxItems: 100 }),\n expectedHash: Text,\n }),\n]);\n\nconst Repository = Type.Object({ id: Text, name: Text, path: Text, active: Type.Boolean() });\nconst Catalog = Type.Array(\n Type.Object({ name: Text, description: Optional(Text), expandsTo: Optional(Strings), layers: Optional(Strings) }),\n);\nconst SelectionText = Type.Object({ effective: Optional(Text), repository: Optional(Text), origin: Origin });\nconst SelectionStrings = Type.Object({ effective: Optional(Strings), repository: Optional(Strings), origin: Origin });\nexport const RepositorySettingsSchema = Type.Object({\n repository: Repository,\n hash: Text,\n catalogs: Type.Object({ majorModes: Catalog, domains: Catalog, profiles: Catalog }),\n selection: Type.Object({ majorMode: SelectionText, domains: SelectionStrings, profile: SelectionText }),\n});\nexport const RepositorySelectionWriteSchema = Type.Object({\n repositoryId: Text,\n expectedHash: Text,\n changes: Type.Object({\n majorMode: Optional(NullableText),\n domains: Optional(Type.Union([Strings, Type.Null()])),\n profile: Optional(NullableText),\n }),\n});\nconst Images = Type.Object({\n autoResize: Type.Boolean(),\n maxDimension: Type.Number(),\n minDimension: Type.Number(),\n maxAllowedDimension: Type.Number(),\n});\nconst http: PoHttpContract[] = (['global', 'workspace'] as const).flatMap((scope) => {\n const common = { scope, basePath: 'settings', authentication: 'owner' as const };\n return [\n {\n ...common,\n id: 'config',\n path: '/',\n method: 'GET',\n description: 'Read selected settings keys and file hashes.',\n parameters: [{ name: 'key', in: 'query', required: false, schema: Strings }],\n responses: jsonApiResponses(SettingsConfigSchema),\n },\n {\n ...common,\n id: 'value',\n path: '/value',\n method: 'PUT',\n description: 'Write a setting with an optimistic file hash.',\n body: { contentType: 'application/json', required: true, schema: SettingsWriteSchema },\n responses: jsonApiResponses(SettingsConfigSchema),\n },\n {\n ...common,\n id: 'repositories',\n path: '/repositories',\n method: 'GET',\n description: 'List admitted repositories.',\n responses: jsonApiResponses(Type.Object({ repositories: Type.Array(Repository) })),\n },\n {\n ...common,\n id: 'repository',\n path: '/repository',\n method: 'GET',\n description: 'Read the mounted workspace catalog and selection.',\n availability: 'Requires a workspace mount; global returns 404.',\n responses: jsonApiResponses(RepositorySettingsSchema),\n },\n {\n ...common,\n id: 'selection',\n path: '/repository/selection',\n method: 'PUT',\n description: 'Update the mounted workspace selection.',\n availability: 'Requires a workspace mount; global returns 404.',\n body: { contentType: 'application/json', required: true, schema: RepositorySelectionWriteSchema },\n responses: jsonApiResponses(RepositorySettingsSchema),\n },\n ...(scope === 'global'\n ? [\n {\n ...common,\n id: 'images.get',\n path: '/images',\n method: 'GET' as const,\n description: 'Read image resizing limits.',\n responses: jsonApiResponses(Images),\n },\n {\n ...common,\n id: 'images.put',\n path: '/images',\n method: 'PUT' as const,\n description: 'Update image resizing settings; dimensions are clamped.',\n body: {\n contentType: 'application/json',\n required: true,\n schema: Type.Object({ autoResize: Optional(Type.Boolean()), maxDimension: Optional(Type.Number()) }),\n },\n responses: jsonApiResponses(Images),\n },\n ]\n : []),\n ] satisfies PoHttpContract[];\n});\nexport const apiContracts = defineApiContract({ version: 1, http, sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;AAGA,MAAM,OAAO,KAAK,OAAO;AACzB,MAAM,WAAW,KAAK;AACtB,MAAM,UAAU,KAAK,MAAM,IAAI;AAC/B,MAAM,e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