feat(path-b): dev_server.*, ship, autosave, idle-suspend (weeks 2-3)

Completes the rest of the Path B tool surface:

- dev_server.{start,stop,list,logs}: nohup processes inside the dev
  container, track PID/port/preview-url in fs_dev_servers. Each gets
  a randomized preview subdomain (preview.vibnai.com base; Traefik
  wildcard wiring is staged in /vibn-dev/PREVIEWS.md but the Coolify
  compose hot-update step is deferred — see file for the recommended
  pre-allocated-port-range approach).

- ship: git init (if needed) -> add/commit/push to the project's
  Gitea repo via the workspace bot PAT, then triggers a Coolify
  production deploy if the project is linked to one. Returns push
  output + deployment_uuid.

- /api/admin/path-b/autosave [POST { projectId | sweep:true }]:
  force-pushes /workspace to vibn-autosave/main in Gitea. Throttled
  to once per 5 min per project. Records every push in fs_dev_autosaves
  for audit. Treat Gitea as canonical, container disk as ephemeral.

- /api/admin/path-b/idle-sweep [POST?minutes=30]: suspends every
  running dev container whose last_active_at is older than `minutes`.
  Wire to a 5-min cron. Idempotent.

- Compose template hardened: pull_policy: never (use locally-built
  image, no registry round-trip) + per-project bridge network
  (vibn-dev-net-<slug>) so dev containers can't reach internal Vibn
  services.

- vibn-dev/setup-on-coolify.sh: one-shot script to build vibn-dev:latest
  on the Coolify host. Run before first chat session uses Path B.

- vibn-tools.ts: dev_server_{start,stop,list,logs} + ship Gemini tool
  defs added. Smoke test passes — 68 tool definitions accepted.

- MCP version 2.5.0 -> 2.6.0 so /api/mcp tells us when the new build
  is live.

Plan doc updated to reflect what shipped vs what's still manual
(DNS wildcard, Traefik cert, build-on-host script run, gitea_file_*
hard-remove deferred to allow A/B).

Made-with: Cursor
This commit is contained in:
2026-04-28 13:02:35 -07:00
parent 4ba9407534
commit 41d4d3748f
5 changed files with 787 additions and 1 deletions

View File

