Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
1cb813c
feat(db): feature flags with per-user overrides, and ai_usage_logs.ke…
2witstudios Nov 30, 2026
635bfae
feat(agent-accounts): inference executor — a person's own model key, …
2witstudios Nov 30, 2026
0587b59
test(agent-accounts): inference executor through the real grant chain…
2witstudios Nov 30, 2026
45da033
feat(ai): route a person's model calls to their own key through the p…
2witstudios Nov 30, 2026
4a408b4
feat(byok): admin feature flags per person, and Settings → AI 'Use yo…
2witstudios Nov 30, 2026
4d2755f
docs(byok): ADR 0009 (model keys through the credential plane), threa…
2witstudios Nov 30, 2026
ffe2844
test(seams): ledger the inference executor's caller-ceiling read (it …
2witstudios Nov 30, 2026
7a14e8b
feat(billing): one key-source decision at every model-call surface (B…
2witstudios Nov 30, 2026
1961dc6
Merge remote-tracking branch 'origin/master' into pu/byok-model-keys
2witstudios Nov 30, 2026
d143c19
feat(byok): check a key with OpenRouter when it is added, through the…
2witstudios Nov 30, 2026
531a239
feat(billing): workflows and triggers on the creator's own key take n…
2witstudios Nov 30, 2026
24cf2e7
fix(byok): CI — GDPR export decision for the flag tables, key_source …
2witstudios Nov 30, 2026
25826fb
Merge remote-tracking branch 'origin/master' into pu/byok-model-keys
2witstudios Nov 30, 2026
7979acd
fix(byok): keep org content and other people's money off a person's o…
2witstudios Nov 30, 2026
1072e6c
fix(byok): serialize model-key saves and removals, and report an unre…
2witstudios Nov 30, 2026
8e6cc04
fix(byok): release a fixed content type for an upstream model answer
2witstudios Nov 30, 2026
c3cf788
fix(byok): cancel a model call when the web caller leaves before the …
2witstudios Nov 30, 2026
9d12c56
fix(byok): give an upstream null-body status a null Response body
2witstudios Nov 30, 2026
fe44904
refactor(byok): one copy of the own-key-unavailable message; type the…
2witstudios Nov 30, 2026
e79a66b
Merge remote-tracking branch 'origin/master' into pu/byok-model-keys
2witstudios Nov 30, 2026
7c6f087
fix(byok): nested runs inherit the caller's key; unknown outcomes are…
2witstudios Nov 30, 2026
3803fd2
fix(byok): a durable managed-conversation mark, session workers keep …
2witstudios Nov 30, 2026
0f89734
fix(byok): mark every managed conversation, workflows and voice inclu…
2witstudios Nov 30, 2026
0bdb9e6
fix(byok): fence model-key removal against lock loss, and never leave…
2witstudios Nov 30, 2026
23a83d8
fix(byok): the managed mark fails closed, abandoned keys leave no mat…
2witstudios Nov 30, 2026
a44edc8
fix(byok): a turn marks its conversation only after ownership and the…
2witstudios Nov 30, 2026
68e9400
fix(byok): consult marks before saving its question; a raced page row…
2witstudios Nov 30, 2026
f5063cc
Merge remote-tracking branch 'origin/master' into byok-merge-master
2witstudios Nov 30, 2026
eef4660
fix(byok): refuse a raced page conversation; keep an unconfirmed key …
2witstudios Nov 30, 2026
88fbf61
fix(byok): sweep abandoned model keys without user action; read every…
2witstudios Nov 30, 2026
d366c85
fix(byok): page the abandoned-key sweep past failing rows; pin the si…
2witstudios Nov 30, 2026
921d8c0
Merge remote-tracking branch 'origin/master' into byok-merge-master
2witstudios Nov 30, 2026
b785c16
fix(byok): a model-key cleanup ref that outlives the account, recorde…
2witstudios Nov 30, 2026
7bdbcaa
fix(byok): a cleanup ref stays until no write can land; a tenant-look…
2witstudios Nov 30, 2026
c10bd55
fix(byok): retiring a stranded model key keeps its cleanup ref for th…
2witstudios Nov 30, 2026
5148aa9
fix(byok): fence the abandoned-key sweep with the person's model-key …
2witstudios Nov 30, 2026
53e297d
fix(byok): date a model-key cleanup ref from when its write is sent
2witstudios Nov 30, 2026
c94e6ce
Merge remote-tracking branch 'origin/master' into byok-merge-master
2witstudios Nov 30, 2026
5bf2137
fix(byok): fence a model key's first vault write against the cleanup …
2witstudios Nov 30, 2026
e22751b
Merge remote-tracking branch 'origin/master' into byok-merge-master
2witstudios Nov 30, 2026
c27d170
docs(adr-0009): record the plane writer-lock-loss residual for model-…
2witstudios Nov 30, 2026
3594f63
test(byok): wire the cleanup-ref store into the end-to-end plane
2witstudios Nov 30, 2026
743e66b
Merge remote-tracking branch 'origin/master' into byok-merge-master
2witstudios Nov 30, 2026
f177a7d
Merge remote-tracking branch 'origin/master' into byok-merge-master
2witstudios Nov 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ All notable user-facing changes to PageSpace are documented here. Format follows

## [Unreleased]

- **Preview: bring your own OpenRouter key.** An admin can now turn this on for specific people in Admin → Feature Flags. Those people get a "Use your own OpenRouter key" card in Settings → AI.
- **Your own model calls run on your key and cost no PageSpace credits.** That covers chat, the global assistant, side questions, agent-to-agent calls, images and your automations. Pro-tier models are available on your key whatever your plan.
- **PageSpace never stores your key.** It goes once to an isolated credential service, is added to each request there, and is removed from anything that comes back. It can never be read back by PageSpace or by an agent, and agents cannot use it as a tool.
- **Calls in an organization's drives always use PageSpace's key**, so an org's content is never sent through a personal OpenRouter account. On your key, the assistant cannot read organization drives, and memory learned from them is left out.
- **Your key only pays for calls you fund yourself.** Calls in a drive someone else owns, and conversations that have already used PageSpace's key, stay on PageSpace's key.
- Work handed between agents keeps the key it started on. An agent started from a conversation on PageSpace's key runs on PageSpace's key. A conversation on your key can't consult an agent, or read a session, that runs on PageSpace's key.
- If an admin switches the preview off for you, PageSpace stops using your key and Settings still lets you remove it.
- **If your key can't be used, the call stops with a message.** It never quietly switches to PageSpace's key. Usage on your key is capped at 1,200 calls an hour. For safety, create a separate OpenRouter key with a credit limit.
- Removing the key in Settings takes it out of PageSpace. It keeps working at OpenRouter until you revoke it there.
- **Local Environments work on Windows.** You can now enrol and connect a Windows computer with `pagespace env enroll` and `pagespace env connect` (CLI 1.13.2), from PowerShell or Command Prompt, with Git for Windows installed (agents' shell commands run in its `sh`). The setup panel no longer tells you not to enrol from Windows.
- **Agents stay signed in to websites, so you approve the password once.** After you approve a website login, the agent's browser can keep that sign-in for you, and the next time the agent needs the site it reuses it instead of typing the password.
- **The saved sign-in is yours alone, and that agent's.** It is only reused in your own conversations with the agent that signed in, never during someone else's turn on a shared agent and never by another of your agents or your global assistant (each signs in for itself). Only you can approve reusing it.
Expand Down
195 changes: 195 additions & 0 deletions apps/admin/src/app/(admin)/feature-flags/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
"use client";

/**
* Feature flags: turn a not-yet-GA feature on for named people, or for everyone. A person's own setting wins
* over the default. Every change is audited.
*/
import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { PageHeader, DataState } from "@/components/admin/kit";
import { useAdminQuery } from "@/hooks/use-admin-query";
import { fetchWithAuth } from "@/lib/auth/auth-fetch";

interface FlagState {
key: string;
label: string;
description: string;
enabledByDefault: boolean;
userOverrideCount: number;
unavailableHere: boolean;
}

interface FlagUser {
userId: string;
name: string | null;
email: string | null;
enabled: boolean;
updatedAt: string;
}

interface UserSearchResult {
id: string;
name: string | null;
email: string | null;
}

async function send(url: string, method: "PUT" | "PATCH" | "DELETE", body?: unknown): Promise<string | null> {
const response = await fetchWithAuth(url, {
method,
headers: { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (response.ok) return null;
const json = (await response.json().catch(() => ({}))) as { error?: string };
return json.error ?? `Request failed (${response.status})`;
}

function FlagPeople({ flag, onChanged }: { flag: FlagState; onChanged: () => void }) {
const usersUrl = `/api/admin/feature-flags/${flag.key}/users`;
const people = useAdminQuery<{ users: FlagUser[] }>(usersUrl);
const [query, setQuery] = useState("");
const [results, setResults] = useState<UserSearchResult[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);

async function search() {
setError(null);
const response = await fetchWithAuth(`/api/admin/users?q=${encodeURIComponent(query.trim())}&limit=10`);
if (!response.ok) return setError("Search failed");
const json = (await response.json()) as { users: UserSearchResult[] };
setResults(json.users);
}

async function act(run: () => Promise<string | null>) {
setBusy(true);
setError(null);
// A request that rejects (network loss) is a failure to show, not an exception that leaves the buttons disabled.
const failed = await run().catch((err: unknown) => (err instanceof Error ? err.message : "Request failed"));
setBusy(false);
if (failed) return setError(failed);
people.refetch();
onChanged();
}

const assigned = new Set((people.data?.users ?? []).map((user) => user.userId));

return (
<div className="space-y-4">
<form
className="flex max-w-lg gap-2"
onSubmit={(event) => {
event.preventDefault();
if (query.trim().length > 0) void search();
}}
>
<Input placeholder="Find a person by name or email" value={query} onChange={(event) => setQuery(event.target.value)} />
<Button type="submit" variant="outline" disabled={query.trim().length === 0}>
Search
</Button>
</form>

{results.length > 0 && (
<Table>
<TableBody>
{results.map((user) => (
<TableRow key={user.id}>
<TableCell>{user.name ?? "—"}</TableCell>
<TableCell className="text-muted-foreground">{user.email ?? "—"}</TableCell>
<TableCell className="text-right">
{assigned.has(user.id) ? (
<Badge variant="secondary">Already set</Badge>
) : (
<Button size="sm" disabled={busy} onClick={() => act(() => send(`${usersUrl}/${user.id}`, "PUT", { enabled: true }))}>
Turn on for this person
</Button>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}

{error && <p className="text-sm text-destructive">{error}</p>}

<DataState isLoading={people.isLoading} error={people.error} onRetry={people.refetch} hasData={people.data !== null} isEmpty={(people.data?.users.length ?? 0) === 0} emptyMessage="Nobody has their own setting for this flag yet.">
<Table>
<TableHeader>
<TableRow>
<TableHead>Person</TableHead>
<TableHead>Email</TableHead>
<TableHead>Setting</TableHead>
<TableHead className="text-right">Change</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{(people.data?.users ?? []).map((user) => (
<TableRow key={user.userId}>
<TableCell>{user.name ?? user.userId}</TableCell>
<TableCell className="text-muted-foreground">{user.email ?? "—"}</TableCell>
<TableCell>{user.enabled ? <Badge>On</Badge> : <Badge variant="secondary">Off</Badge>}</TableCell>
<TableCell className="space-x-2 text-right">
<Button size="sm" variant="outline" disabled={busy} onClick={() => act(() => send(`${usersUrl}/${user.userId}`, "PUT", { enabled: !user.enabled }))}>
Turn {user.enabled ? "off" : "on"}
</Button>
<Button size="sm" variant="ghost" disabled={busy} onClick={() => act(() => send(`${usersUrl}/${user.userId}`, "DELETE"))}>
Use default
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</DataState>
</div>
);
}

export default function FeatureFlagsPage() {
const flags = useAdminQuery<{ flags: FlagState[] }>("/api/admin/feature-flags");
const [error, setError] = useState<string | null>(null);

async function setDefault(flag: FlagState, enabledByDefault: boolean) {
setError(null);
const failed = await send("/api/admin/feature-flags", "PATCH", { key: flag.key, enabledByDefault });
if (failed) setError(failed);
flags.refetch();
}

return (
<div className="space-y-6">
<PageHeader title="Feature flags" description="Turn preview features on for specific people, or for everyone. A person's own setting wins over the default." />
{error && <p className="text-sm text-destructive">{error}</p>}
<DataState isLoading={flags.isLoading} error={flags.error} onRetry={flags.refetch} hasData={flags.data !== null} isEmpty={(flags.data?.flags.length ?? 0) === 0}>
{(flags.data?.flags ?? []).map((flag) => (
<Card key={flag.key}>
<CardHeader>
<CardTitle className="flex flex-wrap items-center gap-2">
{flag.label}
<code className="text-xs text-muted-foreground">{flag.key}</code>
{flag.unavailableHere && <Badge variant="secondary">Off on this deployment</Badge>}
</CardTitle>
<CardDescription>{flag.description}</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3 rounded-md border p-3">
<div className="text-sm">
<p className="font-medium">For everyone else: {flag.enabledByDefault ? "On" : "Off"}</p>
<p className="text-muted-foreground">{flag.userOverrideCount} {flag.userOverrideCount === 1 ? "person has" : "people have"} their own setting.</p>
</div>
<Button variant={flag.enabledByDefault ? "outline" : "default"} disabled={flag.unavailableHere} onClick={() => setDefault(flag, !flag.enabledByDefault)}>
Turn {flag.enabledByDefault ? "off" : "on"} for everyone
</Button>
</div>
<FlagPeople flag={flag} onChanged={flags.refetch} />
</CardContent>
</Card>
))}
</DataState>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { NextResponse } from 'next/server';
import { z } from 'zod/v4';
import { db } from '@pagespace/db/db';
import { eq } from '@pagespace/db/operators';
import { users } from '@pagespace/db/schema/auth';
import { withAdminAuth } from '@/lib/auth';
import { auditRequest } from '@pagespace/lib/audit/audit-log';
import { loggers } from '@pagespace/lib/logging/logger-config';
import { isFeatureFlagKey } from '@pagespace/lib/feature-flags/flags';
import { createFeatureFlagRepository } from '@pagespace/lib/feature-flags/feature-flag-repository';

type RouteContext = { params: Promise<{ key: string; userId: string }> };

const setOverrideBody = z.object({ enabled: z.boolean() }).strict();

/** PUT /api/admin/feature-flags/[key]/users/[userId] — turn the flag on (or off) for this one person. */
export const PUT = withAdminAuth<RouteContext>(async (adminUser, request, context) => {
const { key, userId } = await context.params;
if (!isFeatureFlagKey(key)) return NextResponse.json({ error: 'Unknown flag' }, { status: 404 });
const parsed = setOverrideBody.safeParse(await request.json().catch(() => null));
if (!parsed.success) return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
try {
const [target] = await db.select({ id: users.id }).from(users).where(eq(users.id, userId)).limit(1);
if (!target) return NextResponse.json({ error: 'User not found' }, { status: 404 });
await createFeatureFlagRepository().setOverride({ flag: key, userId, enabled: parsed.data.enabled, adminUserId: adminUser.id });
auditRequest(request, {
eventType: 'admin.settings.changed',
userId: adminUser.id,
resourceType: 'feature_flag',
resourceId: key,
details: { source: 'admin', action: 'set_feature_flag_user', targetUserId: userId, enabled: parsed.data.enabled },
});
return NextResponse.json({ success: true });
} catch (error) {
loggers.api.error('Error setting feature flag for user', error instanceof Error ? error : undefined);
return NextResponse.json({ error: 'Failed to update feature flag' }, { status: 500 });
}
});

/** DELETE /api/admin/feature-flags/[key]/users/[userId] — the person follows the flag's default again. */
export const DELETE = withAdminAuth<RouteContext>(async (adminUser, request, context) => {
const { key, userId } = await context.params;
if (!isFeatureFlagKey(key)) return NextResponse.json({ error: 'Unknown flag' }, { status: 404 });
try {
const removed = await createFeatureFlagRepository().removeOverride({ flag: key, userId });
if (!removed) return NextResponse.json({ error: 'No setting for this person' }, { status: 404 });
auditRequest(request, {
eventType: 'admin.settings.changed',
userId: adminUser.id,
resourceType: 'feature_flag',
resourceId: key,
details: { source: 'admin', action: 'clear_feature_flag_user', targetUserId: userId },
});
return NextResponse.json({ success: true });
} catch (error) {
loggers.api.error('Error clearing feature flag for user', error instanceof Error ? error : undefined);
return NextResponse.json({ error: 'Failed to update feature flag' }, { status: 500 });
}
});
35 changes: 35 additions & 0 deletions apps/admin/src/app/api/admin/feature-flags/[key]/users/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { NextResponse } from 'next/server';
import { db } from '@pagespace/db/db';
import { inArray } from '@pagespace/db/operators';
import { users } from '@pagespace/db/schema/auth';
import { withAdminAuth } from '@/lib/auth';
import { loggers } from '@pagespace/lib/logging/logger-config';
import { decryptUserRows } from '@pagespace/lib/auth/user-repository';
import { isFeatureFlagKey } from '@pagespace/lib/feature-flags/flags';
import { createFeatureFlagRepository } from '@pagespace/lib/feature-flags/feature-flag-repository';

type RouteContext = { params: Promise<{ key: string }> };

/** GET /api/admin/feature-flags/[key]/users — the people with their own setting for this flag. */
export const GET = withAdminAuth<RouteContext>(async (_adminUser, _request, context) => {
const { key } = await context.params;
if (!isFeatureFlagKey(key)) return NextResponse.json({ error: 'Unknown flag' }, { status: 404 });
try {
const overrides = await createFeatureFlagRepository().listOverrides(key);
const ids = overrides.map((override) => override.userId);
const rows = ids.length === 0 ? [] : await decryptUserRows(await db.select({ id: users.id, name: users.name, email: users.email }).from(users).where(inArray(users.id, ids)));
const byId = new Map(rows.map((row) => [row.id, row]));
return NextResponse.json({
users: overrides.map((override) => ({
userId: override.userId,
name: byId.get(override.userId)?.name ?? null,
email: byId.get(override.userId)?.email ?? null,
enabled: override.enabled,
updatedAt: override.updatedAt,
})),
});
} catch (error) {
loggers.api.error('Error listing feature flag users', error instanceof Error ? error : undefined);
return NextResponse.json({ error: 'Failed to list people' }, { status: 500 });
}
});
Loading