feat: 将插件 stdin 协议定为 v1,并按声明注入凭据

进程外插件改为只读环境变量和自身配置,避免读宿主 appsettings;宿主按 plugin.json 声明注入 LLM / OpenWeather 等凭据。
This commit is contained in:
2026-09-11 10:46:52 +08:00
parent d1b979f2db
commit b631acd42e
22 changed files with 377 additions and 95 deletions
+37 -7
View File
@@ -32,18 +32,16 @@ public sealed class CredentialPublicView
/// </summary>
public sealed class CredentialStore
{
private readonly IConfiguration _config;
private readonly Dictionary<string, CredentialRecord> _named = new(StringComparer.OrdinalIgnoreCase);
public CredentialStore(IConfiguration config)
{
_config = config;
LlmOptions llm = AgentFactory.Load(config);
_named["llm-default"] = new CredentialRecord
{
Id = "llm-default",
Name = "系统默认模型",
Type = "openai-compatible",
Type = PluginCredentialTypes.OpenAiCompatible,
Endpoint = llm.Endpoint,
ApiKey = llm.ApiKey,
Model = llm.Model,
@@ -53,23 +51,38 @@ public sealed class CredentialStore
foreach (IConfigurationSection child in section.GetChildren())
{
string id = child.Key;
string type = child["type"] ?? "openai-compatible";
string type = child["type"] ?? PluginCredentialTypes.OpenAiCompatible;
bool useLlm = string.Equals(child["source"], "llm-section", StringComparison.OrdinalIgnoreCase)
|| child.GetValue("useLlmSection", false);
CredentialRecord fallback = _named.GetValueOrDefault("llm-default")!;
CredentialRecord fallback = _named["llm-default"];
Dictionary<string, string> extra = new(StringComparer.OrdinalIgnoreCase);
foreach (IConfigurationSection extraChild in child.GetSection("extra").GetChildren())
{
if (!string.IsNullOrWhiteSpace(extraChild.Value))
{
extra[extraChild.Key] = extraChild.Value;
}
}
string apiKey = First(
child["apiKey"],
useLlm ? fallback.ApiKey : null,
PluginCredentialTypes.IsOpenWeather(type) ? Environment.GetEnvironmentVariable("OPENWEATHER_API_KEY") : null);
_named[id] = new CredentialRecord
{
Id = id,
Name = child["name"] ?? id,
Type = type,
Endpoint = First(child["endpoint"], useLlm ? fallback.Endpoint : null),
ApiKey = First(child["apiKey"], useLlm ? fallback.ApiKey : null),
ApiKey = apiKey,
Model = First(child["model"], useLlm ? fallback.Model : null),
Extra = extra,
};
}
}
/// <summary>给前端的列表。Endpoint 目前未打码(学习项目);ApiKey 绝不会出现在这里。</summary>
/// <summary>给前端的列表。ApiKey 绝不会出现在这里。</summary>
public IReadOnlyList<CredentialPublicView> ListPublic()
=> _named.Values
.OrderBy(item => item.Id, StringComparer.OrdinalIgnoreCase)
@@ -91,6 +104,23 @@ public sealed class CredentialStore
throw new InvalidOperationException($"找不到凭据 `{id}`。请在 appsettings.json 的 Credentials 中配置,或改用 llm-default。");
}
/// <summary>按插件声明的 type 取凭据。preferredId 类型不匹配时不会凑合用。</summary>
public CredentialRecord? TryResolveForType(string declaredType, string? preferredId)
{
if (!string.IsNullOrWhiteSpace(preferredId) && _named.TryGetValue(preferredId, out CredentialRecord? named))
{
if (!PluginCredentialTypes.Matches(declaredType, named.Type))
{
throw new InvalidOperationException(
$"凭据 `{preferredId}` 的类型是 `{named.Type}`,插件声明需要 `{declaredType}`。");
}
return named;
}
return _named.Values.FirstOrDefault(item => PluginCredentialTypes.Matches(declaredType, item.Type));
}
public PluginCredentialPayload ToPayload(CredentialRecord record)
=> new()
{
+40 -32
View File
@@ -16,14 +16,16 @@ public sealed class PluginProcessRunner(PluginOptions options, CredentialStore c
LoadedPlugin plugin,
Dictionary<string, object?> inputs,
string? credentialId,
IReadOnlyDictionary<string, string>? credentialBindings,
CancellationToken cancellationToken)
{
PluginManifest manifest = plugin.Manifest;
ValidateDeclaredInputs(manifest, inputs);
Dictionary<string, PluginCredentialPayload> payload = ResolveCredentials(manifest, credentialId);
Dictionary<string, PluginCredentialPayload> payload = ResolveCredentials(manifest, credentialId, credentialBindings);
PluginRequest request = new()
{
ProtocolVersion = PluginProtocol.Normalize(manifest.ProtocolVersion),
Inputs = inputs,
Credentials = payload,
};
@@ -75,33 +77,58 @@ public sealed class PluginProcessRunner(PluginOptions options, CredentialStore c
return outputs;
}
private Dictionary<string, PluginCredentialPayload> ResolveCredentials(PluginManifest manifest, string? credentialId)
private Dictionary<string, PluginCredentialPayload> ResolveCredentials(
PluginManifest manifest,
string? credentialId,
IReadOnlyDictionary<string, string>? credentialBindings)
{
Dictionary<string, PluginCredentialPayload> map = new(StringComparer.OrdinalIgnoreCase);
foreach (PluginCredentialNeed need in manifest.Credentials)
{
if (need.Type is "openai-compatible" or "llm" || need.Name.Equals("llm", StringComparison.OrdinalIgnoreCase))
if (string.IsNullOrWhiteSpace(need.Type) && string.IsNullOrWhiteSpace(need.Name))
{
CredentialRecord record = credentials.Resolve(credentialId);
if (need.Required && string.IsNullOrWhiteSpace(record.ApiKey))
continue;
}
string declaredType = string.IsNullOrWhiteSpace(need.Type) ? need.Name : need.Type;
string? preferredId = null;
if (credentialBindings is not null
&& !string.IsNullOrWhiteSpace(need.Name)
&& credentialBindings.TryGetValue(need.Name, out string? bound)
&& !string.IsNullOrWhiteSpace(bound))
{
preferredId = bound;
}
else if (PluginCredentialTypes.IsLlm(declaredType) || need.Name.Equals("llm", StringComparison.OrdinalIgnoreCase))
{
preferredId = credentialId;
}
CredentialRecord? record = credentials.TryResolveForType(declaredType, preferredId);
if (record is null)
{
if (need.Required)
{
throw new InvalidOperationException(
$"插件 {manifest.Id} 需要 LLM 凭据,但 `{record.Id}` 没有 API Key。请在环境变量 OPENAI_API_KEY 或 appsettings.json 中配置。");
$"插件 {manifest.Id} 需要类型 `{declaredType}` 的凭据 `{need.Name}`,但宿主 Credentials 里没有匹配项。");
}
map[need.Name] = credentials.ToPayload(record);
continue;
}
}
if (manifest.Credentials.Count == 0)
{
map["llm"] = credentials.ToPayload(credentials.Resolve(credentialId));
if (need.Required && PluginCredentialTypes.IsLlm(declaredType) && string.IsNullOrWhiteSpace(record.ApiKey))
{
throw new InvalidOperationException(
$"插件 {manifest.Id} 需要 LLM 凭据,但 `{record.Id}` 没有 API Key。请在环境变量 OPENAI_API_KEY 或 appsettings.json 中配置。");
}
map[string.IsNullOrWhiteSpace(need.Name) ? declaredType : need.Name] = credentials.ToPayload(record);
}
return map;
}
/// <summary>工作目录=插件文件夹;环境变量带上 OPENAI_* 和 MAF1_CONTENT_ROOT。</summary>
/// <summary>工作目录=插件文件夹。凭据写入子进程环境变量,不读宿主 appsettings 路径。</summary>
private ProcessStartInfo CreateStartInfo(LoadedPlugin plugin, Dictionary<string, PluginCredentialPayload> payload)
{
string command = plugin.Manifest.Launch.Command;
@@ -132,32 +159,13 @@ public sealed class PluginProcessRunner(PluginOptions options, CredentialStore c
start.ArgumentList.Add(arg);
}
start.Environment["MAF1_CONTENT_ROOT"] = AppContext.BaseDirectory;
ApplyDotEnv(plugin.FolderPath, start);
foreach (KeyValuePair<string, string> pair in plugin.Manifest.Env)
{
start.Environment[pair.Key] = pair.Value;
}
if (payload.TryGetValue("llm", out PluginCredentialPayload? llm) || payload.Count > 0)
{
llm ??= payload.Values.First();
if (!string.IsNullOrWhiteSpace(llm.ApiKey))
{
start.Environment["OPENAI_API_KEY"] = llm.ApiKey;
}
if (!string.IsNullOrWhiteSpace(llm.Endpoint))
{
start.Environment["OPENAI_ENDPOINT"] = llm.Endpoint;
}
if (!string.IsNullOrWhiteSpace(llm.Model))
{
start.Environment["OPENAI_CHAT_MODEL"] = llm.Model;
}
}
PluginStdio.ApplyCredentialsToEnvironment(payload, start.Environment);
return start;
}
+14
View File
@@ -76,6 +76,20 @@ public sealed class PluginScanner(PluginOptions options)
continue;
}
int protocol = PluginProtocol.Normalize(manifest.ProtocolVersion);
if (!PluginProtocol.IsSupported(manifest.ProtocolVersion))
{
issues.Add(new CatalogIssue
{
Level = "error",
Source = manifest.Id,
Message = $"plugin.json 的 protocolVersion={protocol} 不受支持。当前宿主只接受 1(缺省视为 1)。",
});
continue;
}
manifest.ProtocolVersion = protocol;
if (!ids.Add(manifest.Id))
{
issues.Add(new CatalogIssue
+22 -1
View File
@@ -391,7 +391,28 @@ public sealed class ConfigurableWorkflowRunner(
{
Dictionary<string, object?> declared = FilterDeclaredInputs(plugin.Manifest, inputs);
node.Config.TryGetValue("credentialId", out string? credentialId);
Dictionary<string, object?> outputs = await plugins.RunAsync(plugin, declared, credentialId, cancellationToken);
Dictionary<string, string> bindings = new(StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair<string, string> pair in node.Config)
{
const string prefix = "credential:";
if (!pair.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
continue;
}
string name = pair.Key[prefix.Length..].Trim();
if (!string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(pair.Value))
{
bindings[name] = pair.Value;
}
}
Dictionary<string, object?> outputs = await plugins.RunAsync(
plugin,
declared,
credentialId,
bindings,
cancellationToken);
string? stderr = null;
if (outputs.Remove("_stderr", out object? stderrValue))
{
+5
View File
@@ -16,6 +16,11 @@
"type": "openai-compatible",
"name": "系统默认模型",
"source": "llm-section"
},
"openweather-default": {
"type": "openweather",
"name": "OpenWeather",
"apiKey": ""
}
},
"Weather": {
+49 -5
View File
@@ -7,7 +7,7 @@
* 3. runGraph POST /api/run;若 status=needsDecision 弹出确认框
* 4. 确认走 /api/run/{id}/decide;超时则 pollRun 等服务端自动采用默认方案
*
* selected / pending 只用于点击交互。发给后端的 JSON 不含 API Key,只有 credentialId。
* selected / pending 只用于点击交互。发给后端的 JSON 不含 API Key,只有 credentialId / credential:名称
*/
const state = {
catalog: [],
@@ -51,6 +51,50 @@ function typeInfo(type) {
|| state.plugins.find((item) => item.type === type);
}
function isLlmCredentialType(type) {
const t = (type || "").toLowerCase();
return t === "openai-compatible" || t === "llm";
}
function credentialConfigKey(need) {
if (isLlmCredentialType(need.type) || (need.name || "").toLowerCase() === "llm") {
return "credentialId";
}
return "credential:" + need.name;
}
function credentialsMatching(type) {
return (state.credentials || []).filter((c) => {
if (isLlmCredentialType(type) && isLlmCredentialType(c.type)) {
return true;
}
return (c.type || "").toLowerCase() === (type || "").toLowerCase();
});
}
function renderCredentialFields(node, info) {
const needs = info.credentials || [];
if (needs.length === 0) {
return `<p class="hint">此节点未声明凭据,宿主不会注入 API Key。</p>`;
}
return needs.map((need) => {
const cfgKey = credentialConfigKey(need);
const options = credentialsMatching(need.type);
const current = node.config[cfgKey] || (options[0] ? options[0].id : "");
if (current && !node.config[cfgKey]) {
node.config[cfgKey] = current;
}
const label = need.name + (need.required ? " *" : "(可选)");
if (options.length === 0) {
return `<label>凭据 ${label}</label><p class="hint">宿主没有类型 ${need.type} 的凭据。</p>`;
}
const opts = options.map((c) =>
`<option value="${c.id}" ${current === c.id ? "selected" : ""}>${c.name}${c.hasApiKey ? "已配置 Key" : "缺少 Key"}</option>`
).join("");
return `<label>凭据 ${label}</label><select data-credential-config="${cfgKey}">${opts}</select>`;
}).join("") + `<p class="hint">Key 由宿主注入子进程,不会出现在端口或导出的流程图里。</p>`;
}
function pickNode(list, inputName) {
return (list || []).find((item) => item.inputs?.some((p) => p.name === inputName));
}
@@ -252,9 +296,7 @@ function renderInspector() {
<p class="hint">${info.description}</p>
<label>显示名</label>
<input id="title" value="${node.title}" />
<label>LLM 凭据</label>
<select id="credentialId">${(state.credentials || []).map((c) => `<option value="${c.id}" ${ (node.config.credentialId || "llm-default") === c.id ? "selected" : ""}>${c.name}${c.hasApiKey ? "已配置 Key" : "缺少 Key"}</option>`).join("")}</select>
<p class="hint">endpoint / API Key 由宿主注入进程,不会出现在输入端口或导出的流程图里。</p>
${renderCredentialFields(node, info)}
${info.inputs.map((p) => `
<label>固定输入 ${p.name}${p.type}${p.required ? " *" : ""}</label>
<input data-config="${p.name}" value="${node.config[p.name] ?? ""}" placeholder="${p.description}" />
@@ -262,7 +304,9 @@ function renderInspector() {
<p class="hint">若该输入已从上一节点连线,运行时以连线为准。</p>
<button type="button" id="delNode">删除节点</button>`;
inspector.querySelector("#title").oninput = (e) => { node.title = e.target.value; };
inspector.querySelector("#credentialId")?.addEventListener("change", (e) => { node.config.credentialId = e.target.value; });
inspector.querySelectorAll("[data-credential-config]").forEach((select) => {
select.addEventListener("change", () => { node.config[select.dataset.credentialConfig] = select.value; });
});
inspector.querySelectorAll("[data-config]").forEach((input) => {
input.oninput = () => { node.config[input.dataset.config] = input.value; };
});