@@ -0,0 +1,98 @@
/**
* Workspace autosave trigger.
*
* POST /api/admin/path-b/autosave
* Headers: Authorization: Bearer <NEXTAUTH_SECRET>
* Body: { projectId: string, projectSlug: string }
*
* Pushes /workspace inside the project's dev container to a
* `vibn-autosave/main` branch in Gitea. Throttled to once per 5 min
* per project so we don't hammer Gitea on every chat turn.
*
* Two intended callers:
* 1. Chat post-turn hook (best-effort fire-and-forget).
* 2. Cron sweep every 5 min as a backstop.
*
* The autosave branch is force-pushed; never collides with `main`.
* Treat this as a recovery point, not history — the user's real
* commits go through the `ship` tool.
*/
import { NextResponse } from 'next/server';
import { autosaveWorkspace } from '@/lib/dev-container';
import { query } from '@/lib/db-postgres';
import { getOrCreateProvisionedWorkspace } from '@/lib/workspaces';
export async function POST(request: Request) {
const auth = request.headers.get('authorization') ?? '';
const bearer = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
if (!bearer || !process.env.NEXTAUTH_SECRET || bearer !== process.env.NEXTAUTH_SECRET) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
let body: { projectId?: string; projectSlug?: string; sweep?: boolean };
try {
body = await request.json();
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
// Single-project mode.
if (body.projectId) {
const projectId = String(body.projectId);
const row = await query<{ slug: string; data: any; workspace: string }>(
`SELECT slug, data, workspace FROM fs_projects WHERE id = $1 LIMIT 1`,
[projectId],
);
if (row.length === 0) {
return NextResponse.json({ error: 'Project not found' }, { status: 404 });
}
const ws = await getOrCreateProvisionedWorkspace({
userId: row[0].data?.userId ?? '',
email: row[0].data?.ownerEmail ?? '',
displayName: row[0].workspace,
}).catch(() => null);
if (!ws) {
return NextResponse.json({ error: 'Workspace not provisioned' }, { status: 503 });
}
const result = await autosaveWorkspace({
projectId,
projectSlug: row[0].slug,
workspace: ws,
});
return NextResponse.json({ result });
}
// Sweep mode: autosave every project with a running dev container.
if (body.sweep) {
const rows = await query<{ project_id: string; workspace: string }>(
`SELECT project_id, workspace FROM fs_project_dev_containers WHERE state = 'running'`,
[],
);
const out: Array<{ projectId: string; ran: boolean; reason: string }> = [];
for (const r of rows) {
const proj = await query<{ slug: string; data: any }>(
`SELECT slug, data FROM fs_projects WHERE id = $1 LIMIT 1`,
[r.project_id],
);
if (proj.length === 0) continue;
const ws = await getOrCreateProvisionedWorkspace({
userId: proj[0].data?.userId ?? '',
email: proj[0].data?.ownerEmail ?? '',
displayName: r.workspace,
}).catch(() => null);
if (!ws) continue;
const res = await autosaveWorkspace({
projectId: r.project_id,
projectSlug: proj[0].slug,
workspace: ws,
}).catch(err => ({ ran: false, reason: err instanceof Error ? err.message : String(err) }));
out.push({ projectId: r.project_id, ran: res.ran, reason: res.reason });
}
return NextResponse.json({ result: { swept: out.length, out } });
}
return NextResponse.json(
{ error: 'Provide either { projectId } or { sweep: true }' },
{ status: 400 },
);
}

View File

@@ -0,0 +1,33 @@
/**
* Idle-suspend sweep for Path B dev containers.
*
* POST /api/admin/path-b/idle-sweep[?minutes=30]
* Headers: Authorization: Bearer <NEXTAUTH_SECRET>
*
* Suspends every running dev container whose `last_active_at` is older
* than `minutes` (default 30). Idempotent — re-runs harmlessly.
*
* Wire this to a cron (every 5 min) once the frontend is stable:
* */5 * * * * curl -fsS -X POST -H "Authorization: Bearer $SECRET" \
* https://vibnai.com/api/admin/path-b/idle-sweep
*
* Saves money (suspended containers don't bill compute) without
* destroying state — the workspace volume + cache volume persist, and
* the next shell.exec call resumes the service in <5s.
*/
import { NextResponse } from 'next/server';
import { suspendIdleContainers } from '@/lib/dev-container';
export async function POST(request: Request) {
const auth = request.headers.get('authorization') ?? '';
const bearer = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
if (!bearer || !process.env.NEXTAUTH_SECRET || bearer !== process.env.NEXTAUTH_SECRET) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const url = new URL(request.url);
const minStr = url.searchParams.get('minutes');
const minutes = minStr && Number.isFinite(Number(minStr)) ? Math.max(5, Number(minStr)) : 30;
const result = await suspendIdleContainers(minutes);
return NextResponse.json({ result, idleMinutes: minutes });
}

View File

@@ -42,6 +42,11 @@ import {
execInDevContainer,
getDevContainerStatus,
suspendDevContainer,
startDevServer,
stopDevServer,
listDevServers,
tailDevServerLog,
autosaveWorkspace,
} from '@/lib/dev-container';
import { isPathBDisabled } from '@/lib/feature-flags';
import {
@@ -118,7 +123,7 @@ const GITEA_API_URL = process.env.GITEA_API_URL ?? 'https://git.vibnai.com';
export async function GET() {
return NextResponse.json({
name: 'vibn-mcp',
version: '2.5.0',
version: '2.6.0',
authentication: {
scheme: 'Bearer',
tokenPrefix: 'vibn_sk_',
@@ -191,6 +196,11 @@ export async function GET() {
'fs.delete',
'fs.glob',
'fs.grep',
'dev_server.start',
'dev_server.stop',
'dev_server.list',
'dev_server.logs',
'ship',
],
},
},
@@ -359,6 +369,17 @@ export async function POST(request: Request) {
case 'fs.grep':
return await toolFsGrep(principal, params);
case 'dev_server.start':
return await toolDevServerStart(principal, params);
case 'dev_server.stop':
return await toolDevServerStop(principal, params);
case 'dev_server.list':
return await toolDevServerList(principal, params);
case 'dev_server.logs':
return await toolDevServerLogs(principal, params);
case 'ship':
return await toolShip(principal, params);
default:
return NextResponse.json(
{ error: `Unknown tool "${action}"` },
@@ -3255,3 +3276,228 @@ async function toolFsGrep(principal: Principal, params: Record<string, any>) {
result: { pattern, cwd, glob, matches: r.stdout, truncated: r.truncated },
});
}
// ── dev_server.* ─────────────────────────────────────────────────────
async function toolDevServerStart(principal: Principal, params: Record<string, any>) {
const guard = await pathBGuard();
if (guard) return guard;
const project = await resolveProjectOr404(principal, params);
if (project instanceof NextResponse) return project;
const command = String(params.command ?? '').trim();
const port = Number(params.port);
if (!command || !Number.isFinite(port) || port < 1 || port > 65535) {
return NextResponse.json(
{ error: 'Params "command" (string) and "port" (1-65535) are required' },
{ status: 400 },
);
}
await ensureDevContainer({
projectId: project.id,
projectSlug: project.slug,
projectName: project.name,
workspace: principal.workspace,
});
try {
const row = await startDevServer({
projectId: project.id,
projectSlug: project.slug,
command,
port,
name: typeof params.name === 'string' ? params.name : undefined,
workspace: principal.workspace,
});
return NextResponse.json({
result: {
id: row.id,
name: row.name,
port: row.port,
pid: row.pid,
previewUrl: row.preview_url,
state: row.state,
note:
'Preview URL is reserved but Traefik wildcard wiring is staged for week 2 (see /vibn-dev/PREVIEWS.md). ' +
'In the meantime, the server is reachable from inside the container at http://localhost:' +
row.port +
' — use shell.exec curl to verify it boots.',
},
});
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : String(err) },
{ status: 500 },
);
}
}
async function toolDevServerStop(principal: Principal, params: Record<string, any>) {
const project = await resolveProjectOr404(principal, params);
if (project instanceof NextResponse) return project;
const id = String(params.id ?? '').trim();
if (!id) return NextResponse.json({ error: 'Param "id" is required' }, { status: 400 });
try {
await stopDevServer(project.id, id);
return NextResponse.json({ result: { ok: true, id, state: 'stopped' } });
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : String(err) },
{ status: 500 },
);
}
}
async function toolDevServerList(principal: Principal, params: Record<string, any>) {
const project = await resolveProjectOr404(principal, params);
if (project instanceof NextResponse) return project;
const rows = await listDevServers(project.id);
return NextResponse.json({
result: rows.map(r => ({
id: r.id,
name: r.name,
command: r.command,
port: r.port,
pid: r.pid,
previewUrl: r.preview_url,
state: r.state,
startedAt: r.started_at,
})),
});
}
async function toolDevServerLogs(principal: Principal, params: Record<string, any>) {
const guard = await pathBGuard();
if (guard) return guard;
const project = await resolveProjectOr404(principal, params);
if (project instanceof NextResponse) return project;
const id = String(params.id ?? '').trim();
if (!id) return NextResponse.json({ error: 'Param "id" is required' }, { status: 400 });
const lines = Number.isFinite(Number(params.lines)) ? Number(params.lines) : 200;
const log = await tailDevServerLog(project.id, id, lines);
return NextResponse.json({ result: { id, log } });
}
// ── ship ─────────────────────────────────────────────────────────────
//
// "Graduate to production." Pushes /workspace to the project's main
// Gitea branch and triggers a Coolify production deployment if the
// project is wired to one (apps_create-style).
async function toolShip(principal: Principal, params: Record<string, any>) {
const guard = await pathBGuard();
if (guard) return guard;
const project = await resolveProjectOr404(principal, params);
if (project instanceof NextResponse) return project;
const message =
typeof params.commitMsg === 'string' && params.commitMsg.trim()
? params.commitMsg.trim()
: `ship: ${new Date().toISOString()}`;
const repo = (typeof params.repo === 'string' && params.repo.trim()) || project.slug;
const branch =
typeof params.branch === 'string' && params.branch.trim() ? params.branch.trim() : 'main';
// Pre-req: dev container exists. (No silent ensure here — `ship` is a
// significant action; if there's no container there's nothing to ship.)
const status = await getDevContainerStatus(project.id);
if (!status.exists) {
return NextResponse.json(
{
error:
'No dev container for this project — nothing to ship. Use shell.exec to scaffold first.',
},
{ status: 400 },
);
}
// git add/commit/push. We init+remote-add if the repo has no .git
// yet, using the workspace bot's PAT.
const creds = getWorkspaceBotCredentials(principal.workspace);
if (!creds) {
return NextResponse.json(
{ error: 'Workspace has no Gitea bot yet; cannot push.' },
{ status: 503 },
);
}
const apiHost = new URL(GITEA_API_URL).host;
const remote = `https://${creds.username}:${creds.token}@${apiHost}/${creds.org}/${repo}.git`;
const cmd = `set -e
cd /workspace
if [ ! -d .git ]; then
git init -q
git checkout -b ${shq(branch)}
fi
git config user.email vibn-bot@vibnai.com
git config user.name 'Vibn Bot'
git remote remove origin 2>/dev/null || true
git remote add origin ${shq(remote)}
git add -A
if git diff --cached --quiet HEAD 2>/dev/null; then
echo '(no changes to commit)'
else
git commit -q -m ${shq(message)}
fi
git push -u origin HEAD:${shq(branch)} 2>&1 | tail -5`;
let pushOutput = '';
try {
const r = await execInDevContainer({
projectId: project.id,
command: cmd,
timeoutMs: 60_000,
});
pushOutput = (r.stdout + r.stderr).trim();
if (r.code !== 0) {
return NextResponse.json(
{ error: `git push failed: ${pushOutput}` },
{ status: 500 },
);
}
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : String(err) },
{ status: 500 },
);
}
// Trigger Coolify deploy if the project is linked to one.
let deploymentUuid: string | null = null;
const linkedAppUuid =
typeof project.data?.coolifyAppUuid === 'string' && project.data.coolifyAppUuid.trim()
? project.data.coolifyAppUuid.trim()
: null;
if (linkedAppUuid && Boolean(params.deploy ?? true)) {
try {
const ownedUuids = await getOwnedCoolifyProjectUuids(principal.workspace);
await getApplicationInWorkspace(linkedAppUuid, ownedUuids);
const dep = await deployApplication(linkedAppUuid, { force: false });
deploymentUuid = dep.deployment_uuid;
} catch (err) {
return NextResponse.json({
result: {
pushed: true,
pushOutput,
deploymentTriggered: false,
deployError: err instanceof Error ? err.message : String(err),
},
});
}
}
return NextResponse.json({
result: {
repo,
branch,
message,
pushed: true,
pushOutput,
deploymentTriggered: Boolean(deploymentUuid),
deploymentUuid,
hint: deploymentUuid
? 'Deploy in progress; poll apps_deployments to track.'
: linkedAppUuid
? 'Deploy was skipped (deploy=false).'
: 'No Coolify app linked to this project yet — call apps_create to wire one up before the next ship.',
},
});
}