refactor: remove the billing tier model (P0.1)

The community edition has no monetization (ADR-0001). Remove the tier
model (packages/shared/src/tiers.ts), the requireTier middleware and every
tier gate, GET/PATCH /api/tier and the trial start, and the Stripe
integration, which depends on the tier model.

Personal features a tier used to limit are open to everyone: unlimited
workspaces and connectors, every embedding provider including LiteLLM,
per-workspace costs, Approvals. The workspace session cap is one constant
(100). Team and enterprise surfaces are hidden instead of unlocked (team
dock zone, Settings Team/Enterprise/Plan tabs, workspace Team tab);
cloud sync reports unavailable, as it did for free users.

The sidecar ignores the tier keys in config.json but does not delete them:
both editions may still share ~/.waggle.

Web billing UI is deleted: plan cards, upgrade and trial modals, payment
success route, the KVARK sales block, tier 403 handling.
This commit is contained in:
shumeiko.it
2026-10-15 19:31:50 +02:00
parent 369d8269c1
commit fe2eb0f648
117 changed files with 342 additions and 6424 deletions

View File

@@ -11,18 +11,16 @@
* `{ kind:'none', fallback:true }` so the frontend falls back to Tier 0.
*/
import type { InterpretResult, ResolvedAction, Tier } from '@waggle/shared';
import type { InterpretResult, ResolvedAction } from '@waggle/shared';
import {
buildActionCatalog,
validateAndBuildAction,
checkTier,
type RegistryContext,
} from './command-registry.js';
export interface InterpretDeps {
text: string;
workspaceId?: string;
currentTier: Tier;
workspaces: ReadonlyArray<{ id: string; name: string }>;
/** The workspace "now" block (awareness + recent sessions + pending). */
memoryContext: string;
@@ -93,21 +91,6 @@ function buildValidStep(
return validateAndBuildAction(actionId, params, ctx);
}
/** Apply the tier gate to a resolved single action. */
function finalizeAction(action: ResolvedAction, currentTier: Tier): InterpretResult {
const tier = checkTier(action.id, currentTier);
if (tier.gated && tier.requiredTier) {
return {
kind: 'tier_gated',
capability: action.label,
requiredTier: tier.requiredTier,
actualTier: currentTier,
message: `${action.label} requires the ${tier.requiredTier} tier.`,
};
}
return { kind: 'action', action };
}
export async function interpretCommand(deps: InterpretDeps): Promise<InterpretResult> {
const ctx: RegistryContext = { workspaceId: deps.workspaceId, workspaces: deps.workspaces };
@@ -136,7 +119,7 @@ export async function interpretCommand(deps: InterpretDeps): Promise<InterpretRe
if (!action) {
return { kind: 'none', fallback: true, message: "I couldn't map that to an action I can run." };
}
return finalizeAction(action, deps.currentTier);
return { kind: 'action', action };
}
case 'plan': {
@@ -144,7 +127,7 @@ export async function interpretCommand(deps: InterpretDeps): Promise<InterpretRe
// a true multi-step plan downgrades to clarify (fast-follow executes it).
const rawSteps = Array.isArray(parsed.steps) ? parsed.steps : [];
const steps = rawSteps.map((s) => buildValidStep(s, ctx)).filter((s): s is ResolvedAction => s !== null);
if (steps.length === 1) return finalizeAction(steps[0], deps.currentTier);
if (steps.length === 1) return { kind: 'action', action: steps[0] };
if (steps.length > 1) {
const labels = steps.map((s) => s.label).join(' → ');
return {

View File

@@ -4,7 +4,7 @@
* The core safety property: the LLM resolver returns only an action `id` +
* `params`. THIS module — never the model — maps the id onto an executable
* shape (a navigation target or a server-derived endpoint), validates params,
* and stamps `sideEffect` / `riskLevel` / `requiredTier`. An unknown id, or
* and stamps `sideEffect` / `riskLevel`. An unknown id, or
* params that fail validation, resolve to `null` (→ the caller returns `none`).
*
* No new execution layer: navigation reuses the CommandResult `onNavigate`
@@ -15,9 +15,6 @@
import {
MCP_CATALOG,
assertTierCapability,
TierError,
type Tier,
type RiskLevel,
type ResolvedAction,
} from '@waggle/shared';
@@ -88,7 +85,6 @@ interface ActionDescriptor {
params: Record<string, ParamSpec>;
sideEffect: boolean;
riskLevel: RiskLevel;
requiredTier?: Tier;
/** Build the executable shape, or return null when params are invalid. */
build: (
params: Record<string, unknown>,
@@ -219,32 +215,14 @@ export function validateAndBuildAction(
};
}
/**
* Tier gate for a resolved action, reusing the canonical `assertTierCapability`.
* Returns `{ gated: true, requiredTier }` when the current tier is below the
* action's `requiredTier`.
*/
export function checkTier(actionId: string, currentTier: Tier): { gated: boolean; requiredTier?: Tier } {
const descriptor = BY_ID.get(actionId);
if (!descriptor?.requiredTier) return { gated: false };
try {
assertTierCapability(currentTier, descriptor.requiredTier);
return { gated: false };
} catch (e) {
if (e instanceof TierError) return { gated: true, requiredTier: descriptor.requiredTier };
throw e;
}
}
/** Render the registry + nav/MCP catalogs as the system-prompt action catalog. */
export function buildActionCatalog(): string {
const actions = ACTION_REGISTRY.map((d) => {
const params = Object.entries(d.params)
.map(([k, s]) => `${k}${s.required ? '' : '?'}: ${s.description}${s.enum ? ` (one of: ${s.enum.join(', ')})` : ''}`)
.join('; ');
const tier = d.requiredTier ? ` [requires ${d.requiredTier}]` : '';
const eff = d.sideEffect ? ' [side-effect → approval]' : '';
return `- ${d.id}${tier}${eff}: ${d.description}\n params: ${params || '(none)'}`;
return `- ${d.id}${eff}: ${d.description}\n params: ${params || '(none)'}`;
}).join('\n');
const navList = NAV_TARGETS.map((t) => `- ${t.id} (${t.label}) — ${t.hints}`).join('\n');

View File

@@ -69,8 +69,7 @@ import {
} from '@waggle/agent';
import { PluginRuntimeManager, getStarterSkillsDir, validatePluginManifest } from '@waggle/sdk';
import { MarketplaceDB, MarketplaceSync, seedMcpServers, seedNewSources } from '@waggle/marketplace';
import { parseTier, type RiskLevel } from '@waggle/shared';
import { readTierFromDataDir } from '../middleware/assert-tier.js';
import type { RiskLevel } from '@waggle/shared';
import { runConnectorFetch } from './connector-harvest.js';
import { writeAutoSyncSummaryFrame } from './harvest-autosync-frame.js';
import { runLoopTick } from './loop-executor.js';
@@ -163,7 +162,6 @@ import { waggleSignalRoutes } from './routes/waggle-signals.js';
import { providerRoutes } from './routes/providers.js';
import { profileRoutes } from './routes/profile.js';
import { telemetryRoutes } from './routes/telemetry.js';
import { stripeRoutes } from '../stripe/index.js';
import { agentGroupRoutes } from './routes/agent-groups.js';
import { localJobRoutes } from './routes/jobs.js';
import { agentEntityRoutes } from './routes/agents.js';
@@ -196,8 +194,7 @@ import {
type ProactiveMessage,
} from './proactive-handlers.js';
import { generateMonthlyAssessment, saveAssessmentToMind } from './monthly-assessment.js';
import { WorkspaceSessionManager } from './workspace-sessions.js';
import { maxWorkspaceSessionsForTier } from './tier-session-cap.js';
import { MAX_WORKSPACE_SESSIONS, WorkspaceSessionManager } from './workspace-sessions.js';
import { EventEmitter } from 'node:events';
import { LocalJobStore } from './job-store.js';
import { AgentRunRegistry } from './agent-run-registry.js';
@@ -213,8 +210,6 @@ export interface LocalConfig {
instanceId?: string;
/** Governed CLI execution — allowlist of program names the agent may run. */
cli?: { allowlist?: string[] };
/** Active subscription tier, when known (drives session/feature caps). */
tier?: string;
/** True only when startService owns the LiteLLM child lifecycle. */
manageLiteLLM?: boolean;
/** Stable child-process port, retained even while requests use a fallback proxy. */
@@ -495,9 +490,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
&& rawDesktopBootstrapToken.length <= 200
? rawDesktopBootstrapToken
: null;
const resolvedTier = parseTier(String(fullConfig.tier ?? '')) ?? readTierFromDataDir(fullConfig.dataDir);
fullConfig.tier = resolvedTier;
const server = Fastify({ logger: false });
const localJobStore = new LocalJobStore();
server.decorate('localJobStore', localJobStore);
@@ -1289,9 +1281,8 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
// ── Workspace Session Manager ────────────────────────────────────
// Manages concurrent workspace sessions with independent minds, orchestrators,
// and tools. Cap is tied to the active tier at startup and when the tier changes.
const sessionManager = new WorkspaceSessionManager(3);
sessionManager.setMaxSessions(maxWorkspaceSessionsForTier(resolvedTier));
// and tools.
const sessionManager = new WorkspaceSessionManager(MAX_WORKSPACE_SESSIONS);
server.decorate('sessionManager', sessionManager);
/**
@@ -2893,7 +2884,6 @@ Return ONLY the improved system prompt text. No commentary, no markdown fences,
await server.register(telemetryRoutes);
await server.register(agentGroupRoutes);
await server.register(localJobRoutes);
await server.register(stripeRoutes);
await server.register(harvestRoutes);
await server.register(wikiRoutes);
await server.register(identityRoutes);

View File

@@ -40,10 +40,6 @@ import { assertSafeSegment, authHeaders, clampStr, clampStrArray } from './valid
* spawn's {workspaceId, sessionId} in an in-process map keyed by agent id, and
* liveStatus/pause act only on that recorded session. Entries are lost on
* restart (the stored status then applies) — acceptable for one-shot C23 runs.
*
* Tier gating: agent creation is deliberately UNGATED — CLAUDE.md §1 moat
* strategy: "Agents are free (they generate memory)", matching the executor
* (`POST /api/fleet/spawn` is free for all tiers).
*/
const AGENT_TYPES: readonly AgentType[] = ['personal', 'workspace', 'team', 'autonomous'];
@@ -187,9 +183,7 @@ export const agentEntityRoutes: FastifyPluginAsync = async (server) => {
return { agents, count: agents.length };
});
// POST /api/agents — create. NOT tier-gated: CLAUDE.md §1 moat strategy says
// "Agents are free (they generate memory)" and the executor (fleet spawn) is
// free for all tiers — a tier gate here would be an incoherent surface.
// POST /api/agents — create.
// Blueprint hard gate: goal, model, memoryScopes and autonomyLevel are
// required so the stored record is the full effective surface ("no hidden
// tool/memory access").

View File

@@ -34,7 +34,6 @@ import { loadSkills } from '@waggle/agent';
import { buildWorkspaceNowBlock, formatWorkspaceNowPrompt } from './workspace-context.js';
import { searchSessions } from './session-utils.js';
import { interpretCommand } from '../command-interpret.js';
import { readTierFromRequest } from '../../middleware/assert-tier.js';
/**
* Memoized `loadSkills()` — the federated `/search` hot path runs per keystroke,
@@ -342,7 +341,6 @@ export const commandRoutes: FastifyPluginAsync = async (server) => {
const result = await interpretCommand({
text,
workspaceId,
currentTier: readTierFromRequest(request),
workspaces,
memoryContext,
llm,

View File

@@ -1,30 +1,8 @@
import { existsSync, readFileSync } from 'fs';
import { join } from 'path';
import type { FastifyInstance } from 'fastify';
import type { ConnectorHealth } from '@waggle/shared';
import { getCapabilities, parseTier, type Tier } from '@waggle/shared';
import type { RecordAuditInput } from '@waggle/core';
import { JiraConnector, SalesforceConnector } from '@waggle/agent';
/**
* Tier cap for connecting connectors. All current tiers (Solo + Team) have an
* unlimited connectorLimit (-1); the gate is retained for any future finite cap.
* Re-connecting an already-connected connector (token refresh) does NOT
* count against the cap. Returns the 403 payload data if the cap is exceeded,
* else null. Pure (no IO) so it is unit-testable.
*/
export function connectorCapExceeded(
tier: Tier,
connectedIds: string[],
id: string,
): { limit: number; current: number } | null {
const limit = getCapabilities(tier).connectorLimit;
if (limit <= 0) return null; // unlimited
if (connectedIds.includes(id)) return null; // already connected — token refresh
if (connectedIds.length >= limit) return { limit, current: connectedIds.length };
return null;
}
/** Vault sub-key holding the C16 manual-sync stamp. Matches the
* `connector:{id}:*` prefix so disconnect/revoke auto-clean it. */
const lastSyncKey = (id: string) => `connector:${id}:lastSync`;
@@ -171,32 +149,6 @@ export async function connectorRoutes(fastify: FastifyInstance) {
}
}
// Tier cap — connectors are unlimited on all current tiers (Solo + Team);
// gate retained for any future finite cap. Count REAL credentialed
// connections (getDefinitions status==='connected' excludes the always-on
// mock channels). Marker `error:'TIER_INSUFFICIENT'` so the adapter's tier
// event + the install store's tier classification light up. Fail-open if the
// tier read throws (matches the workspace-limit gate).
try {
const configPath = join(fastify.localConfig.dataDir, 'config.json');
const tierRaw = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')).tier : '';
const tier = parseTier(String(tierRaw ?? '')) ?? 'FREE';
const connectedIds = registry
? registry.getDefinitions().filter(d => d.status === 'connected').map(d => d.id)
: [];
const cap = connectorCapExceeded(tier, connectedIds, id);
if (cap) {
return reply.code(403).send({
error: 'TIER_INSUFFICIENT',
required: 'TEAMS',
actual: tier,
message: `Connector limit reached for ${tier} (${cap.limit} max). Upgrade to connect more.`,
limit: cap.limit,
current: cap.current,
});
}
} catch { /* tier read failed — allow the connect (fail-open) */ }
const connector = registry?.get(id);
const authType = connector?.authType ?? 'bearer';

View File

@@ -12,7 +12,6 @@
*/
import type { FastifyPluginAsync } from 'fastify';
import { requireTier } from '../../middleware/assert-tier.js';
// ── Types (inline to avoid cross-package resolution issues in worktrees) ──
@@ -95,9 +94,8 @@ export const costRoutes: FastifyPluginAsync = async (server) => {
}
// GET /api/cost/summary — total tokens, estimated cost, daily breakdown.
// Intentionally FREE for all tiers (P22): it powers the personal Telemetry
// dev-mode cost/budget view. The TEAM cost-visibility surface is the separate
// /api/cost/by-workspace + /api/costs alias (both requireTier('TEAMS')).
// Powers the Telemetry cost/budget view; /api/cost/by-workspace adds the
// per-workspace breakdown and /api/costs is an alias of this route.
server.get<{
Querystring: { days?: string };
}>('/api/cost/summary', async (request) => {
@@ -220,7 +218,7 @@ export const costRoutes: FastifyPluginAsync = async (server) => {
});
// GET /api/cost/by-workspace — per-workspace token usage breakdown
server.get('/api/cost/by-workspace', { preHandler: [requireTier('TEAMS')] }, async () => {
server.get('/api/cost/by-workspace', async () => {
const entries = getEntries();
const workspaces = server.workspaceManager.list();
@@ -281,8 +279,7 @@ export const costRoutes: FastifyPluginAsync = async (server) => {
// D2: Alias /api/costs → /api/cost/summary for API discoverability
// Use internal routing instead of 302 redirect so clients get a direct 200 response
// Cost visibility is a Team feature — gated identically to /api/cost/by-workspace.
server.get('/api/costs', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
server.get('/api/costs', async (request, reply) => {
const days = (request.query as Record<string, string>)?.days;
const url = days ? `/api/cost/summary?days=${days}` : '/api/cost/summary';
const response = await server.inject({ method: 'GET', url, headers: request.headers });

View File

@@ -4,7 +4,8 @@
* The read side (`GET /api/embedding/status`) and reprobe
* (`POST /api/embedding/reprobe`) live inline in local/index.ts, where they have
* closure access to the boot-time embedding config. This plugin owns
* `POST /api/embedding/provider`: validate → tier-gate → persist the choice.
* `POST /api/embedding/provider`: validate → persist the choice. Every provider is
* selectable (ADR-0001).
*
* Hot-swap note: the live embedder is created once at boot and threaded BY
* REFERENCE into the Orchestrator, mind search, and the vector-backfill path.
@@ -19,8 +20,7 @@ import fs from 'node:fs';
import path from 'node:path';
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
import { z } from 'zod';
import { WaggleConfig, getMinimumTierForProvider, type EmbeddingProviderType } from '@waggle/core';
import { TIER_CAPABILITIES, parseTier, getEffectiveTier, type Tier } from '@waggle/shared';
import { WaggleConfig } from '@waggle/core';
import { validateBody } from '../../validate-body.js';
/**
@@ -35,19 +35,6 @@ const setProviderSchema = z.object({
provider: z.enum(SELECTABLE_PROVIDERS),
});
/** Effective tier from config.json (mirrors settings.ts readTierConfig + trial resolution). */
function readEffectiveTier(dataDir: string): Tier {
try {
const configPath = path.join(dataDir, 'config.json');
if (fs.existsSync(configPath)) {
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
const parsed = parseTier(String(raw.tier ?? '')) ?? 'FREE';
return getEffectiveTier(parsed, raw.trialStartedAt ?? null);
}
} catch { /* fall through to FREE */ }
return 'FREE';
}
/** True when EMBEDDING_PROVIDER env var is set — it wins over the persisted choice. */
function envOverrideProvider(): string | null {
const v = process.env.EMBEDDING_PROVIDER?.trim();
@@ -103,22 +90,6 @@ export const embeddingRoutes: FastifyPluginAsync = async (server) => {
});
}
// Tier gate — 'auto' is always allowed; an explicit provider must be in
// the tier's allowed set (TIER_CAPABILITIES.embeddingProviders).
if (provider !== 'auto') {
const tier = readEffectiveTier(server.localConfig.dataDir);
const allowed = TIER_CAPABILITIES[tier].embeddingProviders as readonly string[];
if (!allowed.includes(provider)) {
const requiredTier = getMinimumTierForProvider(provider as EmbeddingProviderType);
return reply.status(403).send({
error: 'TIER_REQUIRED',
message: `The "${provider}" embedding provider requires the ${requiredTier} tier or higher (current: ${tier}).`,
requiredTier,
currentTier: tier,
});
}
}
// Persist (setEmbeddingProvider does not save on its own).
const config = new WaggleConfig(server.localConfig.dataDir);
config.setEmbeddingProvider(provider);

View File

@@ -4,13 +4,11 @@
*/
import type { FastifyInstance } from 'fastify';
import { parseTier, type GoalAncestry } from '@waggle/shared';
import { requireTier } from '../../middleware/assert-tier.js';
import type { GoalAncestry } from '@waggle/shared';
import { runAgentLoop, isEnabled, detectTaskShape, listPersonas } from '@waggle/agent';
import { emitWaggleSignal } from './waggle-signals.js';
import { persistMessage } from './chat-persistence.js';
import { createLogger } from '../logger.js';
import { maxWorkspaceSessionsForTier } from '../tier-session-cap.js';
import { spawnIsolatedFleetRun } from '../fleet-run-executor.js';
import { resolveUsableModel } from '../model-availability.js';
@@ -58,15 +56,12 @@ export async function fleetRoutes(fastify: FastifyInstance) {
};
});
// Tier-based maxSessions: FREE=10, TEAMS=25, ENTERPRISE/TRIAL=100
const tierRaw = fastify.localConfig?.tier ?? '';
const tier = parseTier(String(tierRaw)) ?? 'FREE';
const maxSessions = maxWorkspaceSessionsForTier(tier);
const maxSessions = sessionManager.getMaxSessions();
return { sessions, count: sessions.length, maxSessions };
});
// POST /api/fleet/spawn — spawn a new agent session (free for all tiers — agents generate memory)
// POST /api/fleet/spawn — spawn a new agent session
//
// FR #15 Phase A: properly create the workspace session via getOrCreate so
// Room/Mission Control register it as live, and emit an `agent:spawned`

View File

@@ -18,7 +18,6 @@ import { validateSkillMd } from '@waggle/sdk';
import { safeFetch, assertUrlAllowed, scanForInjection } from '@waggle/agent';
import { getKvarkConfig } from '../../kvark/kvark-config.js';
import { emitNotification } from './notifications.js';
import { requireTier } from '../../middleware/assert-tier.js';
import { loadMcpConfig, removeMcpServerEntry } from '../mcp-config.js';
import { enqueueHeldAction } from '../held-action-executor.js';
import { isMarketplaceBackgroundSyncDisabled } from '../marketplace-background-sync.js';
@@ -187,7 +186,7 @@ export async function marketplaceRoutes(fastify: FastifyInstance) {
// Returns enterprise packs that require KVARK. Only populated when
// KVARK credentials are configured in the vault.
fastify.get('/api/marketplace/enterprise-packs', { preHandler: [requireTier('ENTERPRISE')] }, async (request, reply) => {
fastify.get('/api/marketplace/enterprise-packs', async (request, reply) => {
const vault = fastify.vault;
const kvarkConfigured = vault ? getKvarkConfig(vault) !== null : false;

View File

@@ -1,15 +1,12 @@
import fs from 'node:fs';
import path from 'node:path';
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
import type { FastifyPluginAsync } from 'fastify';
import { z } from 'zod';
import { WaggleConfig } from '@waggle/core';
import { type Tier, TIERS, TIER_CAPABILITIES, parseTier, getCapabilities, getEffectiveTier, trialDaysRemaining } from '@waggle/shared';
import type { AutonomyLevel } from '@waggle/agent';
import { requireTier } from '../../middleware/assert-tier.js';
import { validateBody } from '../../validate-body.js';
import { probeProviderKey, validateKeyFormat } from '../llm-key-probe.js';
import { resolveExplicitRoutableModel, resolveUsableModel } from '../model-availability.js';
import { maxWorkspaceSessionsForTier } from '../tier-session-cap.js';
import { applyProviderKeyToEnv } from '../provider-env.js';
import { refreshManagedLiteLLM, type LiteLLMRefreshResult } from '../litellm-runtime-config.js';
@@ -44,11 +41,6 @@ function maskApiKey(key: string): string {
return key.slice(0, 7) + '...' + key.slice(-4);
}
function applyRuntimeTier(server: FastifyInstance, tier: Tier): void {
server.localConfig.tier = tier;
server.sessionManager?.setMaxSessions(maxWorkspaceSessionsForTier(tier));
}
export const settingsRoutes: FastifyPluginAsync = async (server) => {
// GET /api/settings — read config (keys from vault, metadata from vault+config)
server.get('/api/settings', async () => {
@@ -445,162 +437,23 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
return updated;
});
// ── Tier detection ───────────────────────────────────────────────────
// Tier is read from config.json → tier field (defaults to FREE).
// Canonical values: TRIAL | FREE | TEAMS | ENTERPRISE (@waggle/shared
// tiers.ts). Legacy names (PRO/BASIC/lowercase) auto-migrate via parseTier().
// The Stripe webhook (packages/server/src/stripe/webhook.ts) writes this field.
function readTierConfig(dataDir: string): { tier: Tier; trialStartedAt: string | null } {
try {
const configPath = path.join(dataDir, 'config.json');
if (fs.existsSync(configPath)) {
const raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
const parsed = parseTier(String(raw.tier ?? ''));
if (parsed) return { tier: parsed, trialStartedAt: raw.trialStartedAt ?? null };
}
} catch { /* ignore */ }
return { tier: 'FREE', trialStartedAt: null };
}
// GET /api/tier — authoritative tier source for frontend
server.get('/api/tier', async () => {
const { tier: rawTier, trialStartedAt } = readTierConfig(server.localConfig.dataDir);
const tier = getEffectiveTier(rawTier, trialStartedAt);
const caps = getCapabilities(tier);
const daysRemaining = trialDaysRemaining(trialStartedAt);
// Usage counts for limit display
const workspaceCount = server.workspaceManager?.list().length ?? 0;
return {
tier,
rawTier,
trialStartedAt,
trialDaysRemaining: daysRemaining,
trialExpired: rawTier === 'TRIAL' && tier === 'FREE',
capabilities: caps,
teamsServerUrl: process.env.DATABASE_URL
? `http://127.0.0.1:${process.env.TEAMS_SERVER_PORT ?? '3101'}`
: null,
teamsServerAvailable: !!process.env.DATABASE_URL,
usage: {
workspaceCount,
},
// Legacy shape — kept for backward compatibility with existing frontend
limits: {
maxWorkspaces: caps.workspaceLimit,
maxSessions: tier === 'FREE' ? 10 : 25,
maxMembers: caps.teamMembersLimit,
features: {
teams: caps.sharedWorkspaces,
marketplace: true,
budgetControls: caps.adminPanel,
kvark: tier === 'ENTERPRISE',
governance: tier === 'ENTERPRISE',
customModels: true,
},
},
};
});
// PATCH /api/tier — change tier (testing/dev — will be replaced by Stripe webhook)
server.patch<{
Body: { tier: string };
}>('/api/tier', async (request, reply) => {
// AV-3: this dev/test-only override must NOT be a production privilege-escalation
// path. Under the loopback-trust model any local page/extension could PATCH a paid
// tier for free (no payment, no auth). Fail closed — disabled unless explicitly
// enabled for dev/testing. Legit tier changes flow through Stripe (sync/webhook)
// and POST /api/tier/start-trial.
if (process.env.WAGGLE_ALLOW_TIER_OVERRIDE !== '1') {
return reply.status(403).send({ error: 'Tier override disabled', code: 'TIER_OVERRIDE_DISABLED' });
}
const { tier: tierRaw } = request.body ?? {};
const parsed = parseTier(String(tierRaw ?? ''));
if (!parsed) {
return reply.status(400).send({ error: `Invalid tier. Must be one of: ${TIERS.join(', ')}` });
}
const configPath = path.join(server.localConfig.dataDir, 'config.json');
let raw: Record<string, unknown> = {};
try {
if (fs.existsSync(configPath)) {
raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
}
} catch { /* fresh */ }
raw.tier = parsed;
fs.writeFileSync(configPath, JSON.stringify(raw, null, 2), 'utf-8');
applyRuntimeTier(server, parsed);
return { tier: parsed, capabilities: getCapabilities(parsed), updated: true };
});
// POST /api/tier/start-trial — atomic trial start.
//
// Sets `tier='TRIAL'` + `trialStartedAt=now` in a single write. Idempotent
// by design: if `trialStartedAt` is already set, returns 409 with the
// current tier state — a user gets exactly one 15-day trial. The previous
// path (client-side `adapter.updateSettings({ tier: 'TRIAL', trialStartedAt })`)
// was doubly broken: `updateSettings` didn't exist on the adapter, and
// `PATCH /api/tier` ignores `trialStartedAt`, so trials silently never
// started. See UpgradeModal `onStartTrial` and OnboardingWizard completion.
server.post('/api/tier/start-trial', async (_request, reply) => {
const configPath = path.join(server.localConfig.dataDir, 'config.json');
let raw: Record<string, unknown> = {};
try {
if (fs.existsSync(configPath)) {
raw = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
}
} catch { /* fresh */ }
if (typeof raw.trialStartedAt === 'string' && raw.trialStartedAt.length > 0) {
const existingTier = parseTier(String(raw.tier ?? '')) ?? 'FREE';
const effective = getEffectiveTier(existingTier, raw.trialStartedAt);
return reply.status(409).send({
error: 'TRIAL_ALREADY_STARTED',
message: 'A trial has already been started for this installation.',
tier: effective,
rawTier: existingTier,
trialStartedAt: raw.trialStartedAt,
trialDaysRemaining: trialDaysRemaining(raw.trialStartedAt),
trialExpired: existingTier === 'TRIAL' && effective === 'FREE',
});
}
const now = new Date().toISOString();
raw.tier = 'TRIAL';
raw.trialStartedAt = now;
fs.writeFileSync(configPath, JSON.stringify(raw, null, 2), 'utf-8');
applyRuntimeTier(server, 'TRIAL');
return {
tier: 'TRIAL' as Tier,
rawTier: 'TRIAL' as Tier,
trialStartedAt: now,
trialDaysRemaining: trialDaysRemaining(now),
trialExpired: false,
capabilities: getCapabilities('TRIAL'),
};
});
// ── Cloud Sync ────────────────────────────────────────────────────
server.get('/api/cloud-sync', async () => {
const { tier } = readTierConfig(server.localConfig.dataDir);
const caps = getCapabilities(tier);
const configPath = path.join(server.localConfig.dataDir, 'config.json');
let raw: Record<string, unknown> = {};
try { if (fs.existsSync(configPath)) raw = JSON.parse(fs.readFileSync(configPath, 'utf-8')); } catch { /* */ }
return {
available: caps.cloudSync,
// Cloud sync runs through the team server, which the community edition
// does not ship (ADR-0003).
available: false,
enabled: raw.cloudSyncEnabled === true,
tier,
teamServerUrl: (raw.teamServer as Record<string, unknown>)?.url ?? null,
connected: !!((raw.teamServer as Record<string, unknown>)?.token),
};
});
server.post<{ Body: { enabled: boolean } }>('/api/cloud-sync/toggle', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
server.post<{ Body: { enabled: boolean } }>('/api/cloud-sync/toggle', async (request, reply) => {
const { enabled } = request.body ?? {};
if (typeof enabled !== 'boolean') return reply.code(400).send({ error: 'enabled must be a boolean' });
const configPath = path.join(server.localConfig.dataDir, 'config.json');
@@ -613,7 +466,7 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
// ── Admin Overview ────────────────────────────────────────────────
server.get('/api/admin/overview', { preHandler: [requireTier('TEAMS')] }, async () => {
server.get('/api/admin/overview', async () => {
const workspaces = server.workspaceManager?.list() ?? [];
return {
usage: { totalInputTokens: 0, totalOutputTokens: 0 },
@@ -635,7 +488,7 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
// GET /api/admin/audit-export — download audit log as JSON or CSV
server.get<{
Querystring: { from?: string; to?: string; format?: 'json' | 'csv' };
}>('/api/admin/audit-export', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
}>('/api/admin/audit-export', async (request, reply) => {
const { from, to, format = 'json' } = request.query;
const auditStore = server.auditStore;
if (!auditStore?.getAll) {

View File

@@ -15,7 +15,6 @@ import { WaggleConfig } from '@waggle/core';
import { allowLocalFromEnv, safeFetch } from '@waggle/agent';
import { emitNotification } from './notifications.js';
import { emitAuditEvent } from './events.js';
import { requireTier } from '../../middleware/assert-tier.js';
// ── Local team DB ────────────────────────────────────────────────────
@@ -140,7 +139,7 @@ export async function teamRoutes(fastify: FastifyInstance) {
* POST /api/team/connect
* Connect to a team server by validating the token against the server's health endpoint.
*/
fastify.post('/api/team/connect', { preHandler: [requireTier('TEAMS')] }, async (request, reply) => {
fastify.post('/api/team/connect', async (request, reply) => {
const { serverUrl, token } = request.body as { serverUrl: string; token: string };
if (!serverUrl || !token) {
@@ -454,7 +453,7 @@ export async function teamRoutes(fastify: FastifyInstance) {
}
// GET /api/team/governance/permissions — get effective permissions for current user
fastify.get('/api/team/governance/permissions', { preHandler: [requireTier('ENTERPRISE')] }, async (request, reply) => {
fastify.get('/api/team/governance/permissions', async (request, reply) => {
const { workspaceId } = request.query as { workspaceId?: string };
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();

View File

@@ -5,7 +5,6 @@ import Database from 'better-sqlite3';
import type { FastifyPluginAsync } from 'fastify';
import { z } from 'zod';
import { MindDB, WaggleConfig, createFileStore, reconcileFtsIndex } from '@waggle/core';
import { parseTier, getCapabilities } from '@waggle/shared';
import { assertSafeSegment } from './validate.js';
import { validateBody } from '../../validate-body.js';
import { getBoundTeamServer } from '../team-server-binding.js';
@@ -331,25 +330,6 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
}>('/api/workspaces', { preHandler: validateBody(createWorkspaceSchema) }, async (request, reply) => {
const { name, group, icon, model, personaId, directory, tone, teamId, teamServerUrl, teamRole, teamUserId, storageType, storagePath, storageConfig } = request.body;
// Tier limit enforcement: check workspaceLimit from @waggle/shared
try {
const configPath = path.join(server.localConfig.dataDir, 'config.json');
const tierRaw = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, 'utf-8')).tier : '';
const tier = parseTier(String(tierRaw ?? '')) ?? 'FREE';
const caps = getCapabilities(tier);
if (caps.workspaceLimit > 0) {
const currentCount = server.workspaceManager.list().length;
if (currentCount >= caps.workspaceLimit) {
return reply.status(403).send({
error: `Workspace limit reached for ${tier} tier (${caps.workspaceLimit} max). Upgrade to create more.`,
tier,
limit: caps.workspaceLimit,
current: currentCount,
});
}
}
} catch { /* tier check failed — allow creation */ }
// BUG-R3-03: Validate model ID if provided
if (model && !isValidModelId(model)) {
return reply.status(400).send({

View File

@@ -237,25 +237,12 @@ export class SessionTimeoutTracker {
/**
* Routes exempt from bearer token authentication.
*
* `/api/stripe/webhook` is a tokenless POST from Stripe's servers — it can never
* carry our per-process session bearer, so in a hosted (0.0.0.0) deploy it would
* 401 before the handler and subscription-lifecycle events
* (customer.subscription.deleted/updated) would never process — cancelled subs
* would never downgrade to FREE. It is independently authenticated by Stripe
* *signature verification* inside the handler (stripe.webhooks.constructEvent
* rejects any body not signed with STRIPE_WEBHOOK_SECRET before the handler
* trusts it), so exempting it from the bearer gate does not widen the trust
* boundary. Desktop (loopback) mode is unaffected — Stripe can't reach a
* loopback bind. The path string matches the route registered in
* stripe/webhook.ts (`POST /api/stripe/webhook`, no prefix).
*/
const AUTH_EXEMPT_PATHS = [
'/health',
'/api/auth/session-token',
'/api/browser-ext/session-token',
'/api/browser-ext/pair',
'/api/stripe/webhook',
];
/**
@@ -738,8 +725,8 @@ async function securityMiddlewarePlugin(
// ── Bearer token authentication (SEC-011 + D1) ──
// D1: localhost is NO LONGER trusted by default. Waggle is a desktop app that
// coexists with browsers/extensions/other local apps, so "any loopback caller is
// trusted" let any of them drive the authenticated API (e.g. the PATCH /api/tier
// free upgrade). The Tauri webview obtains the token from the auth-exempt,
// trusted" let any of them drive the authenticated API (e.g. change settings or
// provider keys). The Tauri webview obtains the token from the auth-exempt,
// same-origin-gated /api/auth/session-token bootstrap and sends it as a Bearer.
// Set WAGGLE_TRUST_LOCALHOST=1 to restore legacy loopback trust (emergency escape).
if (sessionToken) {

View File

@@ -10,7 +10,6 @@ import type { LlmHealthStatus } from './index.js';
import { startLiteLLM, stopLiteLLM, type LiteLLMStatus } from './lifecycle.js';
import { createLogger } from './logger.js';
import { resolveBindHost } from './net-config.js';
import { readTierFromDataDir } from '../middleware/assert-tier.js';
import { listOllamaChatModelIds } from './model-availability.js';
import {
readEraseMarker,
@@ -245,9 +244,9 @@ export async function startService(options?: ServiceOptions): Promise<ServiceRes
}
// D11: ONE startup line answering "which state am I running against?" —
// resolved dataDir + effective tier. Logged after wipe/migration so it
// reflects the directory the server will actually serve.
log.info(`Data dir: ${dataDir} · tier: ${readTierFromDataDir(dataDir)}`);
// the resolved dataDir. Logged after wipe/migration so it reflects the
// directory the server will actually serve.
log.info(`Data dir: ${dataDir}`);
// 3. Ensure personal.mind exists
const personalPath = path.join(dataDir, 'personal.mind');

View File

@@ -1,7 +0,0 @@
import type { Tier } from '@waggle/shared';
export function maxWorkspaceSessionsForTier(tier: Tier): number {
if (tier === 'FREE') return 10;
if (tier === 'TEAMS') return 25;
return 100;
}

View File

@@ -8,12 +8,15 @@
* state (the "Option Y" fix from docs/plans/phase-a-the-room.md §9).
*
* Max concurrent sessions configurable (default: 3) to prevent resource exhaustion.
* Tier-gate via setMaxSessions() at startup once the user's subscription is known.
* The sidecar starts the manager with MAX_WORKSPACE_SESSIONS.
*/
import type { MindDB } from '@waggle/core';
import type { ToolDefinition, Orchestrator } from '@waggle/agent';
/** Concurrent workspace sessions the sidecar allows. */
export const MAX_WORKSPACE_SESSIONS = 100;
export interface WorkspaceSession {
workspaceId: string;
mind: MindDB;