Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(integrations): add JEV variables and AI providers tab

Rahmand83d01bba433
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.ts
index 56cbb451..cec23c46 100644
--- a/app/api/v1/workflows/route.ts
+++ b/app/api/v1/workflows/route.ts
@@ -26,6 +26,7 @@ import { listLearnedRecipes, recipeMaturity } from "@/lib/workflow";
import { createWorkflowDataTable, deleteWorkflowDataTable, deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "@/lib/workflow/data-table-store";
import { optimizeWorkflowGraph } from "@/lib/workflow/graph-optimizer";
import { createJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-optimizer";
+import { resolveJevIntegrationConfig } from "@/lib/workflow/jev-integration";
export const runtime="nodejs";export const dynamic="force-dynamic";const headers={"Cache-Control":"no-store, private"};
const fail=(error:unknown,status=400)=>NextResponse.json({error:error instanceof Error?error.message.slice(0,500):String(error).slice(0,500)||"workflow request failed"},{status,headers});
async function auth(minimum:"viewer"|"operator"|"owner"="viewer"){const context=await getSessionContext();if(!context?.session.device_id||!roleAtLeast(context.role,minimum))return null;return{context,principal:`web:${context.session.device_id}`};}
@@ -68,9 +69,7 @@ export async function POST(req:NextRequest){const session=await auth("operator")
const mode=body.mode==="jev"?"jev" as const:"deterministic" as const;let evaluator;
if(mode==="jev"){
if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);
- const jev=body.jev;if(!jev||typeof jev!=="object"||Array.isArray(jev))throw new Error("jev connection reference is required");
- const ref=jev as Record<string,unknown>;if(typeof ref.user!=="string"||typeof ref.connection!=="string")throw new Error("jev user and connection are required");
- evaluator=createJevWorkflowOptimizerEvaluator({user:ref.user,connection:ref.connection,...(typeof ref.tool==="string"?{tool:ref.tool}:{}),...(typeof ref.model==="string"?{model:ref.model}:{})});
+ evaluator=createJevWorkflowOptimizerEvaluator(await resolveJevIntegrationConfig(body.jev));
}
const optimized=await optimizeWorkflowGraph(graph,{mode,threshold:Number(body.threshold)||undefined,applyReview:body.apply_review===true,evaluator,resolveTool:name=>TOOLS_BY_NAME.get(name)});
if(action==="optimize_preview")return NextResponse.json({optimization:optimized.preview},{headers});
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
index 4d0fbfe3..a16d19b0 100644
--- a/docs/INTEGRATIONS.md
+++ b/docs/INTEGRATIONS.md
@@ -32,6 +32,22 @@ are ambiguous and refused. An explicit missing user/connection is never replaced
a default from somewhere else. Compound direct operations pin resolved values for
their duration; concurrent work cannot mix two profiles partway through one operation.
+
+### Integration Variables
+
+Integration Variables are global, metadata-only aliases to an existing named connection,
+for example JEV → credential-user / mcp / jev. A variable stores only provider, user and
+connection references; it never copies endpoint, API key, bearer token, OAuth bundle or
+connection field values. Names use uppercase A-Z, 0-9 and underscore. integration_manage
+owns variable.set / variable.delete, while integration_query with view=variables returns
+only those safe references. User rename updates references. Deleting a referenced
+user/connection is refused until the variable is removed or retargeted.
+
+When a pre-variable v2 store already contains one unambiguous mcp/jev connection, the
+upgrade projection seeds JEV in memory. An explicitly stored variable map, including an
+explicit empty map, wins and is never silently re-seeded. This gives existing Jev installs
+a safe default without hardcoding an operator/user ID.
+
## Sources are not authentication methods
**MSO direct** stores owner-only local credential fields. **Composio** keeps the
@@ -106,9 +122,15 @@ Desktop uses the shared Settings sidebar/content measure tokens; compact windows
same sidebar into an accessible drawer. Providers live under **Connections**. Visual
surfaces, accent, typography, radius and spacing come from the shared semantic token
contract, and the native iframe synchronizes those tokens from the active AppShell.
-**Credential owners**, **Project routing**, **Transfer & backup**, and **Add project MCP**
-live under **Manage**. Section state stays selected when the credential owner changes,
-and Transfer & backup renders in the detail pane instead of replacing the navigation.
+**AI Providers**, **Variables**, **Credential owners**, **Project routing**,
+**Transfer & backup**, and **Add project MCP** live under **Manage**. The AI Providers tab
+reuses the existing Alfa /api/config, /api/models/providers, /api/models, /api/models/test,
+and /api/oauth/openai services as its single source of truth: active provider/model
+selection, API-key updates, provider tests, OpenAI account authorization, custom-provider
+creation and disconnect all use the same runtime/config store as Settings. It does not
+create an Integrations copy of AI credentials. Section state stays selected when the
+credential owner changes, and Transfer & backup renders in the detail pane instead of
+replacing the navigation.
The secure credential-entry form remains an intentional drill-down from a connection.
When an agent needs external access, it must inspect Integrations before asking for a new
@@ -214,9 +236,10 @@ mso integrations execute '{"user":"rahman","provider":"dokploy","connection":"pr
## Machine tools and operation coverage
-`integration_query` reads catalog/users/connections, resolves an identity, and returns
-source-aware setup instructions. `integration_manage` performs confirmed user,
-connection, folder-binding, credential-deletion or hosted-authorization actions.
+`integration_query` reads catalog/users/connections/Integration Variables, resolves an
+identity, and returns source-aware setup instructions. `integration_manage` performs
+confirmed user, connection, Integration Variable, folder-binding, credential-deletion or
+hosted-authorization actions.
`integration_execute` takes explicit user/provider/connection and returns a route,
verifies that connection, performs supported bounded direct operations, executes
a toolkit-matching Composio tool using its exact connected account, or calls one exact
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 8545ff75..58c34fcd 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,11 @@
+## 2026-09-24 — Integrations Variables + native AI Providers tab
+
+Integrations now has metadata-only variables that alias an exact named connection without copying credentials. variable.set / variable.delete are part of the existing integration_manage authority, integration_query view=variables exposes only safe references, rename/delete invariants prevent stale aliases, and an existing pre-variable mcp/jev connection can project a JEV alias without hardcoding a user. Workflow Optimizer Jev mode resolves JEV by default while preserving an explicit diagnostic override; endpoint/token remain private in Integrations.
+
+The native Integrations Settings-style manager adds **Variables** and **AI Providers** under Manage. AI Providers reuses Alfa's existing /api/config, /api/models/providers, /api/models, /api/models/test, and /api/oauth/openai surfaces for active provider/model selection, API-key updates, tests, OpenAI authorization, custom providers and disconnect. It does not introduce a second AI credential store. The MCP Page keeps secret-bearing AI management browser-only and links into the native page.
+
+Focused verification: 7 Vitest files, 34/34 tests passed for Integrations identity/variables, MCP contracts, direct MCP dispatch, Jev variable resolution/adapter, Workflow optimizer actions, and Integrations UI layout/script parsing. Full type/build/release verification follows before merge/deploy.
+
## 2026-09-24 — Add review-first Jev Flow Optimizer for Workflow Graph
MSO Workflow Graph now has a compact optimizer path without adding another global MCP tool. The existing `workflow_graph` surface owns `optimize_preview` and `optimize_clone`: preview never mutates the source graph, while clone requires the exact current revision and creates a new draft only when at least one optimization candidate is selected. The original workflow remains immutable during optimization.
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index 6a3d2df9..3da3c159 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -234,9 +234,9 @@ Decision modes:
- `jev` sends only the compact workflow summary plus host-generated candidate descriptions to a named generic MCP Integration. The graph arguments themselves, credentials and capability authority stay in MSO. Jev can score the candidates; it cannot invent a new tool call, alter arguments, authorize an action, or execute anything. The preview also computes a deterministic shadow baseline and reports agreement/disagreement so rollout can be measured before relying more heavily on Jev.
- If the Jev call fails or returns no usable probability, the preview records `provider: fallback` and uses the deterministic scores.
-For Jev, create a normal **Integrations → Project MCP** named connection to the reviewed Jev MCP endpoint, keep the bearer key in the private Integrations form, and optionally pin `allowedTools` to the exact decision tool (for example `jev_decide`). The workflow stores only the non-secret Integration user/connection reference supplied at optimization time.
+For Jev, create a normal **Integrations → Project MCP** named connection to the reviewed Jev MCP endpoint, keep the bearer key in the private Integrations form, and optionally pin allowedTools to the exact decision tool (for example jev_decide). Point the metadata-only **Integration Variable JEV** at that named connection. Jev optimization resolves JEV by default; an explicit user/connection override remains available for diagnostics or alternate evaluators. Neither path stores the endpoint/token in the Workflow Graph.
-The native Workflows UI exposes **Optimize** and a Flow Optimizer detail panel. Dirty graph edits are saved before opening the optimizer so preview/clone always operate on the revision the user can see.
+The native Workflows UI exposes **Optimize** and a Flow Optimizer detail panel. Dirty graph edits are saved before opening the optimizer so preview/clone always operate on the revision the user can see. Jev mode now shows JEV as the normal path, with explicit connection fields moved under an optional override.
## Automatic learning
diff --git a/frontend/slices/workflows/components/workflow-optimizer-panel.tsx b/frontend/slices/workflows/components/workflow-optimizer-panel.tsx
index 890da885..d8e62f90 100644
--- a/frontend/slices/workflows/components/workflow-optimizer-panel.tsx
+++ b/frontend/slices/workflows/components/workflow-optimizer-panel.tsx
@@ -25,10 +25,16 @@ export function WorkflowOptimizerPanel({ graph, onCloned }: {
const options = (): WorkflowOptimizeOptions => ({
mode,
applyReview,
- ...(mode === "jev" ? { jev: { user: user.trim(), connection: connection.trim() } } : {}),
+ ...(mode === "jev" ? {
+ jev: user.trim() && connection.trim()
+ ? { user: user.trim(), connection: connection.trim() }
+ : { variable: "JEV" },
+ } : {}),
});
- const valid = mode === "deterministic" || Boolean(user.trim() && connection.trim());
+ const hasUser = Boolean(user.trim());
+ const hasConnection = Boolean(connection.trim());
+ const valid = mode === "deterministic" || hasUser === hasConnection;
const analyze = async () => {
setBusy(true); setMessage("");
try { setPreview(await optimizeGraphPreview(graph, options())); }
@@ -62,9 +68,17 @@ export function WorkflowOptimizerPanel({ graph, onCloned }: {
</select>
</label>
{mode === "jev" ? <div className="grid gap-2">
- <p className="text-[11px] leading-relaxed text-muted-foreground">Use a named Integrations → Project MCP connection. Endpoint/token remain in Integrations and never enter the workflow graph.</p>
- <Input className={inputClass} value={user} onChange={(event) => setUser(event.target.value)} placeholder="Credential user ID"/>
- <Input className={inputClass} value={connection} onChange={(event) => setConnection(event.target.value)} placeholder="MCP connection ID, e.g. jev"/>
+ <div className="rounded-md border border-dashed p-2 text-[11px] leading-relaxed text-muted-foreground">
+ Uses Integrations variable <b className="text-foreground">JEV</b> by default. The variable only points to a named MCP connection; endpoint and token remain private in Integrations.
+ </div>
+ <details className="rounded-md border p-2">
+ <summary className="cursor-pointer text-xs font-medium">Override JEV connection</summary>
+ <div className="mt-2 grid gap-2">
+ <Input className={inputClass} value={user} onChange={(event) => setUser(event.target.value)} placeholder="Credential user ID"/>
+ <Input className={inputClass} value={connection} onChange={(event) => setConnection(event.target.value)} placeholder="MCP connection ID"/>
+ {hasUser !== hasConnection ? <p className="text-[11px] text-destructive">Fill both override fields, or leave both empty to use JEV.</p> : null}
+ </div>
+ </details>
</div> : null}
<label className="flex items-start gap-2 text-xs">
<input className="mt-0.5" type="checkbox" checked={applyReview} onChange={(event) => { setApplyReview(event.target.checked); setPreview(null); }}/>
diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.ts
index 3259f62e..bf65f074 100644
--- a/frontend/slices/workflows/lib/api.ts
+++ b/frontend/slices/workflows/lib/api.ts
@@ -35,7 +35,7 @@ export async function deleteDataTable(id:string){return post<{id:string;deleted:
export async function upsertDataTableRow(tableId:string,values:Record<string,unknown>,rowId?:string){return(await post<{row:WorkflowDataTableRow}>({action:"data_table_row_upsert",table_id:tableId,...(rowId?{row_id:rowId}:{}),values})).row;}
export async function deleteDataTableRow(tableId:string,rowId:string){return post<{tableId:string;rowId:string;deleted:boolean}>({action:"data_table_row_delete",table_id:tableId,row_id:rowId});}
export async function aiSuggest(prompt:string){return(await post<{definition:Omit<WorkflowGraph,"version"|"id"|"revision"|"createdAt"|"updatedAt">}>({action:"ai_suggest",prompt})).definition;}
-export type WorkflowOptimizeOptions={mode?:"deterministic"|"jev";threshold?:number;applyReview?:boolean;jev?:{user:string;connection:string;tool?:string;model?:string}};
+export type WorkflowOptimizeOptions={mode?:"deterministic"|"jev";threshold?:number;applyReview?:boolean;jev?:{variable?:string;user?:string;connection?:string;tool?:string;model?:string}};
export async function optimizeGraphPreview(graph:WorkflowGraph,options:WorkflowOptimizeOptions={}){return(await post<{optimization:WorkflowOptimizationPreview}>({action:"optimize_preview",graph_id:graph.id,mode:options.mode??"deterministic",threshold:options.threshold,apply_review:options.applyReview===true,...(options.jev?{jev:options.jev}:{})})).optimization;}
export async function optimizeGraphClone(graph:WorkflowGraph,options:WorkflowOptimizeOptions={}){const result=await post<{graph:WorkflowGraph;optimization:WorkflowOptimizationPreview}>({action:"optimize_clone",graph_id:graph.id,expected_revision:graph.revision,mode:options.mode??"deterministic",threshold:options.threshold,apply_review:options.applyReview===true,...(options.jev?{jev:options.jev}:{})});invalidateWorkflowResources("graphs");seedWorkflowResource(`graph:${result.graph.id}`,result.graph,8000);return result;}
export async function resolveNode(graphId:string,nodeId:string){return json<{project:string;name:string;path:string;relativePath:string}>(`/api/v1/workflows?graph_id=${encodeURIComponent(graphId)}&node_id=${encodeURIComponent(nodeId)}&resolve=target`);}
diff --git a/lib/infra/connection-manage.ts b/lib/infra/connection-manage.ts
index b9cff3d3..3cb4d92b 100644
--- a/lib/infra/connection-manage.ts
+++ b/lib/infra/connection-manage.ts
@@ -1,18 +1,21 @@
+import { variableKey, assertNoVariableReferences } from "./connection-variables";
import {connectionMethod} from "./connection-registry";
import { randomUUID } from "node:crypto";
import { mutateIntegrationState } from "./connection-storage";
import { createConnectionIn, summaryIn } from "./connection-service";
import { IntegrationError, identity, connectionLabel, canonicalFolder, selectConnection, metadataOnly, assertNotBusy, type ConnectionSource } from "./identity";
-export const INTEGRATION_ACTIONS=["user.create","user.rename","user.duplicate","user.delete","user.default","folder.map","folder.unmap","connection.create","connection.rename","connection.default","connection.delete","connection.share","connection.duplicate","connection.unshare","credential.delete"] as const;
+export const INTEGRATION_ACTIONS=["variable.set","variable.delete","user.create","user.rename","user.duplicate","user.delete","user.default","folder.map","folder.unmap","connection.create","connection.rename","connection.default","connection.delete","connection.share","connection.duplicate","connection.unshare","credential.delete"] as const;
export async function integrationManage(input:Record<string,unknown>){
metadataOnly(input);if(input.confirm!==true)throw new IntegrationError("confirmation_required",403);
const shapes:Record<string,string[]>={
+ "variable.set":["key","user","provider","connection"],"variable.delete":["key"],
"user.create":["user","label"],"user.rename":["user","target","label"],"user.duplicate":["user","target","label","copyCredentials"],"user.delete":["user"],"user.default":["user"],
"folder.map":["user","path","provider","connection"],"folder.unmap":["path"],"connection.create":["user","provider","connection","label","source","authMethod","makeDefault"],
"connection.rename":["user","provider","connection","label"],"connection.default":["user","provider","connection"],"connection.delete":["user","provider","connection"],"connection.share":["user","provider","connection","target","label","makeDefault"],"connection.duplicate":["user","provider","connection","target","targetConnection","label","copyCredentials","makeDefault"],"connection.unshare":["user","provider","connection"],"credential.delete":["user","provider","connection","key"],
};
const action=String(input.action);if(!shapes[action]||Object.keys(input).some(k=>!["action","confirm",...shapes[action]].includes(k)))throw new IntegrationError("invalid_management_fields");
return mutateIntegrationState(state=>{
+ if(action==="variable.set"||action==="variable.delete"){const key=variableKey(input.key);state.variables??={};if(action==="variable.delete")delete state.variables[key];else{const provider=identity(input.provider),user=identity(input.user),connection=identity(input.connection);selectConnection(state,provider,{user,connection});state.variables[key]={provider,user,connection};}return{ok:true,action,variables:state.variables};}
if(action==="folder.unmap"){const p=canonicalFolder(String(input.path));state.bindings=state.bindings.filter(b=>b.path!==p);return{ok:true,action};}
const user=identity(input.user,"user");
if(action==="user.create"){
@@ -22,6 +25,7 @@ export async function integrationManage(input:Record<string,unknown>){
const profile=state.users[user];if(!profile)throw new IntegrationError("user_not_found",404);
if(action==="user.default"){state.defaultUser=user;return{ok:true,action,user};}
if(action==="user.delete"){
+ assertNoVariableReferences(state,user);
if(Object.values(state.users).some(u=>Object.values(u.connections).some(rows=>Object.values(rows).some(c=>c.sharedFrom?.user===user))))throw new IntegrationError("user_has_shared_dependents",409);
Object.values(profile.connections).flatMap(Object.values).forEach(assertNotBusy);
delete state.users[user];state.bindings=state.bindings.filter(b=>b.user!==user);if(state.defaultUser===user)state.defaultUser=null;return{ok:true,action,user};
@@ -34,7 +38,7 @@ export async function integrationManage(input:Record<string,unknown>){
if(action==="user.duplicate")for(const rows of Object.values(copy.connections))for(const c of Object.values(rows))if(c.sharedFrom){const ref=c.sharedFrom,owner=state.users[ref.user]?.connections[ref.provider]?.[ref.connection];if(!owner)throw new IntegrationError("shared_backing_not_found",409);c.values={...owner.values};delete c.sharedFrom;}if(action==="user.duplicate")copy.uid=randomUUID();copy.label=connectionLabel(input.label??target);
for(const rows of Object.values(copy.connections))for(const c of Object.values(rows)){c.uid=randomUUID();c.revision++;c.updatedAt=Date.now();delete c.lease;if(action==="user.duplicate"&&input.copyCredentials!==true){c.values={};delete c.verifiedAt;}if(action==="user.duplicate"&&c.source!=="direct"){c.external=undefined;delete c.verifiedAt;}}
state.users[target]=copy;
- if(action==="user.rename"){delete state.users[user];for(const u of Object.values(state.users))for(const rows of Object.values(u.connections))for(const c of Object.values(rows))if(c.sharedFrom?.user===user)c.sharedFrom.user=target;for(const b of state.bindings)if(b.user===user)b.user=target;if(state.defaultUser===user)state.defaultUser=target;}
+ if(action==="user.rename"){for(const ref of Object.values(state.variables??{}))if(ref.user===user)ref.user=target;delete state.users[user];for(const u of Object.values(state.users))for(const rows of Object.values(u.connections))for(const c of Object.values(rows))if(c.sharedFrom?.user===user)c.sharedFrom.user=target;for(const b of state.bindings)if(b.user===user)b.user=target;if(state.defaultUser===user)state.defaultUser=target;}
return{ok:true,action,user:target};
}
if(action==="folder.map"){
@@ -59,7 +63,9 @@ export async function integrationManage(input:Record<string,unknown>){
const alias=structuredClone(c);alias.id=id;alias.uid=randomUUID();alias.label=connectionLabel(input.label??c.label);alias.values={};alias.sharedFrom={user,connection,provider};alias.revision++;alias.createdAt=Date.now();alias.updatedAt=Date.now();delete alias.lease;
targetUser.connections[provider]={...rows,[id]:alias};if(input.makeDefault===true||!targetUser.defaults[provider])targetUser.defaults[provider]=id;return{ok:true,action,connection:summaryIn(state,target,alias)};
}
+ if(action==="connection.delete"||action==="connection.unshare")assertNoVariableReferences(state,user,provider,connection);
if(action==="connection.unshare"){
+ if(state.bindings.some(b=>b.user===user&&b.connections[provider]===connection))throw new IntegrationError("connection_has_folder_binding",409);
if(!c.sharedFrom)throw new IntegrationError("connection_not_shared",409);delete profile.connections[provider][connection];if(profile.defaults[provider]===connection)delete profile.defaults[provider];return{ok:true,action,user,provider,connection};
}
if(c.sharedFrom&&action==="connection.delete")throw new IntegrationError("shared_alias_use_unshare",409);
diff --git a/lib/infra/connection-model.test.ts b/lib/infra/connection-model.test.ts
index db98be49..2797f8ca 100644
--- a/lib/infra/connection-model.test.ts
+++ b/lib/infra/connection-model.test.ts
@@ -129,6 +129,30 @@ describe("native credential identity core",()=>{
await f.manage({action:"connection.unshare",confirm:true,user:"bob",provider:"github",connection:alias.id});expect((await f.integrationSnapshot({user:"bob"})).connections).toHaveLength(0);await expect(f.manage({action:"connection.unshare",confirm:true,user:"bob-copy",provider:"github",connection:alias.id})).rejects.toMatchObject({code:"connection_not_shared"});
await f.manage({action:"connection.delete",confirm:true,user:"owner-renamed",provider:"github",connection:"work"});
});
+ it("stores metadata-only Integration Variables, keeps references coherent, and blocks deleting referenced identities",async()=>{
+ const f=await fixture();await f.add("alice","mcp","jev","direct",{});
+ await expect(f.manage({action:"variable.set",confirm:true,key:"jev",user:"alice",provider:"mcp",connection:"jev"})).rejects.toMatchObject({code:"invalid_variable_key"});
+ await expect(f.manage({action:"variable.set",confirm:true,key:"MISSING",user:"alice",provider:"mcp",connection:"missing"})).rejects.toMatchObject({code:"connection_not_found"});
+ await f.manage({action:"variable.set",confirm:true,key:"JEV",user:"alice",provider:"mcp",connection:"jev"});
+ expect(await f.integrationQuery({view:"variables"})).toEqual({variables:{JEV:{provider:"mcp",user:"alice",connection:"jev"}}});
+ expect(await f.resolveIntegrationVariable("JEV")).toMatchObject({key:"JEV",provider:"mcp",user:"alice",connection:"jev",state:"incomplete"});
+ await expect(f.manage({action:"connection.delete",confirm:true,user:"alice",provider:"mcp",connection:"jev"})).rejects.toMatchObject({code:"integration_has_variables"});
+ await expect(f.manage({action:"user.delete",confirm:true,user:"alice"})).rejects.toMatchObject({code:"integration_has_variables"});
+ await f.manage({action:"user.rename",confirm:true,user:"alice",target:"owner-renamed"});
+ expect(await f.integrationQuery({view:"variables"})).toEqual({variables:{JEV:{provider:"mcp",user:"owner-renamed",connection:"jev"}}});
+ await f.manage({action:"variable.delete",confirm:true,key:"JEV"});
+ expect(await f.integrationQuery({view:"variables"})).toEqual({variables:{}});
+ await f.manage({action:"connection.delete",confirm:true,user:"owner-renamed",provider:"mcp",connection:"jev"});
+ });
+ it("seeds JEV only when upgrading a pre-variable store with an unambiguous mcp/jev connection",async()=>{
+ const f=await fixture();await f.add("alice","mcp","jev","direct",{});
+ const raw=JSON.parse(await fs.readFile(file,"utf8"));delete raw.variables;const legacyLike=JSON.stringify(raw,null,2);await fs.writeFile(file,legacyLike,{mode:0o600});
+ vi.resetModules();const {readIntegrationState}=await import("./connection-storage");const state=await readIntegrationState();
+ expect(state.variables).toEqual({JEV:{provider:"mcp",user:"alice",connection:"jev"}});
+ expect(await fs.readFile(file,"utf8")).toBe(legacyLike);
+ raw.variables={};await fs.writeFile(file,JSON.stringify(raw,null,2),{mode:0o600});vi.resetModules();
+ const explicit=await (await import("./connection-storage")).readIntegrationState();expect(explicit.variables).toEqual({});
+ });
it("rejects sharing external sources and deletes one direct credential field without exposing values",async()=>{
const f=await fixture();await f.add("alice","github","hosted","oauth2",{},"composio");await expect(f.manage({action:"connection.share",confirm:true,user:"alice",provider:"github",connection:"hosted",target:"bob",label:"Hosted share"})).rejects.toMatchObject({code:"external_connections_cannot_share"});
await f.add("alice","convex-cloud","deploy","deployment",{deployKey:KEY_A,deploymentName:"test-deployment"});await f.manage({action:"credential.delete",confirm:true,user:"alice",provider:"convex-cloud",connection:"deploy",key:"deploymentName"});const values=await f.directConnectionValues("convex-cloud",{user:"alice",connection:"deploy"});expect(values).toEqual({deployKey:KEY_A});const row=(await f.integrationSnapshot({user:"alice"})).connections.find(c=>c.id==="deploy")!;expect(row.missing).toContain("deploymentName");expect(JSON.stringify(row)).not.toContain(KEY_A);
diff --git a/lib/infra/connection-service.ts b/lib/infra/connection-service.ts
index 7b80e94a..28a921e5 100644
--- a/lib/infra/connection-service.ts
+++ b/lib/infra/connection-service.ts
@@ -1,3 +1,4 @@
+import { variableKey } from "./connection-variables";
import { randomUUID } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
import { connectionCatalog, connectionMethod, connectionSummary, nativeDefinition } from "./connection-registry";
@@ -19,11 +20,18 @@ export async function resolveIntegration(provider:string,selector:ConnectionSele
const state=await readIntegrationState(),resolved=selectConnection(state,provider,selector),c=resolved.connection;
return{...summaryIn(state,resolved.user,c),resolution:resolved.reason,execution:c.source==="direct"?{route:"native-direct"}:c.source==="composio"?{route:"composio",connectedAccountId:c.external?.connectedAccountId??null,toolkit:c.external?.toolkit??null}:{route:"provider-mcp",endpoint:nativeDefinition(provider)?.url??null,authorization:"provider-client-owned"}};
}
+export async function resolveIntegrationVariable(key:string){
+ const name=variableKey(key),state=await readIntegrationState(),ref=state.variables?.[name];
+ if(!ref)throw new IntegrationError("integration_variable_not_found",404);
+ const selected=selectConnection(state,ref.provider,{user:ref.user,connection:ref.connection});
+ const summary=summaryIn(state,selected.user,selected.connection);
+ return{key:name,provider:ref.provider,user:ref.user,connection:ref.connection,label:summary.label,state:summary.state};
+}
export async function integrationSnapshot(selector:ConnectionSelector={}){
const state=await readIntegrationState();let user:string|null=null;try{user=resolveUser(state,selector);}catch(e){if(selector.user)throw e;}
const profiles=Object.values(state.users).map(u=>({id:u.id,label:u.label,isDefault:state.defaultUser===u.id,connectionCount:Object.values(u.connections).reduce((n,rows)=>n+Object.keys(rows).length,0)}));
const connections=user?Object.values(state.users[user].connections).flatMap(rows=>Object.values(rows).map(c=>summaryIn(state,user!,c))):[];
- return{version:2,users:profiles,user,bindings:state.bindings,connections,resolution:user?(selector.user?"explicit":folderBinding(state,selector.cwd)?"folder":"default"):"choose-user"};
+ return{version:2,variables:state.variables??{},users:profiles,user,bindings:state.bindings,connections,resolution:user?(selector.user?"explicit":folderBinding(state,selector.cwd)?"folder":"default"):"choose-user"};
}
export function createConnectionIn(state:IntegrationState,input:{user:string;provider:string;connection:string;label?:string;source?:ConnectionSource;authMethod?:string;makeDefault?:boolean}){
const user=identity(input.user,"user"),provider=identity(input.provider,"provider"),id=identity(input.connection,"connection"),profile=state.users[user];if(!profile)throw new IntegrationError("user_not_found",404);
@@ -61,6 +69,6 @@ export async function integrationQuery(input:Record<string,unknown>){
if(!input.connection)return{provider,user:input.user??null,sources:catalog.sources,next:"choose named connection, source and auth; never pass keys through tool JSON"};
const route=await resolveIntegration(provider,selection);return{...route,guidance:connectionMethod(provider,route.source,route.authMethod).guidance,next:route.source==="direct"?"integration_setup_open with this user and connection":route.source==="composio"?"authorize, then sync until ACTIVE":"authorize the provider-owned MCP in your client"};
}
- if(!["snapshot","users","connections","which"].includes(String(view)))throw new IntegrationError("unknown_query_view");
- const out=await integrationSnapshot(selection);if(view==="users")return{users:out.users,user:out.user};if(view==="which")return{user:out.user,resolution:out.resolution,bindings:out.bindings};if(view==="connections")return{user:out.user,connections:out.connections.filter(c=>!input.provider||c.provider===input.provider)};return out;
+ if(!["snapshot","variables","users","connections","which"].includes(String(view)))throw new IntegrationError("unknown_query_view");
+ const out=await integrationSnapshot(selection);if(view==="variables")return{variables:out.variables};if(view==="users")return{users:out.users,user:out.user};if(view==="which")return{user:out.user,resolution:out.resolution,bindings:out.bindings};if(view==="connections")return{user:out.user,connections:out.connections.filter(c=>!input.provider||c.provider===input.provider)};return out;
}
diff --git a/lib/infra/connection-storage.ts b/lib/infra/connection-storage.ts
index 0c0fcce8..40632b2f 100644
--- a/lib/infra/connection-storage.ts
+++ b/lib/infra/connection-storage.ts
@@ -1,3 +1,4 @@
+import { normalizeIntegrationVariables } from "./connection-variables";
import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
import { constants, promises as fs } from "node:fs";
import { randomUUID } from "node:crypto";
@@ -21,6 +22,7 @@ function validate(d:IntegrationState):IntegrationState{
for(const [id,u] of Object.entries(d.users)){identity(id);if(u.id!==id||!u.connections||!u.defaults)throw new IntegrationError("invalid_integration_store");
for(const [p,rows]of Object.entries(u.connections)){identity(p);for(const [cid,c]of Object.entries(rows)){identity(cid);if(c.id!==cid||c.provider!==p||!c.uid||!Number.isInteger(c.revision)||!c.values||typeof c.values!=="object"||Array.isArray(c.values)||Object.values(c.values).some(v=>typeof v!=="string"))throw new IntegrationError("invalid_connection_store");connectionMethod(c.provider,c.source,c.authMethod);if(c.sharedFrom&&(!c.sharedFrom.user||!c.sharedFrom.connection||c.sharedFrom.provider!==p||c.source!=="direct"||Object.keys(c.values).length))throw new IntegrationError("invalid_shared_connection");if(c.source!=="direct"&&Object.keys(c.values).length)throw new IntegrationError("external_secrets_forbidden");}}
}
+ normalizeIntegrationVariables(d);
return d;
}
function projected(raw:Record<string,unknown>|undefined):IntegrationState{
diff --git a/lib/infra/connection-ui-layout.test.ts b/lib/infra/connection-ui-layout.test.ts
index 29df2a59..45041ea2 100644
--- a/lib/infra/connection-ui-layout.test.ts
+++ b/lib/infra/connection-ui-layout.test.ts
@@ -1,6 +1,7 @@
import { expect, it } from "vitest";
import { CONNECTION_MANAGER_SCRIPT } from "./connection-ui";
import { CONNECTION_MANAGER_STYLE } from "./connection-ui-style";
+import { INTEGRATION_BROWSER_SCRIPT } from "./setup-browser";
it("uses the Settings master/detail navigation contract", () => {
expect(CONNECTION_MANAGER_SCRIPT).toContain('aria-label","Integrations sections"');
@@ -8,6 +9,8 @@ it("uses the Settings master/detail navigation contract", () => {
expect(CONNECTION_MANAGER_SCRIPT).toContain('integration-settings-content');
expect(CONNECTION_MANAGER_SCRIPT).toContain('n("p","Connections","integration-nav-label")');
expect(CONNECTION_MANAGER_SCRIPT).toContain('n("p","Manage","integration-nav-label")');
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('["ai-providers","AI Providers",showAiProviders]');
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('["variables","Variables",showVariables]');
expect(CONNECTION_MANAGER_SCRIPT).toContain('["transfer","Transfer & backup",showTransfer]');
expect(CONNECTION_MANAGER_SCRIPT).toContain('["project-mcp","Add project MCP",showProjectMcp]');
expect(CONNECTION_MANAGER_STYLE).toContain('grid-template-columns:var(--settings-sidebar-width) minmax(0,1fr)');
@@ -19,3 +22,14 @@ it("uses the Settings master/detail navigation contract", () => {
it("keeps transfer inside the selected detail pane when the browser bridge supports it", () => {
expect(CONNECTION_MANAGER_SCRIPT).toContain('bridge.mountTransfer(detail');
});
+
+it("keeps AI Providers on the existing AI config/runtime SSOT and browser-only credential bridge", () => {
+ expect(() => new Function(CONNECTION_MANAGER_SCRIPT)).not.toThrow();
+ expect(CONNECTION_MANAGER_SCRIPT).toContain("same AI runtime/config store as Settings");
+ expect(CONNECTION_MANAGER_SCRIPT).toContain("Integration Variables");
+ expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiConfig=()=>json("/api/config")');
+ expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiCatalog=()=>json("/api/models/providers")');
+ expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiTest=()=>json("/api/models/test"');
+ expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiOauth=body=>json("/api/oauth/openai"');
+ expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiRemove=provider=>json("/api/config?provider="');
+});
diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.ts
index 4d18fdbc..e511d9b7 100644
--- a/lib/infra/connection-ui.ts
+++ b/lib/infra/connection-ui.ts
@@ -4,7 +4,7 @@ import { PROVIDER_ICON_PATHS } from "./provider-icons";
export const CONNECTION_MANAGER_SCRIPT=PROJECT_MCP_UI_SCRIPT+`const PROVIDER_ICON_PATHS=${JSON.stringify(PROVIDER_ICON_PATHS)};`+String.raw`
function mountConnectionManager(root,catalog,bridge,initial={}){
let disposed=false,sequence=0,snapshot=initial.snapshot||{users:[],connections:[],bindings:[]},user=initial.user||snapshot.user||null,provider=catalog.find(p=>p.id===initial.provider)||catalog.find(p=>p.id==="github")||catalog[0];
- let detail,status,container,sidebarPanel,sidebarBackdrop,sidebarToggle,navButtons=[],navMode="provider",sidebarOpen=false;
+ let detail,status,container,sidebarPanel,sidebarBackdrop,sidebarToggle,navButtons=[],navMode=["variables","ai-providers"].includes(initial.section)?initial.section:"provider",sidebarOpen=false;
const ready=c=>c.state==="verified"||c.state==="ACTIVE";
const stateLabel=c=>ready(c)?"Verified":c.state==="incomplete"?"Needs setup":c.state==="configured"?"Not verified":c.state==="invalid"?"Access rejected":c.state==="unavailable"?"Check unavailable":c.state==="unconfigured"?"Needs setup":"Authorize";
const mark=p=>{const wrap=n("span",undefined,"provider-mark"),svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),shape=document.createElementNS("http://www.w3.org/2000/svg","path");wrap.setAttribute("aria-hidden","true");svg.setAttribute("viewBox","0 0 24 24");shape.setAttribute("d",PROVIDER_ICON_PATHS[p.id]||"M8 2h8v5h5v10h-5v5H8v-5H3V7h5V2zm2 2v5H5v6h5v5h4v-5h5V9h-5V4z");svg.append(shape);wrap.append(svg);return wrap};
@@ -23,7 +23,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
popup.addEventListener("keydown",event=>{if(event.key==="ArrowDown")move(event,1);else if(event.key==="ArrowUp")move(event,-1);else if(event.key==="Home"){event.preventDefault();options[0]?.[1].focus()}else if(event.key==="End"){event.preventDefault();options.at(-1)?.[1].focus()}else if(event.key==="Escape"){event.preventDefault();close(true)}});
wrap.addEventListener("focusout",()=>setTimeout(()=>{if(!wrap.contains(document.activeElement))close()},0));wrap.append(caption,trigger,popup);paint();return{wrap,get value(){return value},set value(next){value=next;paint()}};
};
- const textError=e=>({user_required:"Select a credential owner first.",connection_ambiguous:"Choose a named connection; more than one account exists.",connection_has_folder_binding:"Remove or change this connection's folder binding before deleting it.",connection_busy:"This connection is being used. Retry after that operation finishes.",choose_auth_config_id:"Several Composio auth configs match. Enter the intended auth config ID.",matching_auth_config_required:"Select a matching Composio auth config, or explicitly permit managed OAuth setup.",composio_project_key_required:"Configure a Composio project key under this same credential owner first.",external_source_requires_own_executor:"This connection uses an external backend; a local API key will not be substituted.",user_has_shared_dependents:"Unshare this owner’s shared connections before deleting the owner.",connection_has_shared_dependents:"Unshare dependent accounts before deleting this connection.",shared_alias_readonly:"Shared connections are read-only. Rotate credentials from the owner connection.",shared_alias_cannot_share:"A shared connection cannot be shared again. Share from its owner instead.",external_connections_cannot_share:"Only direct MSO credentials can be shared between credential owners.",shared_alias_use_unshare:"Use Unshare to remove a shared connection without touching its owner.",owner_required:"Sign in as an Owner before changing connections."}[e.code||e.message]||e.message||"Operation failed.");
+ const textError=e=>({user_required:"Select a credential owner first.",connection_ambiguous:"Choose a named connection; more than one account exists.",connection_has_folder_binding:"Remove or change this connection's folder binding before deleting it.",integration_has_variables:"Remove Integration Variables that point to this owner or connection first.",invalid_variable_key:"Variable names use uppercase A-Z, 0-9 and underscore.",connection_busy:"This connection is being used. Retry after that operation finishes.",choose_auth_config_id:"Several Composio auth configs match. Enter the intended auth config ID.",matching_auth_config_required:"Select a matching Composio auth config, or explicitly permit managed OAuth setup.",composio_project_key_required:"Configure a Composio project key under this same credential owner first.",external_source_requires_own_executor:"This connection uses an external backend; a local API key will not be substituted.",user_has_shared_dependents:"Unshare this owner’s shared connections before deleting the owner.",connection_has_shared_dependents:"Unshare dependent accounts before deleting this connection.",shared_alias_readonly:"Shared connections are read-only. Rotate credentials from the owner connection.",shared_alias_cannot_share:"A shared connection cannot be shared again. Share from its owner instead.",external_connections_cannot_share:"Only direct MSO credentials can be shared between credential owners.",shared_alias_use_unshare:"Use Unshare to remove a shared connection without touching its owner.",owner_required:"Sign in as an Owner before changing connections."}[e.code||e.message]||e.message||"Operation failed.");
function remember(){if(bridge.remember)bridge.remember({user,provider:provider.id})}
async function reload(){const version=++sequence;if(!bridge.query){draw();return}try{const next=await bridge.query({view:"snapshot",...(user?{user}:{})});if(disposed||version!==sequence)return;snapshot=next;user=next.user||user;draw();remember()}catch(e){if(!disposed){draw();status.textContent=textError(e)}}}
async function change(args,after=reload){if(!bridge.manage)return;try{status.textContent="Saving connection metadata…";await bridge.manage({...args,confirm:true});await after()}catch(e){status.textContent=textError(e)}}
@@ -34,6 +34,8 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
function showBindings(){navMode="routing";activateNav(navMode);setSidebar(false);bindings()}
function showTransfer(){navMode="transfer";activateNav(navMode);setSidebar(false);if(bridge.mountTransfer)bridge.mountTransfer(detail,()=>{navMode="provider";activateNav(navMode);drawProvider()});else if(bridge.openTransfer)bridge.openTransfer();else bridge.openTransferBrowser?.()}
function showProjectMcp(){navMode="project-mcp";activateNav(navMode);setSidebar(false);mountProjectMcpForm(detail,bridge,snapshot,user,status,()=>{navMode="provider";activateNav(navMode);drawProvider()},{n,b,input})}
+ function showVariables(){navMode="variables";activateNav(navMode);setSidebar(false);variables()}
+ function showAiProviders(){navMode="ai-providers";activateNav(navMode);setSidebar(false);void aiProviders()}
function selectProvider(p){provider=p;navMode="provider";remember();activateNav(navMode);setSidebar(false);drawProvider()}
function draw(){
root.replaceChildren();root.classList.add("integration","manager");
@@ -50,6 +52,8 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
const manageGroup=n("div",undefined,"integration-nav-group"),manageLabel=n("p","Manage","integration-nav-label");manageGroup.append(manageLabel);
const management=[
["owners","Credential owners",showProfiles],
+ ["ai-providers","AI Providers",showAiProviders],
+ ["variables","Variables",showVariables],
["routing","Project routing",showBindings],
["transfer","Transfer & backup",showTransfer],
["project-mcp","Add project MCP",showProjectMcp],
@@ -64,7 +68,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
detail=n("section",undefined,"identity-detail integration-settings-detail");status=n("p",undefined,"identity-feedback");status.setAttribute("role","status");status.setAttribute("aria-live","polite");content.append(detail,status);
shell.append(sidebarPanel,sidebarBackdrop,content);root.append(shell);container=shell;
activateNav(navMode);
- if(navMode==="owners")profiles();else if(navMode==="routing")bindings();else if(navMode==="project-mcp")showProjectMcp();else drawProvider();
+ if(navMode==="owners")profiles();else if(navMode==="variables")variables();else if(navMode==="ai-providers")void aiProviders();else if(navMode==="routing")bindings();else if(navMode==="project-mcp")showProjectMcp();else drawProvider();
}
function confirmation(title,id,fn){detail.replaceChildren(n("h2",title),n("p","This changes only the selected identity. Type “"+id+"” to confirm."));const value=input("Confirmation");detail.append(value.label,b("Confirm",()=>{if(value.input.value!==id){status.textContent="Confirmation does not match.";return}void fn()},"danger"),b("Cancel",()=>{navMode="provider";activateNav(navMode);drawProvider()}));}
function profiles(){
@@ -81,6 +85,48 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
const folder=input("Absolute project folder"),connection=input("Connection ID (optional)");detail.append(folder.label,connection.label);const save=b("Bind this folder",()=>change({action:"folder.map",path:folder.input.value,user,...(connection.input.value?{provider:provider.id,connection:connection.input.value}:{})}));save.disabled=!user||!bridge.manage;detail.append(save);
for(const binding of snapshot.bindings){const card=n("div",undefined,"connection-card");card.append(n("strong",binding.path),n("p",binding.user+" · "+Object.entries(binding.connections).map(([p,id])=>p+"="+id).join(", ")));const remove=b("Remove binding",()=>change({action:"folder.unmap",path:binding.path}));remove.disabled=!bridge.manage;card.append(remove);detail.append(card)}
}
+ function variables(){
+ detail.replaceChildren(n("h2","Integration Variables"),n("p","Metadata-only aliases point to named Integrations connections. Credentials are never copied into a variable."));
+ const variables=snapshot.variables&&typeof snapshot.variables==="object"?snapshot.variables:{};
+ const entries=Object.entries(variables).sort(([a],[b])=>a.localeCompare(b));
+ if(!entries.length)detail.append(n("p","No Integration Variables yet.","identity-muted"));
+ for(const[key,ref]of entries){const card=n("article",undefined,"connection-card"),top=n("header",undefined,"connection-heading"),copy=n("div");copy.append(n("h3",key),n("small",ref.user+" / "+ref.provider+" / "+ref.connection));top.append(copy);card.append(top);if(key==="JEV")card.append(n("p","Default decision-kernel alias used by Workflow Optimizer.","identity-muted"));const remove=b("Remove",()=>change({action:"variable.delete",key}),"danger");remove.disabled=!bridge.manage;card.append(n("div",undefined,"identity-actions"));card.lastChild.append(remove);detail.append(card)}
+ const editor=n("div",undefined,"connection-card");editor.append(n("h3","Add or update variable"),n("p","Select a credential owner in the sidebar, then point the variable to one of that owner’s named connections.","identity-muted"));
+ if(!user){editor.append(n("p","Select a credential owner first.","identity-muted"));detail.append(editor);return}
+ const key=input("Variable name",variables.JEV?"":"JEV"),providerSelect=n("select"),providerLabel=n("label","Provider"),connectionSelect=n("select"),connectionLabel=n("label","Named connection");
+ providerLabel.append(providerSelect);connectionLabel.append(connectionSelect);
+ for(const p of catalog){const o=n("option",p.title);o.value=p.id;providerSelect.append(o)}
+ providerSelect.value=catalog.some(p=>p.id==="mcp")?"mcp":provider.id;
+ const fillConnections=()=>{connectionSelect.replaceChildren();const rows=snapshot.connections.filter(c=>c.provider===providerSelect.value);for(const c of rows){const o=n("option",c.label+" · "+c.id);o.value=c.id;connectionSelect.append(o)}};
+ providerSelect.addEventListener("change",fillConnections);fillConnections();key.input.addEventListener("input",()=>key.input.value=key.input.value.toUpperCase().replace(/[^A-Z0-9_]/g,"").slice(0,64));
+ const fields=n("div",undefined,"identity-fields");fields.append(key.label,providerLabel,connectionLabel);editor.append(fields);
+ const save=b("Save variable",()=>{if(!key.input.value||!connectionSelect.value){status.textContent="Choose a variable name and named connection.";return}void change({action:"variable.set",key:key.input.value,user,provider:providerSelect.value,connection:connectionSelect.value})},"primary");save.disabled=!bridge.manage;editor.append(save);detail.append(editor);
+ }
+ async function aiProviders(){
+ detail.replaceChildren(n("h2","AI Providers"),n("p","Configure Alfa’s active model provider here. This view uses the same AI runtime/config store as Settings; it does not create another credential registry."));
+ if(!bridge.aiConfig||!bridge.aiCatalog||!bridge.aiModels||!bridge.aiSave){
+ const card=n("div",undefined,"identity-empty");card.append(n("h3","Open native MSO"),n("p","AI provider credentials are managed only in the private native MSO page, not through the MCP Page payload."));
+ if(bridge.openAiProviders)card.append(b("Open AI Providers",()=>bridge.openAiProviders(),"primary"));detail.append(card);return;
+ }
+ const loading=n("p","Loading AI providers…","identity-muted");detail.append(loading);
+ try{
+ const[cfg,catalogResult]=await Promise.all([bridge.aiConfig(),bridge.aiCatalog()]);if(navMode!=="ai-providers")return;
+ const dynamic=Array.isArray(catalogResult?.providers)?catalogResult.providers:[],connected=Array.isArray(cfg?.providers)?cfg.providers:[],meta=new Map();
+ for(const row of dynamic)meta.set(row.id,{id:row.id,name:row.name||row.id,...row});for(const row of connected)meta.set(row.id,{id:row.id,name:meta.get(row.id)?.name||row.id,...meta.get(row.id),...row});if(cfg.provider&&!meta.has(cfg.provider))meta.set(cfg.provider,{id:cfg.provider,name:cfg.provider});
+ detail.replaceChildren(n("h2","AI Providers"),n("p","Alfa provider/model selection and credentials share the exact Settings SSOT. Saved keys stay server-side and are only shown masked."));
+ const providerSelect=n("select"),providerLabel=n("label","Active provider"),modelSelect=n("select"),modelLabel=n("label","Model"),key=input("API key","","password"),fields=n("div",undefined,"identity-fields");
+ for(const row of [...meta.values()].sort((a,b)=>String(a.name).localeCompare(String(b.name)))){const o=n("option",row.name+(row.freeAgentModelCount? " · "+row.freeAgentModelCount+" free agent model"+(row.freeAgentModelCount===1?"":"s"):""));o.value=row.id;providerSelect.append(o)}
+ providerSelect.value=cfg.provider||providerSelect.options[0]?.value||"";providerLabel.append(providerSelect);modelLabel.append(modelSelect);fields.append(providerLabel,modelLabel,key.label);detail.append(fields);
+ const currentMeta=()=>connected.find(row=>row.id===providerSelect.value),syncKey=()=>{const row=currentMeta();key.label.hidden=row?.kind==="oauth";key.input.value="";key.input.placeholder=row?.masked||"API key (leave blank to keep existing)";};
+ const loadModels=async()=>{modelSelect.replaceChildren();modelSelect.disabled=true;try{const result=await bridge.aiModels(providerSelect.value),rows=Array.isArray(result?.models)?result.models:[];const connectedModels=currentMeta()?.models||[],ids=[...new Set([...connectedModels,...rows.map(row=>row.id)].filter(Boolean))];if(providerSelect.value===cfg.provider&&cfg.model&&!ids.includes(cfg.model))ids.unshift(cfg.model);for(const id of ids){const row=rows.find(x=>x.id===id),o=n("option",(row?.free?"Free · ":"")+String(row?.name||id));o.value=id;modelSelect.append(o)}if(providerSelect.value===cfg.provider&&cfg.model)modelSelect.value=cfg.model;else if(ids.length)modelSelect.value=ids[0]}catch(e){status.textContent=textError(e)}finally{modelSelect.disabled=false}};
+ providerSelect.addEventListener("change",()=>{syncKey();void loadModels()});syncKey();await loadModels();
+ const save=async(test=false)=>{try{status.textContent=test?"Saving before test…":"Saving AI provider…";await bridge.aiSave({provider:providerSelect.value,...(modelSelect.value?{model:modelSelect.value}:{}),...(key.input.value.trim()?{apiKey:key.input.value.trim()}:{})});key.input.value="";if(test){const result=await bridge.aiTest();status.textContent=result.ok?"AI provider connected.":result.error||"Provider test failed."}else status.textContent="AI provider saved.";await aiProviders()}catch(e){status.textContent=textError(e)}};
+ const actions=n("div",undefined,"identity-actions"),saveButton=b("Save",()=>void save(false),"primary"),testButton=b("Save & test",()=>void save(true));actions.append(saveButton,testButton);detail.append(actions);
+ const oauth=n("div",undefined,"connection-card");oauth.append(n("h3","OpenAI account"),n("p","Use device authorization without copying OAuth tokens into Integrations.","identity-muted"));if(bridge.aiOauth){const authBox=n("div"),start=selectAfter=>async()=>{try{status.textContent="Starting OpenAI authorization…";const flow=await bridge.aiOauth({action:"start"});authBox.replaceChildren();const link=n("a","Open verification page");link.href=flow.verificationUrl;link.target="_blank";link.rel="noopener noreferrer";authBox.append(n("p","Code: "+flow.userCode),link,b("Check authorization",async()=>{try{const out=await bridge.aiOauth({action:"poll",select:selectAfter});if(out.pending){status.textContent="Authorization is still pending.";return}status.textContent=out.selected?"OpenAI connected and selected.":"OpenAI connected.";await aiProviders()}catch(e){status.textContent=textError(e)}}));if(bridge.openLink)bridge.openLink(flow.verificationUrl)}catch(e){status.textContent=textError(e)}};const oauthActions=n("div",undefined,"identity-actions");oauthActions.append(b("Connect OpenAI",start(false)),b("Connect & use",start(true),"primary"));oauth.append(oauthActions,authBox)}detail.append(oauth);
+ const custom=n("details",undefined,"connection-card");custom.append(n("summary","Add custom provider"));const cname=input("Provider name"),base=input("Base URL"),protocol=n("select"),protocolLabel=n("label","Protocol"),models=input("Models (comma separated)"),customKey=input("API key","","password");for(const id of["openai","anthropic"]){const o=n("option",id);o.value=id;protocol.append(o)}protocolLabel.append(protocol);const customFields=n("div",undefined,"identity-fields");customFields.append(cname.label,base.label,protocolLabel,models.label,customKey.label);custom.append(customFields,b("Add custom provider",async()=>{try{await bridge.aiSave({select:false,customProvider:{name:cname.input.value,baseURL:base.input.value,protocol:protocol.value,models:models.input.value.split(",").map(v=>v.trim()).filter(Boolean),apiKey:customKey.input.value}});status.textContent="Custom provider added.";await aiProviders()}catch(e){status.textContent=textError(e)}},"primary"));detail.append(custom);
+ if(connected.length){detail.append(n("h3","Connected providers"));for(const row of connected){const card=n("div",undefined,"connection-card"),top=n("header",undefined,"connection-heading"),copy=n("div");copy.append(n("h3",meta.get(row.id)?.name||row.id),n("small",row.id+" · "+row.kind));top.append(copy,n("span",row.id===cfg.provider?"Active":row.hasKey?"Connected":"Configured","connection-state"));card.append(top,n("p",row.masked||"Credential stored server-side","identity-muted"));if(bridge.aiRemove){const disconnect=b("Disconnect",async()=>{if(!window.confirm("Disconnect "+row.id+"? Stored credentials for this AI provider will be removed."))return;try{await bridge.aiRemove(row.id);status.textContent="AI provider disconnected.";await aiProviders()}catch(e){status.textContent=textError(e)}},"danger");card.append(n("div",undefined,"identity-actions"));card.lastChild.append(disconnect)}detail.append(card)}}
+ }catch(e){loading.remove();detail.append(n("p",textError(e),"identity-muted"))}
+ }
function drawProvider(){
navMode="provider";activateNav(navMode);detail.replaceChildren();const heading=n("header",undefined,"provider-heading"),title=n("div",undefined,"provider-title"),copy=n("div");copy.append(n("h2",provider.title),n("p",provider.description));title.append(mark(provider),copy);heading.append(title);const add=b("Add connection",()=>user?newConnection():showProfiles(),"primary");add.disabled=!bridge.manage;heading.append(add);detail.append(heading);
diff --git a/lib/infra/connection-variables.ts b/lib/infra/connection-variables.ts
new file mode 100644
index 00000000..772fefd3
--- /dev/null
+++ b/lib/infra/connection-variables.ts
@@ -0,0 +1,25 @@
+import { IntegrationError, identity, selectConnection, type IntegrationState } from "./identity";
+export type IntegrationVariable = { provider: string; user: string; connection: string };
+export function variableKey(value: unknown): string {
+ if (typeof value !== "string" || !/^[A-Z][A-Z0-9_]{0,63}$/.test(value)) throw new IntegrationError("invalid_variable_key");
+ return value;
+}
+/** Only absent fields on pre-variable stores are seeded. An explicit empty map disables seeding. */
+export function normalizeIntegrationVariables(state: IntegrationState) {
+ if (state.variables === undefined) {
+ state.variables = {};
+ const owners = Object.keys(state.users).filter(user => state.users[user].connections.mcp?.jev);
+ const user = state.defaultUser && owners.includes(state.defaultUser) ? state.defaultUser : owners.length === 1 ? owners[0] : undefined;
+ if (user) state.variables.JEV = { provider: "mcp", user, connection: "jev" };
+ }
+ if (!state.variables || typeof state.variables !== "object" || Array.isArray(state.variables)) throw new IntegrationError("invalid_variables");
+ for (const [key, ref] of Object.entries(state.variables)) {
+ variableKey(key);
+ if (!ref || typeof ref !== "object" || Object.keys(ref).sort().join(",") !== "connection,provider,user") throw new IntegrationError("invalid_variable_reference");
+ selectConnection(state, identity(ref.provider), { user: identity(ref.user), connection: identity(ref.connection) });
+ }
+ return state.variables;
+}
+export function assertNoVariableReferences(state: IntegrationState, user: string, provider?: string, connection?: string) {
+ if (Object.values(state.variables ?? {}).some(ref => ref.user === user && (!provider || ref.provider === provider && ref.connection === connection))) throw new IntegrationError("integration_has_variables", 409);
+}
diff --git a/lib/infra/identity.ts b/lib/infra/identity.ts
index c10b8ed5..12bed480 100644
--- a/lib/infra/identity.ts
+++ b/lib/infra/identity.ts
@@ -13,7 +13,7 @@ export type IntegrationConnection = {
};
export type IntegrationUser = { id: string; uid:string; label: string; connections: Record<string, Record<string, IntegrationConnection>>; defaults: Record<string, string> };
export type IntegrationBinding = { path: string; user: string; connections: Record<string, string> };
-export type IntegrationState = { version: 2; instanceId:string; defaultUser: string | null; users: Record<string, IntegrationUser>; bindings: IntegrationBinding[]; migratedAt?: number };
+export type IntegrationState = { version: 2; instanceId:string; defaultUser: string | null; users: Record<string, IntegrationUser>; bindings: IntegrationBinding[]; variables?: Record<string, {provider:string;user:string;connection:string}>; migratedAt?: number };
export class IntegrationError extends Error { constructor(public readonly code: string, public readonly status = 400) { super(code); } }
export const emptyIntegrationState = (): IntegrationState => ({ version: 2, instanceId:randomUUID(), defaultUser: null, users: {}, bindings: [] });
export function identity(value: unknown, name = "identity"): string {
diff --git a/lib/infra/portable/data.ts b/lib/infra/portable/data.ts
index 5e00609c..bc78f5d6 100644
--- a/lib/infra/portable/data.ts
+++ b/lib/infra/portable/data.ts
@@ -12,7 +12,7 @@ export type TransferOptions={users?:string[];selection?:TransferSelection[];incl
// destination metadata — never a password/credential digest exposed to the caller.
const PLAN_TTL_MS=10*60*1000,MAX_PLANS=128;
const plans=new Map<string,{snapshot:string;expires:number}>();
-function snapshot(document:unknown,options:TransferOptions,state:IntegrationState){return JSON.stringify([document,options.prefix??'',options.policy??'skip',state.users,state.defaultUser,state.bindings]);}
+function snapshot(document:unknown,options:TransferOptions,state:IntegrationState){return JSON.stringify([document,options.prefix??'',options.policy??'skip',state.users,state.defaultUser,state.bindings,state.variables??{}]);}
function issuePlan(value:string){const now=Date.now();for(const [id,p]of plans)if(p.expires<=now)plans.delete(id);while(plans.size>=MAX_PLANS)plans.delete(plans.keys().next().value!);const id=randomBytes(32).toString('hex');plans.set(id,{snapshot:value,expires:now+PLAN_TTL_MS});return id;}
function requirePlan(id:string|undefined,value:string){if(!id)throw new IntegrationError('preview_required_or_destination_changed',409);const p=plans.get(id);if(!p||p.expires<=Date.now()||p.snapshot!==value){plans.delete(id);throw new IntegrationError('preview_required_or_destination_changed',409)}return id;}
export async function exportIntegrationData(options:TransferOptions={}){
diff --git a/lib/infra/setup-browser.ts b/lib/infra/setup-browser.ts
index 7753cbd2..e3ec2b63 100644
--- a/lib/infra/setup-browser.ts
+++ b/lib/infra/setup-browser.ts
@@ -1,6 +1,6 @@
export const INTEGRATION_BROWSER_SCRIPT=String.raw`
(async()=>{
- const root=document.getElementById("setup"),endpoint=location.origin+"/api/integrations/setup";let cleanup=()=>{},state={},authController,wantsTransfer=new URLSearchParams(location.search).get("transfer")==="1";
+ const root=document.getElementById("setup"),endpoint=location.origin+"/api/integrations/setup",params=new URLSearchParams(location.search);let cleanup=()=>{},state={...(params.get("section")==="ai-providers"?{section:"ai-providers"}:{})},authController,wantsTransfer=params.get("transfer")==="1";
const error=data=>{const e=new Error(data.error||"integration_operation_failed");e.code=data.error;return e};
async function json(url,init){const r=await fetch(url,{credentials:"same-origin",cache:"no-store",referrerPolicy:"no-referrer",...init});const data=await r.json();if(!r.ok)throw error(data);return data}
const post=(mode,input)=>json("/api/v1/integrations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode,...input})});
@@ -21,6 +21,9 @@ export const INTEGRATION_BROWSER_SCRIPT=String.raw`
bridge.projectMcp=args=>json("/api/v1/project-mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(args)});
bridge.query=args=>json("/api/v1/integrations?"+new URLSearchParams(args));
bridge.manage=args=>post("manage",args);bridge.execute=args=>post("execute",args);
+ bridge.aiConfig=()=>json("/api/config");bridge.aiCatalog=()=>json("/api/models/providers");bridge.aiModels=provider=>json("/api/models?provider="+encodeURIComponent(provider));
+ bridge.aiSave=body=>json("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});bridge.aiRemove=provider=>json("/api/config?provider="+encodeURIComponent(provider),{method:"DELETE"});
+ bridge.aiTest=()=>json("/api/models/test",{method:"POST"});bridge.aiOauth=body=>json("/api/oauth/openai",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});
bridge.openSetup=async args=>{const data=await json("/api/v1/infra/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(args)});showForm(data.setup,data.token)};
}
if(owner&&wantsTransfer){openTransfer();return}
diff --git a/lib/infra/store.ts b/lib/infra/store.ts
index 7e2e4f56..4e914615 100644
--- a/lib/infra/store.ts
+++ b/lib/infra/store.ts
@@ -1,3 +1,4 @@
+import { assertNoVariableReferences } from "./connection-variables";
import {randomUUID} from "node:crypto";
import { getInfraProviderDefinition, normalizeInfraValues } from "./catalog";
import { mutateIntegrationState } from "./connection-storage";
@@ -26,7 +27,7 @@ export async function setInfraProvider(id:InfraProviderId,raw:Record<string,unkn
});
}
export async function removeInfraProvider(id:InfraProviderId){
- await mutateIntegrationState(state=>{const selection=currentIntegrationSelection();const r=selectConnection(state,id,selection);assertNotBusy(r.connection);if(state.bindings.some(b=>b.user===r.user&&b.connections[id]===r.connection.id))throw new IntegrationError("connection_has_folder_binding");if(id==="composio"&&Object.values(state.users[r.user].connections).some(rows=>Object.values(rows).some(c=>c.source==="composio"&&c.external?.brokerConnection===r.connection.id)))throw new IntegrationError("broker_has_linked_connections",409);const profile=state.users[r.user];
+ await mutateIntegrationState(state=>{const selection=currentIntegrationSelection();const r=selectConnection(state,id,selection);assertNotBusy(r.connection);assertNoVariableReferences(state,r.user,id,r.connection.id);if(state.bindings.some(b=>b.user===r.user&&b.connections[id]===r.connection.id))throw new IntegrationError("connection_has_folder_binding");if(id==="composio"&&Object.values(state.users[r.user].connections).some(rows=>Object.values(rows).some(c=>c.source==="composio"&&c.external?.brokerConnection===r.connection.id)))throw new IntegrationError("broker_has_linked_connections",409);const profile=state.users[r.user];
const remaining=Object.fromEntries(Object.entries(profile.connections[id]).filter(([key])=>key!==r.connection.id));
profile.connections=Object.fromEntries(Object.entries(profile.connections).map(([key,rows])=>[key,key===id?remaining:rows]));
profile.defaults=Object.fromEntries(Object.entries(profile.defaults).filter(([key,value])=>key!==id||value!==r.connection.id));});
diff --git a/lib/mcp/integration-model-contract.test.ts b/lib/mcp/integration-model-contract.test.ts
index 6d3490b3..565304a8 100644
--- a/lib/mcp/integration-model-contract.test.ts
+++ b/lib/mcp/integration-model-contract.test.ts
@@ -17,8 +17,15 @@ it("uses the same native metadata services through actual MCP calls and rejects
const metadata=await call(4,"integration_query",{view:"resolve",user:"alice",provider:"convex-cloud",connection:"mimin-production"});expect((metadata.result as any)?.structuredContent?.result).toMatchObject({user:"alice",id:"mimin-production",source:"direct",authMethod:"deployment"});
const inputRejected=await call(5,"integration_manage",{action:"user.create",user:"eve",confirm:true,token:"synthetic"});expect((await readIntegrationState()).users.eve).toBeUndefined();expect(inputRejected.error??(inputRejected.result as any)?.isError).toBeTruthy();
});
+it("exposes metadata-only Integration Variables through the compact query/manage contract",async()=>{
+ const {INTEGRATION_TOOLS}=await import("./tools-integrations");
+ const query=INTEGRATION_TOOLS.find(entry=>entry.name==="integration_query")!,manage=INTEGRATION_TOOLS.find(entry=>entry.name==="integration_manage")!;
+ const q=query.inputSchema as {properties?:Record<string,{enum?:string[]}>},m=manage.inputSchema as {properties?:Record<string,{enum?:string[]}>};
+ expect(q.properties?.view?.enum).toContain("variables");expect(m.properties?.action?.enum).toEqual(expect.arrayContaining(["variable.set","variable.delete"]));
+ expect(m.properties).not.toHaveProperty("value");expect(m.properties).not.toHaveProperty("secret");
+});
it("keeps share/unshare in the same integration management contract without accepting secret values",async()=>{
- const {INTEGRATION_TOOLS}=await import("./tools-integrations");const tool=INTEGRATION_TOOLS.find(entry=>entry.name==="integration_manage")!;const schema=tool.inputSchema as {properties?:Record<string,{enum?:string[]}>};const actions=schema.properties?.action?.enum??[];expect(actions).toContain("connection.share");expect(actions).toContain("connection.duplicate");expect(actions).toContain("connection.unshare");expect(schema.properties).toHaveProperty("target");expect(schema.properties).toHaveProperty("targetConnection");expect(schema.properties).toHaveProperty("label");expect(schema.properties).toHaveProperty("key");expect(schema.properties).not.toHaveProperty("token");expect(schema.properties).not.toHaveProperty("apiKey");
+ const {INTEGRATION_TOOLS}=await import("./tools-integrations");const tool=INTEGRATION_TOOLS.find(entry=>entry.name==="integration_manage")!;const schema=tool.inputSchema as {properties?:Record<string,{enum?:string[]}>};const actions=schema.properties?.action?.enum??[];expect(actions).toContain("connection.share");expect(actions).toContain("connection.duplicate");expect(actions).toContain("connection.unshare");expect(actions).toContain("variable.set");expect(actions).toContain("variable.delete");expect(schema.properties).toHaveProperty("target");expect(schema.properties).toHaveProperty("targetConnection");expect(schema.properties).toHaveProperty("label");expect(schema.properties).toHaveProperty("key");expect(schema.properties).not.toHaveProperty("token");expect(schema.properties).not.toHaveProperty("apiKey");
});
it("exposes the bounded Dokploy application operations through integration_execute without adding a generic request escape hatch",async()=>{
const {INTEGRATION_TOOLS}=await import("./tools-integrations");
@@ -32,6 +39,8 @@ it("exposes the bounded Dokploy application operations through integration_execu
expect(operations).toContain("dokploy.domain.ensure");
expect(operations).toContain("dokploy.dockerfile");
expect(operations).toContain("dokploy.application.publicEnv.upsert");
+ expect(operations).toContain("mcp.tools.list");
+ expect(operations).toContain("mcp.tool");
expect(operations.some(operation=>/request|fetch|raw/i.test(operation))).toBe(false);
});
it("returns identity-bound setup only in UI-private metadata on both supported MCP profiles",async()=>{
diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.ts
index a09e2ed6..1592a272 100644
--- a/lib/mcp/tools-flows.ts
+++ b/lib/mcp/tools-flows.ts
@@ -16,6 +16,7 @@ import { listAutomationScripts } from "@/lib/orchestration/repo-memory-artifacts
import { createWorkflowDataTable, deleteWorkflowDataTable, deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "@/lib/workflow/data-table-store";
import { optimizeWorkflowGraph } from "@/lib/workflow/graph-optimizer";
import { createJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-optimizer";
+import { resolveJevIntegrationConfig } from "@/lib/workflow/jev-integration";
const project = { type: "string", maxLength: 4096 };
const flow = { type: "string", maxLength: 64 };
@@ -98,11 +99,7 @@ export const FLOW_TOOLS: McpTool[] = [
const mode = data.mode === "jev" ? "jev" as const : "deterministic" as const;
let evaluator;
if (mode === "jev") {
- const jev = data.jev;
- if (!jev || typeof jev !== "object" || Array.isArray(jev)) throw new Error("data.jev with user and connection is required for Jev optimization");
- const ref = jev as Record<string, unknown>;
- if (typeof ref.user !== "string" || typeof ref.connection !== "string") throw new Error("Jev optimizer requires integration user and connection");
- evaluator = createJevWorkflowOptimizerEvaluator({ user: ref.user, connection: ref.connection, ...(typeof ref.tool === "string" ? { tool: ref.tool } : {}), ...(typeof ref.model === "string" ? { model: ref.model } : {}) });
+ evaluator = createJevWorkflowOptimizerEvaluator(await resolveJevIntegrationConfig(data.jev));
}
const { TOOLS_BY_NAME } = await import("./tools");
const optimized = await optimizeWorkflowGraph(graph, { mode, threshold: Number(data.threshold) || undefined, applyReview: data.apply_review === true, evaluator, resolveTool: name => TOOLS_BY_NAME.get(name) });
diff --git a/lib/mcp/tools-integrations.ts b/lib/mcp/tools-integrations.ts
index 7b10f2fb..d51a133a 100644
--- a/lib/mcp/tools-integrations.ts
+++ b/lib/mcp/tools-integrations.ts
@@ -9,7 +9,7 @@ export const INTEGRATION_TOOLS:McpTool[]=[
{name:"integration_query",title:"Inspect Integration Connections",scope:"read",annotations:{readOnlyHint:true,idempotentHint:true,openWorldHint:false},
description:"Read native MSO credential users, providers, named connections, source/auth guidance and directory resolution. Never returns keys. Before asking the user for a credential or creating new setup, inspect Integrations for the exact project/context and resolve the intended user/provider/connection. User profiles are credential owners, not device roles. Resolve before acting when multiple accounts or deployments exist.",
chatgptDescription:"When work needs a service credential, check Integrations first. Inspect users/providers/connections and resolve the exact existing connection; use view=request only when setup is actually missing.",
- inputSchema:S({...BASE,view:{type:"string",enum:["snapshot","catalog","users","connections","which","resolve","request"]},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64}}),outputSchema:OUTPUT,
+ inputSchema:S({...BASE,view:{type:"string",enum:["snapshot","variables","catalog","users","connections","which","resolve","request"]},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64}}),outputSchema:OUTPUT,
meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>({result:await queryIntegrationAction(a)}),
},
{name:"integration_manage",title:"Manage Integrations",scope:"write",annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:true},audit:{action:"infra.write",targetArg:"user"},limit:{key:"integration.manage",max:30,windowMs:60000},
@@ -22,7 +22,7 @@ export const INTEGRATION_TOOLS:McpTool[]=[
{name:"integration_execute",title:"Use an Exact Integration Connection",scope:"exec",annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:true},audit:{action:"infra.write",targetArg:"connection"},limit:{key:"integration.execute",max:30,windowMs:60000},
description:"Execute using an explicit user/provider/named connection. Verify or inspect its route; bounded direct operations reject external backends. Composio tool execution requires an ACTIVE connected account and a toolkit-prefixed tool. Native-MCP returns the provider route without copying OAuth tokens. Non-verification operations require confirm=true. No credentials in arguments.",
chatgptDescription:"Run an operation for exact user/provider/connection. Route or verify first; mutations need confirm=true.",
- inputSchema:S({...BASE,operation:{type:"string",enum:["route","verify","dokploy.projects.list","dokploy.applications.list","dokploy.gitProviders.list","dokploy.github.repositories.list","dokploy.application.ensureGithub","dokploy.domain.ensure","dokploy.deployments.list","dokploy.deployment.logs","dokploy.git.recover","dokploy.application.deploy","dokploy.dockerfile","dokploy.application.publicEnv.upsert","dokploy.project.ensure","convex.customDomains.list","convex.customDomain.ensure","convex.canonical.get","convex.env.presence","convex.canonical.set","convex.project.deploy","convex.snapshot.import","cloudflare.zones.list","cloudflare.dns.upsert","hostinger.dns.upsert","hostinger.mail.orders.list","hostinger.mail.plan.get","hostinger.mail.list","hostinger.mail.logs.list","hostinger.mail.mutate","composio.tool"]},confirm:{type:"boolean"},tool:{type:"string",maxLength:180},arguments:{type:"object",additionalProperties:true}},["user","provider","connection","operation"]),outputSchema:OUTPUT,
+ inputSchema:S({...BASE,operation:{type:"string",enum:["route","verify","dokploy.projects.list","dokploy.applications.list","dokploy.gitProviders.list","dokploy.github.repositories.list","dokploy.application.ensureGithub","dokploy.domain.ensure","dokploy.deployments.list","dokploy.deployment.logs","dokploy.git.recover","dokploy.application.deploy","dokploy.dockerfile","dokploy.application.publicEnv.upsert","dokploy.project.ensure","convex.customDomains.list","convex.customDomain.ensure","convex.canonical.get","convex.env.presence","convex.canonical.set","convex.project.deploy","convex.snapshot.import","cloudflare.zones.list","cloudflare.dns.upsert","hostinger.dns.upsert","hostinger.mail.orders.list","hostinger.mail.plan.get","hostinger.mail.list","hostinger.mail.logs.list","hostinger.mail.mutate","mcp.tools.list","mcp.tool","composio.tool"]},confirm:{type:"boolean"},tool:{type:"string",maxLength:180},arguments:{type:"object",additionalProperties:true}},["user","provider","connection","operation"]),outputSchema:OUTPUT,
meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>({result:await executeIntegrationAction(a)}),
},
];
diff --git a/lib/mcp/ui-page-integrations.ts b/lib/mcp/ui-page-integrations.ts
index 8855846d..504f7ee5 100644
--- a/lib/mcp/ui-page-integrations.ts
+++ b/lib/mcp/ui-page-integrations.ts
@@ -19,7 +19,7 @@ async function integrationTool(name,args){
function renderIntegrations(){
const back=()=>{integrationAccess=null;lastOutputKey="";current={route:"/integrations",kind:"integrations",title:"Integrations",openPath:"/integrations",catalog:[]};render()};
if(current.setup){captureIntegrationAccess(window.openai?.toolResponseMetadata);viewCleanup=mountIntegrationForm(body,current.setup,{...(integrationAccess||{}),onBack:back,openLink:openIntegrationReference,openBrowser:()=>openIntegrationReference(INTEGRATION_BROWSER)})||(()=>{});return}
- const bridge={openTransferBrowser:()=>openIntegrationReference(INTEGRATION_BROWSER+"?transfer=1"),remember:s=>integrationSelection=s,openLink:openIntegrationReference,
+ const bridge={openTransferBrowser:()=>openIntegrationReference(INTEGRATION_BROWSER+"?transfer=1"),openAiProviders:()=>openIntegrationReference(INTEGRATION_BROWSER+"?section=ai-providers"),remember:s=>integrationSelection=s,openLink:openIntegrationReference,
query:async args=>(await integrationTool("integration_query",args)).data,
manage:async args=>{const{response,data}=await integrationTool("integration_manage",args);const meta=privateIntegrationMeta(response,"integrationAuthorization")||privateIntegrationMeta(window.openai?.toolResponseMetadata,"integrationAuthorization");return{...data,...(meta?.url?{privateUrl:meta.url}:{})}},
projectMcp:async args=>(await integrationTool("project_mcp_manage",args)).data,
diff --git a/lib/workflow/jev-integration.test.ts b/lib/workflow/jev-integration.test.ts
new file mode 100644
index 00000000..05ea3612
--- /dev/null
+++ b/lib/workflow/jev-integration.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+vi.mock("server-only",()=>({}));
+let root:string;
+beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-jev-ref-"));process.env.OS_INFRA_STORE=path.join(root,"infra.json");vi.resetModules();});
+afterEach(async()=>{delete process.env.OS_INFRA_STORE;await fs.rm(root,{recursive:true,force:true});vi.resetModules();});
+
+describe("Jev Integration Variable resolution",()=>{
+ it("uses JEV by default and preserves an explicit connection override",async()=>{
+ const {integrationManage}=await import("@/lib/infra/connection-manage");
+ await integrationManage({action:"user.create",confirm:true,user:"alice"});
+ await integrationManage({action:"connection.create",confirm:true,user:"alice",provider:"mcp",connection:"jev",source:"direct",authMethod:"direct"});
+ await integrationManage({action:"connection.create",confirm:true,user:"alice",provider:"mcp",connection:"alternate",source:"direct",authMethod:"direct"});
+ await integrationManage({action:"variable.set",confirm:true,key:"JEV",user:"alice",provider:"mcp",connection:"jev"});
+ const {resolveJevIntegrationConfig}=await import("./jev-integration");
+ await expect(resolveJevIntegrationConfig()).resolves.toEqual({user:"alice",connection:"jev"});
+ await expect(resolveJevIntegrationConfig({variable:"JEV",model:"decision-model"})).resolves.toEqual({user:"alice",connection:"jev",model:"decision-model"});
+ await expect(resolveJevIntegrationConfig({user:"alice",connection:"alternate"})).resolves.toEqual({user:"alice",connection:"alternate"});
+ await expect(resolveJevIntegrationConfig({user:"alice"})).rejects.toThrow("both integration user and connection");
+ });
+ it("rejects a variable that points to a non-MCP provider",async()=>{
+ const {integrationManage}=await import("@/lib/infra/connection-manage");
+ await integrationManage({action:"user.create",confirm:true,user:"alice"});
+ await integrationManage({action:"connection.create",confirm:true,user:"alice",provider:"github",connection:"work",source:"direct",authMethod:"direct"});
+ await integrationManage({action:"variable.set",confirm:true,key:"JEV",user:"alice",provider:"github",connection:"work"});
+ const {resolveJevIntegrationConfig}=await import("./jev-integration");
+ await expect(resolveJevIntegrationConfig()).rejects.toThrow("must reference provider mcp");
+ });
+});
diff --git a/lib/workflow/jev-integration.ts b/lib/workflow/jev-integration.ts
new file mode 100644
index 00000000..77b69444
--- /dev/null
+++ b/lib/workflow/jev-integration.ts
@@ -0,0 +1,38 @@
+import { resolveIntegrationVariable } from "@/lib/infra/connection-service";
+
+export type JevIntegrationInput = {
+ variable?: string;
+ user?: string;
+ connection?: string;
+ tool?: string;
+ model?: string;
+};
+
+export type JevIntegrationConfig = {
+ user: string;
+ connection: string;
+ tool?: string;
+ model?: string;
+};
+
+function optionalText(value: unknown, max: number): string | undefined {
+ if (value === undefined) return undefined;
+ if (typeof value !== "string" || !value.trim() || value.length > max) throw new Error("invalid Jev integration option");
+ return value.trim();
+}
+
+export async function resolveJevIntegrationConfig(raw?: unknown): Promise<JevIntegrationConfig> {
+ const input = raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, unknown> : {};
+ const user = optionalText(input.user, 64);
+ const connection = optionalText(input.connection, 64);
+ const tool = optionalText(input.tool, 180);
+ const model = optionalText(input.model, 180);
+ if (user || connection) {
+ if (!user || !connection) throw new Error("Jev override requires both integration user and connection");
+ return { user, connection, ...(tool ? { tool } : {}), ...(model ? { model } : {}) };
+ }
+ const variable = optionalText(input.variable, 64) ?? "JEV";
+ const ref = await resolveIntegrationVariable(variable);
+ if (ref.provider !== "mcp") throw new Error(variable + " Integration Variable must reference provider mcp");
+ return { user: ref.user, connection: ref.connection, ...(tool ? { tool } : {}), ...(model ? { model } : {}) };
+}