Build a GitHub integration with a hosted dashboard
This example builds a GitHub analytics product whose dashboard stays hosted, while each customer's GitHub token and private GitHub Enterprise server stay in their environment. A small Worker (serverless code Alien runs there) does everything that touches GitHub and returns metrics.
Architecture diagram. Left: Your cloud containing Control plane, Next.js dashboard, Postgres (metadata), sync workflow. Right: Customer cloud containing Data plane containing agent (Worker); integrations (Vault).
This is the control plane ⇄ data plane split applied to a whole product. The same structure fits a security scanner, an internal search connector, or any integration that needs credentials or network access the customer won't put in your SaaS backend.
Source: examples/github-agent. The template has two packages: packages/remote-agent (the data plane) and packages/dashboard (the control plane).
What goes where
| Your cloud (control plane) | Customer's environment (data plane) |
|---|---|
| Next.js dashboard, Postgres, authentication, a durable workflow | A Worker named agent |
| Billing, organization membership, charts, metric history | A Vault named integrations with the GitHub token |
| Calls the Alien platform API to manage deployments | Commands set-integration, analyze-repository, label-pull-requests |
One HTTPS route, GET /prs, for pull request details |
Nothing in your cloud is duplicated per customer. The page follows one organization from sign-up to its first repository analysis:
- The dashboard creates a deployment group (Alien's record of one customer) for the organization.
- The customer's admin sets up the Worker from a setup link, a URL that opens the setup page Alien hosts for them.
- The dashboard sends the repository config to that deployment.
- A workflow calls
analyze-repositoryand stores the metrics. - The browser fetches pull request details from the Worker's HTTPS endpoint.
The agent
The remote package has its own alien.ts:
import * as alien from "@alienplatform/core"
const integrations = new alien.Vault("integrations").build()
const agent = new alien.Worker("agent")
.code({ type: "source", src: "./", toolchain: { type: "typescript" } })
.link(integrations)
.memoryMb(512)
.commandsEnabled(true)
.publicEndpoint("api")
.permissions("execution")
.build()
export default new alien.Stack("github-agent")
.platforms(["aws", "gcp", "azure", "kubernetes"])
.add(integrations, "frozen")
.add(agent, "live")
.permissions({
profiles: {
execution: {},
},
})
.build()- The Worker has two entry points on purpose. Commands carry private product operations from your backend, with no inbound port, VPN, or peering. The public endpoint serves
GET /prsto the browser, which needs a URL. integrationsis frozen: the initial setup (the admin's one-time step) creates it and releases never replace it, so stored tokens survive every code update.agentis live: each release replaces it. See Frozen and live.- The
executionprofile is empty. Linking a Vault without naming it in the profile grants the defaultvault/data-readandvault/data-write, which the Worker needs to save and load configs. Name it explicitly in production; see Permissions. - The stack supports Kubernetes as well as the three clouds, so a customer can run it in their own cluster.
GitHub config in the customer's vault
set-integration validates the config and writes it to the vault under the integration's ID:
const integrationIdSchema = z.object({ integrationId: z.string() })
const setIntegrationSchema = integrationIdSchema.extend({
config: z.object({
owner: z.string(),
repo: z.string(),
token: z.string().optional(),
baseUrl: z.string().optional(),
}),
})
// ...
command("set-integration", setIntegrationSchema, async ({ integrationId, config }) => {
const id = ensureIntegrationId(integrationId)
const normalized = normalizeConfig(config)
console.log(`Saving integration config for ${id}: ${normalized.owner}/${normalized.repo}`)
await saveIntegrationConfig(id, normalized)
return { ok: true }
})The vault helpers wrap vault("integrations"):
import { vault } from "@alienplatform/sdk"
import type { IntegrationConfig } from "./types.js"
const VAULT_NAME = "integrations"
export async function saveIntegrationConfig(
integrationId: string,
config: IntegrationConfig,
): Promise<void> {
const integrations = await vault(VAULT_NAME)
await integrations.putJson(integrationId, config)
}
export async function loadIntegrationConfig(integrationId: string): Promise<IntegrationConfig> {
const integrations = await vault(VAULT_NAME)
try {
return await integrations.getJson<IntegrationConfig>(integrationId)
} catch (error) {
const message = error instanceof Error ? error.message : "Integration configuration not found"
throw new Error(`Missing integration ${integrationId}: ${message}`)
}
}baseUrl points the Worker at GitHub Enterprise; without it the Worker calls https://api.github.com. Because the Worker runs in the customer's environment, it can reach a GitHub Enterprise server on their private network.
Where the token goes:
- The user types it into your dashboard.
- Your backend passes it through the
set-integrationcommand. - The Worker writes it to the vault.
- Every later GitHub call loads it from the vault inside the customer's environment.
Your database never stores the token; it keeps only hasToken.
Product operations as commands
command("analyze-repository", integrationIdSchema, async ({ integrationId }) => {
const id = ensureIntegrationId(integrationId)
console.log(`Analyzing repository for integration ${id}`)
const config = await loadIntegrationConfig(id)
const prs = await fetchPullRequests(config)
const classified = classifyPullRequests(prs)
const metrics = computeMetrics(classified)
console.log(
`Analysis complete: ${metrics.totalPRs} PRs, review throughput score ${metrics.reviewThroughputScore}`,
)
return metrics
})fetchPullRequestsreads the 30 most recent pull requests, then fetches details, files, and reviews for each with at most five requests in flight.classifyPullRequestsizes each one by lines changed (smallunder 100,mediumunder 500,largeabove). It scores risk from size, files changed, and hours to first review, intolow,medium,high, orcritical.computeMetricsaggregates counts, average review and merge times, a throughput score, and the most-changed files.
label-pull-requests applies size:* and risk:* labels to open pull requests through the GitHub API.
The callable surface is three named, schema-validated operations. A new operation is a reviewed code change and a release, not a remote shell.
Demo mode
A config with no token, or the token demo, makes the Worker use six built-in pull requests instead of calling GitHub. label-pull-requests then returns a fixed result without writing labels.
Demo mode lets you run the whole product without a GitHub token.
Pull request details over HTTPS
app.get("/prs", async c => {
const start = Date.now()
const integrationId = c.req.query("integrationId")?.trim()
if (!integrationId) {
return c.json({ error: "integrationId is required" }, 400)
}
const config = await loadIntegrationConfig(integrationId)
console.log(`Fetching PRs for integration ${integrationId}`)
const prs = await fetchPullRequests(config)
const classified = classifyPullRequests(prs)The route returns every pull request with its size, risk, and a review summary. The browser calls it directly, so titles, file paths, and review text go from the customer's environment to the user's browser without passing through your backend.
Only aggregate metrics reach your database.
The review summaries come from generateAIReview, which returns fixed sample reviews for the demo pull requests. In a real product, call a model there, for example through an AI resource in the customer's cloud.
Run the agent locally
alien init github-agent github-agent
cd github-agent/packages/remote-agent
pnpm install
alien devIn a second terminal, register a demo integration and analyze it:
alien dev commands invoke --deployment local-dev/default \
--command set-integration \
--params '{"integrationId": "demo-repo", "config": {"owner": "acme", "repo": "api", "token": "demo"}}'{ "ok": true }alien dev commands invoke --deployment local-dev/default \
--command analyze-repository --params '{"integrationId": "demo-repo"}'The demo data has six pull requests: three small, two medium, one large. The response starts like this, followed by avgTimeToFirstReviewHours, avgMergeTimeHours, reviewThroughputScore, and churnHotspots:
{
"totalPRs": 6,
"bySize": { "small": 3, "medium": 2, "large": 1 },
"byRisk": { "low": 2, "medium": 3, "high": 0, "critical": 1 }
}Fetch the details over HTTP from the URL alien dev printed:
curl "<url>/prs?integrationId=demo-repo"packages/remote-agent/tests/remote-agent.test.ts runs this flow. It deploys locally, registers demo-repo, and checks the six pull requests, the size split, the demo labels, and /prs. Run it with pnpm test.
Connect the dashboard
The dashboard needs Postgres and an Alien workspace and project, because it creates deployment groups and setup links through the platform API:
| Variable | Value |
|---|---|
ALIEN_API_URL | Platform API URL |
ALIEN_TOKEN | A server-side Alien API key |
ALIEN_WORKSPACE, ALIEN_PROJECT | Your workspace and project |
DATABASE_URL | The dashboard's Postgres |
BETTER_AUTH_SECRET, BETTER_AUTH_URL | Session auth for the dashboard |
DEMO_MODE | true to allow integrations without a GitHub token |
cd packages/dashboard
docker-compose up -d
pnpm install
pnpm db:push
pnpm db:seed
pnpm devThe dashboard listens on http://localhost:3001. Sign in with demo@example.com and demo1234.
One deployment group per organization
When an organization first needs a deployment, the dashboard creates a deployment group for it and a token for the initial setup. The example does this in lib/deployment-groups.ts. With the platform SDK:
const deploymentGroup = await alien.deploymentGroups.createDeploymentGroup({
name,
project: config.project,
maxDeployments: 10,
})
const tokenResponse = await alien.deploymentGroups.createToken(deploymentGroup.id, {
description: `Deployment token for ${organizationName}`,
})The dashboard stores the group ID with the organization and lists only that group's deployments with alien.deployments.list({ deploymentGroup }). An organization points to its deployment group, and each repository integration points to one deployment in it.
The customer's admin opens the setup link and chooses where the Worker runs: AWS, Google Cloud, Azure, or their Kubernetes cluster. After that initial setup, releases reach the Worker without them.
Send the config to the right deployment
When a user adds a repository, the dashboard builds an integration ID, invokes set-integration on the organization's deployment, and stores only metadata:
const integrationId = `github-${activeOrgId}-${owner}-${repo}`
.toLowerCase()
.replace(/[^a-z0-9-]/g, "-")
// ...
try {
await invokeCommand(agentId, "set-integration", {
integrationId,
config,
})
} catch (error) {
console.error("Failed to set integration in agent:", error)
return Response.json(
{ error: "Failed to configure agent. Make sure the agent is running." },
{ status: 500 },
)
}
// Store only metadata in database
await db.insert(integration).values({
id: integrationId,
organizationId: activeOrgId,
agentId: agentId,
owner,
repo,
baseUrl: baseUrl || null,
hasToken: !!token && token !== "demo",
isActive: true,
createdAt: new Date(),
updatedAt: new Date(),
})invokeCommand wraps a commands client for one deployment (lib/arc.ts in the example). With @alienplatform/commands:
import { CommandsClient } from "@alienplatform/commands"
const commands = await CommandsClient.forDeployment({
deploymentId,
apiKey: process.env.ALIEN_TOKEN!,
})
const metrics = await commands.target("agent").invoke("analyze-repository", { integrationId })Sync results into your database
A durable workflow invokes analyze-repository for each of the organization's integrations every five seconds and writes the returned metrics to the dashboard's own tables:
async function fetchMetricsFromAgent(integrationId: string, agentId: string) {
"use step"
const { invokeCommand } = await import("@/lib/arc")
try {
const metrics = await invokeCommand<AnalysisMetrics>(agentId, "analyze-repository", {
integrationId,
})
return { success: true as const, metrics }
} catch (error) {
return {
success: false as const,
error: error instanceof Error ? error.message : "Unknown error",
}
}
}A failed call is recorded as a sync error on the integration instead of crashing the loop.
The Worker owns GitHub access and analysis; the dashboard owns history and presentation. Only the metrics cross between them.
How it runs on each platform
| Platform | agent | integrations |
|---|---|---|
| AWS | Lambda | SSM Parameter Store SecureString parameters |
| Google Cloud | Cloud Run | Secret Manager secrets |
| Azure | Container Apps | Key Vault |
| Kubernetes | Deployment and Service | Kubernetes Secrets in the deployment namespace |
alien dev | Native process | JSON file on disk |
Before production
- Authenticate
/prs. It's open in the example and returns data for anyintegrationId. Have your dashboard issue a short-lived token that the Worker verifies, scoped to the integration. See Browser to the deployment. - Restrict CORS. The Worker allows every origin (
cors()). Allow only your dashboard's origin. - Sync less often. Each
analyze-repositorycall makes about 90 GitHub requests for 30 pull requests. Every five seconds will hit GitHub's rate limits on a real repository. - Name the vault in the permission profile with exactly the sets the Worker needs.
- Don't log repository names if they're sensitive to the customer; the Worker's logs stay in their environment, but your log forwarding may not.
Next
Call the cloud's models
A Worker that lists and calls the models in Amazon Bedrock, Vertex AI, or Azure AI Foundry with its own cloud identity. No API keys.
Chat with a private Postgres
A streaming Next.js chat app in the customer's cloud that answers from a private Postgres through a model served by the same cloud. No API keys, no database password in the app.