refactor(server): move the team runtime into a postponed package (P1.1)
Team mode stays in the repository but is not built or shipped (ADR-0003). - The team server (index.ts, config, db, daemons, plugins, proactive, routes, scheduler, services, ws, drizzle migrations) and its tests move from @waggle/server to packages/team-server (@waggle/team-server, private). It keeps its own copies of the logger and the agent-group executor, so it does not import @waggle/server. @clerk/fastify, bullmq, ioredis, postgres, drizzle-orm, drizzle-kit, cron-parser and @waggle/waggle-dance leave @waggle/server; the launcher drops the same team-only dependencies. - build:packages no longer builds waggle-dance or the worker: nothing in the community edition imports them, and the worker's project reference would otherwise build the team server. The worker now imports from team-server; the team Dockerfile builds both explicitly. - The sidecar no longer starts the team server when DATABASE_URL is set, and loses the team routes (/api/team/*, /api/teams), the WaggleDance routes and bridge (/api/waggle-dance/*), the Team server binding and egress guard, the WebSocket team client, the TeamSync cache and pushes, team audit forwarding, team workspace registration and the team capability-policy lookup in chat. The in-process room signal bus stays: agent groups, fleet runs and external tool runs use it. middleware/audit.ts was dead and is deleted. - @waggle/core loses TeamSync and the teamServer part of WaggleConfig. A teamServer key in config.json is ignored and kept on save, as P0.1 does for the tier keys. Workspaces lose teamServerUrl and teamUserId; teamId and teamRole stay because workspaces from a shared data directory still carry them and the viewer write guards read them. POST /api/workspaces ignores team fields. - The sidecar bundle no longer marks the team packages as external. The agent still references the TeamSync type in orchestrator.ts and pattern-write-back.ts; those files are being rewritten in P1.5 and drop it there. Logs UF-030 and UF-031 (team sync and team policy defects found while removing the code).
This commit is contained in:
@@ -10,10 +10,8 @@ import Fastify, { type FastifyInstance, type FastifyRequest } from 'fastify';
|
||||
import cors from '@fastify/cors';
|
||||
import fastifyStatic from '@fastify/static';
|
||||
import websocket from '@fastify/websocket';
|
||||
import { MindDB, MultiMind, WaggleDB, importLegacyMindData, workspaceDataScope, type LegacyMindSource, MultiMindCache, WorkspaceManager, WaggleConfig, createEmbeddingProvider, type EmbeddingProviderConfig, type EmbeddingProviderInstance, FrameStore, SessionStore, SuppressionStore, InstallAuditStore, CronStore, AwarenessLayer, VaultStore, SkillHashStore, HarvestSourceStore, ClaudeCodeAdapter, reconcileIndexes, TeamSync, TelemetryStore, TELEMETRY_EVENTS, ExecutionTraceStore, harvestSetHash, type WorkspaceConfig } from '@waggle/core';
|
||||
import { MindDB, MultiMind, WaggleDB, importLegacyMindData, workspaceDataScope, type LegacyMindSource, MultiMindCache, WorkspaceManager, WaggleConfig, createEmbeddingProvider, type EmbeddingProviderConfig, type EmbeddingProviderInstance, FrameStore, SessionStore, SuppressionStore, InstallAuditStore, CronStore, AwarenessLayer, VaultStore, SkillHashStore, HarvestSourceStore, ClaudeCodeAdapter, reconcileIndexes, TelemetryStore, TELEMETRY_EVENTS, ExecutionTraceStore, harvestSetHash } from '@waggle/core';
|
||||
import { corsOriginAllowed } from './cors-config.js';
|
||||
import { getBoundTeamServer } from './team-server-binding.js';
|
||||
import { fetchTeamServer } from './team-server-egress.js';
|
||||
import { getStorageProvider } from './storage/index.js';
|
||||
import { isLoopbackBind, resolveBindHost } from './net-config.js';
|
||||
import { isLocalRequest } from './origin-guard.js';
|
||||
@@ -82,7 +80,6 @@ import { embeddingRoutes, buildEmbeddingStatusPayload } from './routes/embedding
|
||||
import { sessionRoutes } from './routes/sessions.js';
|
||||
import { knowledgeRoutes } from './routes/knowledge.js';
|
||||
import { litellmRoutes } from './routes/litellm.js';
|
||||
import { waggleDanceRoutes } from './routes/waggle-dance.js';
|
||||
import { ingestRoutes, readFileRegistry } from './routes/ingest.js';
|
||||
import { mindRoutes } from './routes/mind.js';
|
||||
import { agentRoutes } from './routes/agent.js';
|
||||
@@ -92,12 +89,12 @@ import { skillsHygieneRoutes } from './routes/skills-hygiene.js';
|
||||
import { skillsAuditRoutes } from './routes/skills-audit.js';
|
||||
import { approvalRoutes } from './routes/approval.js';
|
||||
import { anthropicProxyRoutes } from './routes/anthropic-proxy.js';
|
||||
import { teamRoutes } from './routes/team.js';
|
||||
import { taskRoutes } from './routes/tasks.js';
|
||||
import { capabilitiesRoutes } from './routes/capabilities.js';
|
||||
import { toolsRoutes } from './routes/tools.js';
|
||||
import { externalToolRunRoutes } from './routes/external-tool-runs.js';
|
||||
import { routeProposalRoutes } from './routes/route-proposals.js';
|
||||
import { SignalBus } from './signal-bus.js';
|
||||
import { commandRoutes } from './routes/commands.js';
|
||||
import { commandRoutes as commandCenterRoutes } from './routes/command.js';
|
||||
import { homeRoutes } from './routes/home.js';
|
||||
@@ -129,7 +126,6 @@ import { costRoutes } from './routes/cost.js';
|
||||
import { backupRoutes } from './routes/backup.js';
|
||||
import { offlineRoutes } from './routes/offline.js';
|
||||
import { eventRoutes, closeAuditDb, cleanupAuditEvents, emitAuditEvent } from './routes/events.js';
|
||||
import { closeTeamsDb } from './routes/team.js';
|
||||
import { pinRoutes } from './routes/pins.js';
|
||||
import { documentRoutes } from './routes/documents.js';
|
||||
import { fileRoutes } from './routes/files.js';
|
||||
@@ -2003,13 +1999,12 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
await server.register(skillsAuditRoutes);
|
||||
await server.register(approvalRoutes);
|
||||
await server.register(anthropicProxyRoutes);
|
||||
await server.register(teamRoutes);
|
||||
await server.register(taskRoutes);
|
||||
await server.register(capabilitiesRoutes);
|
||||
await server.register(toolsRoutes);
|
||||
await server.register(externalToolRunRoutes);
|
||||
await server.register(routeProposalRoutes);
|
||||
await server.register(waggleDanceRoutes);
|
||||
server.decorate('signalBus', new SignalBus());
|
||||
await server.register(commandRoutes);
|
||||
// UX-Refactor Phase 1: Home Cockpit (S01) + Command Center (S00/S03) surfaces.
|
||||
// commandCenterRoutes registers the singular /api/command/* aliases (B4) — it
|
||||
@@ -2092,7 +2087,7 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
});
|
||||
server.decorate('channelManager', channelManager);
|
||||
// Auto-start enabled channels once the server is up; skip under test to
|
||||
// keep unit runs hermetic (mirrors the teams-server VITEST guard below).
|
||||
// keep unit runs hermetic.
|
||||
if (!process.env.VITEST && process.env.NODE_ENV !== 'test') {
|
||||
server.addHook('onReady', async () => {
|
||||
await channelManager.startEnabled();
|
||||
@@ -2347,7 +2342,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
workspaces: ['GET /api/workspaces', 'POST /api/workspaces', 'GET /api/workspaces/:id', 'PUT /api/workspaces/:id', 'DELETE /api/workspaces/:id', 'GET /api/workspaces/:id/cost', 'GET /api/workspaces/:id/context', 'GET /api/workspaces/:id/files', 'GET /api/workspaces/:id/storage', 'GET /api/workspaces/:id/storage/files', 'GET /api/workspaces/:id/storage/read', 'POST /api/workspaces/:id/storage/write', 'DELETE /api/workspaces/:id/storage/delete'],
|
||||
memory: ['GET /api/memory/search', 'GET /api/memory/frames', 'POST /api/memory/frames', 'DELETE /api/memory/frames/:id', 'GET /api/memory/stats', 'GET /api/memory/graph'],
|
||||
sessions: ['GET /api/workspaces/:workspaceId/sessions', 'POST /api/workspaces/:workspaceId/sessions', 'PATCH /api/sessions/:sessionId', 'DELETE /api/sessions/:sessionId', 'GET /api/sessions/:sessionId/summary'],
|
||||
teams: ['GET /api/teams', 'POST /api/teams', 'GET /api/teams/:id', 'PUT /api/teams/:id', 'DELETE /api/teams/:id', 'POST /api/teams/:id/members', 'PUT /api/teams/:id/members/:userId', 'DELETE /api/teams/:id/members/:userId', 'GET /api/teams/:id/activity'],
|
||||
events: ['GET /api/events', 'GET /api/events/stats', 'GET /api/events/stream'],
|
||||
settings: ['GET /api/settings', 'PUT /api/settings', 'PATCH /api/settings', 'POST /api/settings/test-key', 'POST /api/settings/probe-provider'],
|
||||
vault: ['GET /api/vault', 'POST /api/vault', 'DELETE /api/vault/:name'],
|
||||
@@ -2529,9 +2523,8 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
await memory.close();
|
||||
waggleDb.close();
|
||||
|
||||
// Close audit DB, teams DB, and telemetry
|
||||
// Close audit DB and telemetry
|
||||
closeAuditDb();
|
||||
closeTeamsDb();
|
||||
try { telemetry.close(); } catch { /* already closed */ }
|
||||
|
||||
// Close marketplace DB
|
||||
@@ -2566,36 +2559,5 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
return { done, cancel: () => { cancelled = true; } };
|
||||
})();
|
||||
|
||||
// ── Start Teams server if PostgreSQL is configured (TEAMS tier) ──
|
||||
// Skip in test environment to avoid port conflicts and addHook-after-listen errors
|
||||
if (process.env.DATABASE_URL && !process.env.VITEST && process.env.NODE_ENV !== 'test') {
|
||||
// DAY0V-03 / F-02: cloud-mode detected (DATABASE_URL set) — require CLERK_SECRET_KEY.
|
||||
// The Teams server registers wsGateway, which itself hard-fails in NODE_ENV=production
|
||||
// when the key is absent (see packages/server/src/ws/gateway.ts DAY0V-01 fix). We surface
|
||||
// the misconfiguration here too so the operator sees a single clear log line instead of
|
||||
// a buildServer rejection further down.
|
||||
if (!process.env.CLERK_SECRET_KEY) {
|
||||
log.error(
|
||||
'[teams-server] CLERK_SECRET_KEY missing while DATABASE_URL is set. Cloud/Teams ' +
|
||||
'deployment requires both. Skipping Teams server startup — set CLERK_SECRET_KEY ' +
|
||||
'and restart, or unset DATABASE_URL to run desktop-only.',
|
||||
);
|
||||
} else {
|
||||
const teamsPort = parseInt(process.env.TEAMS_SERVER_PORT ?? '3101', 10);
|
||||
import('../index.js').then(({ buildServer }) => {
|
||||
buildServer().then(teamsServer => {
|
||||
teamsServer.listen({ port: teamsPort, host: '127.0.0.1' }, (err) => {
|
||||
if (err) {
|
||||
log.info(`[teams-server] Failed to start: ${err.message}`);
|
||||
} else {
|
||||
log.info(`[teams-server] Running at http://127.0.0.1:${teamsPort}`);
|
||||
}
|
||||
});
|
||||
server.addHook('onClose', async () => { await teamsServer.close(); });
|
||||
}).catch(err => log.info(`[teams-server] Build failed: ${(err as Error).message}`));
|
||||
}).catch(() => { /* Teams server optional — non-blocking */ });
|
||||
}
|
||||
}
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
/**
|
||||
* chat-governance.ts — Direct governance permission lookup for the chat route.
|
||||
*
|
||||
* Replaces the HTTP loopback call to /api/team/governance/permissions
|
||||
* with a direct function call that accesses the same data source.
|
||||
*/
|
||||
|
||||
import { WaggleConfig } from '@waggle/core';
|
||||
import { fetchTeamServer } from '../team-server-egress.js';
|
||||
|
||||
/** Cached governance policies — same TTL as team.ts route cache (5 minutes) */
|
||||
const policyCache = new Map<string, { permissions: unknown; fetchedAt: number }>();
|
||||
const CACHE_TTL_MS = 5 * 60 * 1000;
|
||||
|
||||
export interface GovernancePolicies {
|
||||
blockedTools?: string[];
|
||||
allowedSources?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch governance permissions for the given workspace directly from the team server.
|
||||
* This replaces the HTTP self-call (`fetch('http://127.0.0.1:${port}/api/team/governance/permissions')`)
|
||||
* that previously looped back through the Fastify route.
|
||||
*
|
||||
* Returns the role-specific policy if found, or undefined if governance is unavailable.
|
||||
*/
|
||||
export async function getGovernancePermissions(
|
||||
dataDir: string,
|
||||
workspaceId: string,
|
||||
teamRole: string | undefined,
|
||||
): Promise<GovernancePolicies | undefined> {
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
if (!teamServer?.url || !teamServer?.token) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Check cache
|
||||
const cacheKey = workspaceId ?? 'default';
|
||||
const cached = policyCache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
|
||||
return extractRolePolicy(cached.permissions, teamRole);
|
||||
}
|
||||
|
||||
try {
|
||||
const teamSlug = (teamServer as unknown as Record<string, unknown>).teamSlug as string ?? 'default';
|
||||
const url = `${teamServer.url.replace(/\/$/, '')}/api/teams/${teamSlug}/capability-policies`;
|
||||
const res = await fetchTeamServer(url, {
|
||||
headers: { 'Authorization': `Bearer ${teamServer.token}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`${res.status}`);
|
||||
const policies = await res.json();
|
||||
|
||||
policyCache.set(cacheKey, { permissions: policies, fetchedAt: Date.now() });
|
||||
return extractRolePolicy(policies, teamRole);
|
||||
} catch {
|
||||
// Return cached if available, otherwise undefined
|
||||
if (cached) return extractRolePolicy(cached.permissions, teamRole);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Extract blocked tools from the role-specific policy within the permissions array */
|
||||
function extractRolePolicy(
|
||||
permissions: unknown,
|
||||
teamRole: string | undefined,
|
||||
): GovernancePolicies | undefined {
|
||||
if (!Array.isArray(permissions)) return undefined;
|
||||
const rolePolicy = permissions.find(
|
||||
(p: Record<string, unknown>) => p.role === teamRole,
|
||||
);
|
||||
if (rolePolicy?.blockedTools) {
|
||||
return { blockedTools: rolePolicy.blockedTools as string[] };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -37,7 +37,7 @@ const NON_RETAINED_TURN_CONTENT = '[Not retained: memory disabled for this turn]
|
||||
function resolvePersona(id: string) {
|
||||
return listPersonas().find(p => p.id === id) ?? null;
|
||||
}
|
||||
import { TeamSync, WaggleConfig, type CronStore, type SavePendingActionInput } from '@waggle/core';
|
||||
import { WaggleConfig, type CronStore, type SavePendingActionInput } from '@waggle/core';
|
||||
import { PERSONAL_SCOPE, workspaceScope } from '@waggle/memory-contract';
|
||||
|
||||
// ── Extracted modules ──────────────────────────────────────────────────
|
||||
@@ -63,7 +63,6 @@ import {
|
||||
selectChatPromptPackageMode,
|
||||
type ChatPromptPackageMode,
|
||||
} from './chat-prompt-packaging.js';
|
||||
import { getGovernancePermissions } from './chat-governance.js';
|
||||
import { applyPersonaToolFilter, filterMcpToolsForPersona, selectToolsForTurn } from '../persona-tool-filter.js';
|
||||
import { decideReviewTurnTool } from '../held-action-executor.js';
|
||||
import { assertSafeSegment } from './validate.js';
|
||||
@@ -77,8 +76,6 @@ import { bindModelSpendBudget } from '../model-spend-meter.js';
|
||||
import { resolveWorkspaceExecutionRoot } from '../workspace-execution-root.js';
|
||||
import type { WorkspaceTurnScope } from '../workspace-turn-coordinator.js';
|
||||
import { bindChatCollaborationTools } from '../chat-collaboration.js';
|
||||
import { getBoundTeamServer } from '../team-server-binding.js';
|
||||
import { fetchTeamServer } from '../team-server-egress.js';
|
||||
import { getResolvedChatWorkspaceId } from '../security-middleware.js';
|
||||
import type { GoalAncestry } from '@waggle/shared';
|
||||
import { GENERATION_FAILED_PREFIX, RISK_LEVELS, type RiskLevel } from '@waggle/shared';
|
||||
@@ -2487,30 +2484,7 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
|
||||
windowedMessages = applyContextWindow(history);
|
||||
}
|
||||
|
||||
// Governance policies for team workspaces — direct call (no HTTP loopback)
|
||||
let governancePolicies: { blockedTools?: string[]; allowedSources?: string[] } | undefined;
|
||||
if (wsConfig?.teamId && effectiveWorkspace) {
|
||||
try {
|
||||
governancePolicies = await getGovernancePermissions(
|
||||
server.localConfig.dataDir,
|
||||
effectiveWorkspace,
|
||||
wsConfig.teamRole,
|
||||
);
|
||||
throwIfTurnAborted();
|
||||
} catch {
|
||||
throwIfTurnAborted();
|
||||
// Governance not available — allow all.
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasCustomRunner) {
|
||||
// Remove governance-blocked definitions before serialization, while
|
||||
// retaining the executor's deny check as defense in depth.
|
||||
const blockedTools = new Set(governancePolicies?.blockedTools ?? []);
|
||||
if (blockedTools.size > 0) {
|
||||
effectiveTools = effectiveTools.filter(tool => !blockedTools.has(tool.name));
|
||||
spawnAvailableTools = spawnAvailableTools.filter(tool => !blockedTools.has(tool.name));
|
||||
}
|
||||
effectiveTools = filterToolsByTurnMutationPolicy(
|
||||
effectiveTools,
|
||||
turnMutationPolicy,
|
||||
@@ -2571,7 +2545,6 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
|
||||
allowDerivedPersistence,
|
||||
securityContext: {
|
||||
hooks: requestHookRegistry,
|
||||
blockedTools: governancePolicies?.blockedTools,
|
||||
allowedToolNames: spawnAllowedToolNames,
|
||||
},
|
||||
parentSignal: turnSignal,
|
||||
@@ -2813,7 +2786,6 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
|
||||
reasoning: reasoningForModelAttempt(resolvedModel),
|
||||
hooks: requestHookRegistry,
|
||||
capabilityRouter,
|
||||
governancePolicies,
|
||||
signal: turnSignal,
|
||||
turnId, // H-AUDIT-1: propagate trace ID into the loop
|
||||
|
||||
@@ -2896,42 +2868,6 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
|
||||
const filePath = String(input.path);
|
||||
sendEvent('file_created', { filePath, fileAction });
|
||||
}
|
||||
|
||||
// TeamSync push — after save_memory in team workspace (fire-and-forget)
|
||||
if (allowMemoryPersistence && name === 'save_memory' && !result.startsWith('Error')) {
|
||||
const pushWsConfig = activeExecutionWorkspaceId
|
||||
? server.workspaceManager?.get(activeExecutionWorkspaceId)
|
||||
: undefined;
|
||||
if (pushWsConfig?.teamId) {
|
||||
try {
|
||||
const waggleConfig = new WaggleConfig(server.localConfig.dataDir);
|
||||
const teamServer = getBoundTeamServer(pushWsConfig.teamServerUrl, waggleConfig.getTeamServer());
|
||||
if (teamServer?.token) {
|
||||
const sync = new TeamSync({
|
||||
teamServerUrl: teamServer.url,
|
||||
teamSlug: pushWsConfig.teamId,
|
||||
authToken: teamServer.token,
|
||||
userId: teamServer.userId ?? 'local-user',
|
||||
displayName: teamServer.displayName ?? 'You',
|
||||
}, fetchTeamServer);
|
||||
// Fire-and-forget push — non-blocking
|
||||
sync.pushFrame({
|
||||
id: Date.now(),
|
||||
gop_id: sessionId ?? 'unknown',
|
||||
t: 0,
|
||||
frame_type: 'I',
|
||||
base_frame_id: null,
|
||||
content: typeof result === 'string' ? result.slice(0, 500) : '',
|
||||
importance: 'normal',
|
||||
source: 'agent_inferred',
|
||||
access_count: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
last_accessed: new Date().toISOString(),
|
||||
}).catch(err => log.warn('[waggle] TeamSync push failed:', err.message));
|
||||
}
|
||||
} catch { /* TeamSync not available */ }
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -15,8 +15,6 @@ import path from 'node:path';
|
||||
import type { FastifyPluginAsync, FastifyInstance } from 'fastify';
|
||||
import Database from 'better-sqlite3';
|
||||
import { validateOrigin } from '../cors-config.js';
|
||||
import { getBoundTeamServer } from '../team-server-binding.js';
|
||||
import { fetchTeamServer } from '../team-server-egress.js';
|
||||
|
||||
// ── Event types ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -145,35 +143,6 @@ export function emitAuditEvent(
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
server.eventBus?.emit('audit_event', fullEvent);
|
||||
|
||||
// TeamSync: Push audit event to team server (fire-and-forget)
|
||||
try {
|
||||
const wsConfig = event.workspaceId ? server.workspaceManager?.get(event.workspaceId) : null;
|
||||
if (wsConfig?.teamId && wsConfig?.teamServerUrl) {
|
||||
(async () => {
|
||||
try {
|
||||
const { WaggleConfig } = await import('@waggle/core');
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = getBoundTeamServer(wsConfig.teamServerUrl, waggleConfig.getTeamServer());
|
||||
if (teamServer?.token) {
|
||||
fetchTeamServer(`${teamServer.url}/api/teams/${wsConfig.teamId}/audit`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${teamServer.token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...event,
|
||||
timestamp: new Date().toISOString(),
|
||||
source: 'local-agent',
|
||||
}),
|
||||
signal: AbortSignal.timeout(3000),
|
||||
}).catch(() => { /* non-blocking */ });
|
||||
}
|
||||
} catch { /* team push is best-effort */ }
|
||||
})();
|
||||
}
|
||||
} catch { /* team push is best-effort */ }
|
||||
} catch {
|
||||
// Non-blocking — audit logging must never crash the main flow
|
||||
}
|
||||
|
||||
@@ -152,8 +152,8 @@ export async function fleetRoutes(fastify: FastifyInstance) {
|
||||
//
|
||||
// Scoped out vs chat parity (separate followup): credential pool +
|
||||
// provider fallback chain, trace recorder for evolution substrate,
|
||||
// file_created events, TeamSync push, governance.allowedSources
|
||||
// enforcement, custom user-system-prompt + profile injection. Spawn
|
||||
// file_created events, governance.allowedSources enforcement,
|
||||
// custom user-system-prompt + profile injection. Spawn
|
||||
// uses the orchestrator's bare buildSystemPrompt() — enough for
|
||||
// autonomous tool-use, not as personalized as chat.
|
||||
const spawnSessionId = `spawn-${Date.now()}`;
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { PERSONAL_SCOPE } from '@waggle/memory-contract';
|
||||
|
||||
/** Minimal shape of an OpenAI-compatible chat-completions response. */
|
||||
interface ChatCompletionResponse {
|
||||
@@ -220,20 +221,22 @@ export const profileRoutes: FastifyPluginAsync = async (fastify) => {
|
||||
profile.industry && `Industry: ${profile.industry}`,
|
||||
].filter(Boolean).join('. ');
|
||||
if (identity) {
|
||||
const frames = orch.getFrames();
|
||||
const sessions = orch.getSessions();
|
||||
const active = sessions.getActive();
|
||||
const gopId = active.length > 0 ? active[0].gop_id : sessions.create().gop_id;
|
||||
// Replace-on-update (the W4.3 profile-card lane): a profile save
|
||||
// updates THE identity card — every save appending another
|
||||
// "User identity:" frame filled the memory list with duplicates.
|
||||
frames.deleteByContentPrefix('User identity: ');
|
||||
const latestI = frames.getLatestIFrame(gopId);
|
||||
if (latestI) {
|
||||
frames.createPFrame(gopId, `User identity: ${identity}`, latestI.id, 'important');
|
||||
} else {
|
||||
frames.createIFrame(gopId, `User identity: ${identity}`, 'important');
|
||||
// "User identity:" memory filled the memory list with duplicates.
|
||||
const memory = orch.getMemory();
|
||||
const cards = await memory.list({ scopes: [PERSONAL_SCOPE], kinds: ['profile'], limit: 1000 });
|
||||
for (const card of cards) {
|
||||
if (card.text.startsWith('User identity: ')) await memory.forget(card.id);
|
||||
}
|
||||
await memory.remember({
|
||||
scope: PERSONAL_SCOPE,
|
||||
text: `User identity: ${identity}`,
|
||||
kind: 'profile',
|
||||
importance: 'important',
|
||||
source: 'user_stated',
|
||||
origin: 'profile',
|
||||
});
|
||||
|
||||
// profile.json is the authoritative identity source: a profile save
|
||||
// SUPERSEDES the structured IdentityLayer row (org/title), so stale
|
||||
|
||||
@@ -448,8 +448,6 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
// does not ship (ADR-0003).
|
||||
available: false,
|
||||
enabled: raw.cloudSyncEnabled === true,
|
||||
teamServerUrl: (raw.teamServer as Record<string, unknown>)?.url ?? null,
|
||||
connected: !!((raw.teamServer as Record<string, unknown>)?.token),
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -1,848 +0,0 @@
|
||||
/**
|
||||
* Team routes for the local server.
|
||||
*
|
||||
* These routes handle team server connection from the desktop app:
|
||||
* - POST /api/team/connect — connect to team server (validate token, store config)
|
||||
* - POST /api/team/disconnect — disconnect from team server
|
||||
* - GET /api/team/status — get current team connection status
|
||||
*/
|
||||
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import Database from 'better-sqlite3';
|
||||
import { WaggleConfig } from '@waggle/core';
|
||||
import { allowLocalFromEnv, safeFetch } from '@waggle/agent';
|
||||
import { emitNotification } from './notifications.js';
|
||||
import { emitAuditEvent } from './events.js';
|
||||
|
||||
// ── Local team DB ────────────────────────────────────────────────────
|
||||
|
||||
type TeamRole = 'owner' | 'admin' | 'member' | 'viewer';
|
||||
|
||||
interface TeamRow {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
owner_id: string;
|
||||
created: string;
|
||||
updated: string;
|
||||
}
|
||||
|
||||
interface MemberRow {
|
||||
team_id: string;
|
||||
user_id: string;
|
||||
role: TeamRole;
|
||||
display_name: string;
|
||||
email: string | null;
|
||||
joined: string;
|
||||
}
|
||||
|
||||
let teamsDb: Database.Database | null = null;
|
||||
|
||||
function getTeamsDb(dataDir: string): Database.Database {
|
||||
if (teamsDb) return teamsDb;
|
||||
|
||||
const dbPath = path.join(dataDir, 'teams.db');
|
||||
teamsDb = new Database(dbPath);
|
||||
teamsDb.pragma('journal_mode = WAL');
|
||||
teamsDb.pragma('synchronous = NORMAL');
|
||||
|
||||
teamsDb.exec(`
|
||||
CREATE TABLE IF NOT EXISTS teams (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
owner_id TEXT NOT NULL,
|
||||
created TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS team_members (
|
||||
team_id TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('owner', 'admin', 'member', 'viewer')),
|
||||
display_name TEXT NOT NULL DEFAULT '',
|
||||
email TEXT,
|
||||
joined TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (team_id, user_id),
|
||||
FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_team_members_user ON team_members (user_id);
|
||||
`);
|
||||
|
||||
return teamsDb;
|
||||
}
|
||||
|
||||
export function closeTeamsDb(): void {
|
||||
if (teamsDb) {
|
||||
try { teamsDb.close(); } catch { /* ignore */ }
|
||||
teamsDb = null;
|
||||
}
|
||||
}
|
||||
|
||||
function getLocalUserId(dataDir: string): string {
|
||||
try {
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
if (teamServer?.userId && teamServer.userId !== 'unknown') return teamServer.userId;
|
||||
} catch { /* ignore */ }
|
||||
return 'local-user';
|
||||
}
|
||||
|
||||
function getLocalDisplayName(dataDir: string): string {
|
||||
try {
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
if (teamServer?.displayName) return teamServer.displayName;
|
||||
} catch { /* ignore */ }
|
||||
return 'You';
|
||||
}
|
||||
|
||||
function hasAllowedTeamServerProtocol(url: URL, allowLocal: boolean): boolean {
|
||||
const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
||||
const isExplicitLoopback = hostname === 'localhost'
|
||||
|| hostname.endsWith('.localhost')
|
||||
|| hostname === '::1'
|
||||
|| /^127(?:\.\d{1,3}){3}$/.test(hostname);
|
||||
return url.protocol === 'https:' || (url.protocol === 'http:' && allowLocal && isExplicitLoopback);
|
||||
}
|
||||
|
||||
function normalizeTeamServerBaseUrl(value: string, allowLocal: boolean): string | null {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.username || url.password || url.search || url.hash) return null;
|
||||
if (!hasAllowedTeamServerProtocol(url, allowLocal)) return null;
|
||||
return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function fetchTeamServer(url: string, init: RequestInit = {}): Promise<Response> {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.username || parsed.password || parsed.hash
|
||||
|| !hasAllowedTeamServerProtocol(parsed, allowLocalFromEnv())) {
|
||||
return Promise.reject(new Error('Blocked insecure Team server URL'));
|
||||
}
|
||||
return safeFetch(url, init, {
|
||||
allowLocal: allowLocalFromEnv(),
|
||||
maxRedirects: 0,
|
||||
});
|
||||
}
|
||||
|
||||
export async function teamRoutes(fastify: FastifyInstance) {
|
||||
const dataDir = fastify.localConfig.dataDir;
|
||||
|
||||
/**
|
||||
* POST /api/team/connect
|
||||
* Connect to a team server by validating the token against the server's health endpoint.
|
||||
*/
|
||||
fastify.post('/api/team/connect', async (request, reply) => {
|
||||
const { serverUrl, token } = request.body as { serverUrl: string; token: string };
|
||||
|
||||
if (!serverUrl || !token) {
|
||||
return reply.code(400).send({ error: 'serverUrl and token are required' });
|
||||
}
|
||||
const normalizedServerUrl = normalizeTeamServerBaseUrl(serverUrl, allowLocalFromEnv());
|
||||
if (!normalizedServerUrl) {
|
||||
return reply.code(400).send({
|
||||
error: 'Team server URL must use HTTPS; HTTP is allowed only for explicitly enabled loopback servers',
|
||||
});
|
||||
}
|
||||
|
||||
// Validate by calling the team server health endpoint
|
||||
try {
|
||||
const healthUrl = `${normalizedServerUrl}/health`;
|
||||
const healthRes = await fetchTeamServer(healthUrl, {
|
||||
headers: { 'Authorization': `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
|
||||
if (!healthRes.ok) {
|
||||
return reply.code(502).send({ error: `Team server returned ${healthRes.status}` });
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const name = err instanceof Error ? err.name : '';
|
||||
if (name === 'TimeoutError' || name === 'AbortError') {
|
||||
return reply.code(504).send({ error: 'Team server connection timed out' });
|
||||
}
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return reply.code(502).send({ error: `Cannot reach team server: ${message}` });
|
||||
}
|
||||
|
||||
// Try to get user info from the team server
|
||||
let userId = 'unknown';
|
||||
let displayName = 'Unknown User';
|
||||
try {
|
||||
const teamsRes = await fetchTeamServer(`${normalizedServerUrl}/api/teams`, {
|
||||
headers: { 'Authorization': `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (teamsRes.ok) {
|
||||
// Token is valid and user has access — extract from response is not possible without user endpoint
|
||||
// For now, we know the connection works
|
||||
userId = 'authenticated';
|
||||
displayName = 'Team User';
|
||||
}
|
||||
} catch {
|
||||
// Non-critical — connection itself was validated by health check
|
||||
}
|
||||
|
||||
// Store team server config
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
waggleConfig.setTeamServer({
|
||||
url: normalizedServerUrl,
|
||||
token,
|
||||
userId,
|
||||
displayName,
|
||||
});
|
||||
waggleConfig.save();
|
||||
|
||||
const connection = {
|
||||
serverUrl: normalizedServerUrl,
|
||||
token: '***', // Don't send token back
|
||||
userId,
|
||||
displayName,
|
||||
};
|
||||
|
||||
return reply.code(200).send(connection);
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/team/disconnect
|
||||
* Disconnect from the team server.
|
||||
*/
|
||||
fastify.post('/api/team/disconnect', async (_request, reply) => {
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
waggleConfig.clearTeamServer();
|
||||
waggleConfig.save();
|
||||
|
||||
return reply.code(200).send({ disconnected: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/team/teams
|
||||
* List teams the connected user belongs to (proxied from team server).
|
||||
*/
|
||||
fastify.get('/api/team/teams', async (_request, reply) => {
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
|
||||
if (!teamServer || !teamServer.token) {
|
||||
return reply.code(401).send({ error: 'Not connected to a team server' });
|
||||
}
|
||||
|
||||
try {
|
||||
const teamsUrl = `${teamServer.url}/api/teams`;
|
||||
const res = await fetchTeamServer(teamsUrl, {
|
||||
headers: { 'Authorization': `Bearer ${teamServer.token}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return reply.code(res.status).send({ error: `Team server returned ${res.status}` });
|
||||
}
|
||||
|
||||
const teams = await res.json();
|
||||
return reply.code(200).send(teams);
|
||||
} catch (err: unknown) {
|
||||
const name = err instanceof Error ? err.name : '';
|
||||
if (name === 'TimeoutError' || name === 'AbortError') {
|
||||
return reply.code(504).send({ error: 'Team server request timed out' });
|
||||
}
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return reply.code(502).send({ error: `Cannot reach team server: ${message}` });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/team/presence?workspaceId=X
|
||||
* Get team presence data for a workspace (proxied from team server, or mock if unavailable).
|
||||
*/
|
||||
fastify.get<{
|
||||
Querystring: { workspaceId?: string };
|
||||
}>('/api/team/presence', async (request, reply) => {
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
|
||||
if (!teamServer || !teamServer.token) {
|
||||
return reply.code(200).send({ members: [] });
|
||||
}
|
||||
|
||||
// Try to fetch real presence from team server
|
||||
try {
|
||||
const presenceUrl = `${teamServer.url}/api/presence`;
|
||||
const res = await fetchTeamServer(presenceUrl, {
|
||||
headers: { 'Authorization': `Bearer ${teamServer.token}` },
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
// Emit presence update for WebSocket subscribers
|
||||
fastify.eventBus.emit('presence_update', data);
|
||||
return reply.code(200).send(data);
|
||||
}
|
||||
} catch {
|
||||
// Team server unavailable — return self as online (local-only fallback)
|
||||
}
|
||||
|
||||
// Fallback: return current user as online
|
||||
const fallbackData = {
|
||||
members: [{
|
||||
userId: teamServer.userId ?? 'self',
|
||||
displayName: teamServer.displayName ?? 'You',
|
||||
status: 'online',
|
||||
lastActivity: new Date().toISOString(),
|
||||
}],
|
||||
};
|
||||
// Emit presence update for WebSocket subscribers
|
||||
fastify.eventBus.emit('presence_update', fallbackData);
|
||||
return reply.code(200).send(fallbackData);
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/team/status
|
||||
* Get current team connection status.
|
||||
*/
|
||||
fastify.get('/api/team/status', async (_request, reply) => {
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
|
||||
if (!teamServer) {
|
||||
return reply.code(200).send({ connected: false });
|
||||
}
|
||||
|
||||
return reply.code(200).send({
|
||||
connected: true,
|
||||
serverUrl: teamServer.url,
|
||||
userId: teamServer.userId ?? 'unknown',
|
||||
displayName: teamServer.displayName ?? 'Team User',
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/team/members
|
||||
* List team members. Proxies to team server or returns local user when disconnected.
|
||||
*/
|
||||
fastify.get('/api/team/members', async () => {
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
if (teamServer) {
|
||||
try {
|
||||
const res = await fetchTeamServer(`${teamServer.url}/api/team/members`, {
|
||||
headers: { Authorization: `Bearer ${teamServer.token}` },
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
if (res.ok) return res.json();
|
||||
} catch { /* fall through */ }
|
||||
}
|
||||
return { members: [{ id: 'local', name: 'You', status: 'online' }] };
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/team/activity?workspaceId=X&limit=N
|
||||
* Get recent team activity for a workspace.
|
||||
* Proxies to team server or returns empty when disconnected.
|
||||
*/
|
||||
fastify.get<{
|
||||
Querystring: { workspaceId?: string; limit?: string };
|
||||
}>('/api/team/activity', async (request, reply) => {
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
const limit = Math.min(parseInt(request.query.limit ?? '20', 10) || 20, 50);
|
||||
|
||||
if (!teamServer || !teamServer.token) {
|
||||
return reply.code(200).send({ items: [] });
|
||||
}
|
||||
|
||||
// Try to fetch activity from team server's entities API
|
||||
// (synced frames = memory additions, which are our primary activity source)
|
||||
try {
|
||||
const workspaceId = request.query.workspaceId;
|
||||
const entitiesUrl = `${teamServer.url}/api/entities?type=memory_frame&limit=${limit}`;
|
||||
const res = await fetchTeamServer(entitiesUrl, {
|
||||
headers: { 'Authorization': `Bearer ${teamServer.token}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json() as { entities?: Array<{
|
||||
id: string;
|
||||
metadata?: { authorName?: string; authorId?: string; frameType?: string; content?: string };
|
||||
createdAt?: string;
|
||||
}> };
|
||||
|
||||
const items = (data.entities ?? []).map((e) => ({
|
||||
id: e.id,
|
||||
type: 'memory' as const,
|
||||
authorName: e.metadata?.authorName ?? 'Unknown',
|
||||
authorId: e.metadata?.authorId,
|
||||
summary: e.metadata?.content
|
||||
? (e.metadata.content.length > 120 ? e.metadata.content.slice(0, 120) + '...' : e.metadata.content)
|
||||
: `Added ${e.metadata?.frameType ?? 'frame'}`,
|
||||
timestamp: e.createdAt ?? new Date().toISOString(),
|
||||
}));
|
||||
|
||||
return reply.code(200).send({ items });
|
||||
}
|
||||
} catch {
|
||||
// Team server unavailable — return empty
|
||||
}
|
||||
|
||||
return reply.code(200).send({ items: [] });
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/team/messages?workspaceId=X&limit=N
|
||||
* Get recent Waggle Dance messages for a workspace.
|
||||
* Proxies to team server or returns empty when disconnected.
|
||||
*/
|
||||
fastify.get<{
|
||||
Querystring: { workspaceId?: string; limit?: string };
|
||||
}>('/api/team/messages', async (request, reply) => {
|
||||
const waggleConfig = new WaggleConfig(dataDir);
|
||||
const teamServer = waggleConfig.getTeamServer();
|
||||
const limit = Math.min(parseInt(request.query.limit ?? '20', 10) || 20, 50);
|
||||
|
||||
if (!teamServer || !teamServer.token) {
|
||||
return reply.code(200).send({ messages: [] });
|
||||
}
|
||||
|
||||
try {
|
||||
const teamSlug = (teamServer as { teamSlug?: string }).teamSlug ?? 'default';
|
||||
const messagesUrl = `${teamServer.url}/api/teams/${teamSlug}/messages?limit=${limit}`;
|
||||
const res = await fetchTeamServer(messagesUrl, {
|
||||
headers: { 'Authorization': `Bearer ${teamServer.token}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json() as { messages?: unknown[] } | unknown[];
|
||||
const messages = (Array.isArray(data) ? data : data?.messages) ?? [];
|
||||
if (Array.isArray(messages) && messages.length > 0) {
|
||||
emitNotification(fastify, {
|
||||
title: 'Team message',
|
||||
body: 'New message from team',
|
||||
category: 'message',
|
||||
});
|
||||
}
|
||||
return reply.code(200).send({ messages });
|
||||
}
|
||||
} catch {
|
||||
// Team server unavailable — return empty
|
||||
}
|
||||
|
||||
return reply.code(200).send({ messages: [] });
|
||||
});
|
||||
|
||||
// --- Capability Governance Proxy ---
|
||||
|
||||
// In-memory policy cache: teamId → { permissions, fetchedAt }
|
||||
const policyCache = new Map<string, { permissions: unknown; fetchedAt: number }>();
|
||||
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
// Listen for policy update events to invalidate cache
|
||||
if (fastify.eventBus) {
|
||||
fastify.eventBus.on('capability_policy_update', (data: { teamId?: string } | undefined) => {
|
||||
if (data?.teamId) policyCache.delete(data.teamId);
|
||||
else policyCache.clear(); // Clear all if no specific teamId
|
||||
});
|
||||
}
|
||||
|
||||
// GET /api/team/governance/permissions — get effective permissions for current user
|
||||
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();
|
||||
if (!teamServer?.url || !teamServer?.token) {
|
||||
return { connected: false, permissions: null };
|
||||
}
|
||||
|
||||
// Check cache
|
||||
const cacheKey = workspaceId ?? 'default';
|
||||
const cached = policyCache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
|
||||
return { connected: true, permissions: cached.permissions };
|
||||
}
|
||||
|
||||
try {
|
||||
const teamSlug = (teamServer as { teamSlug?: string }).teamSlug ?? 'default';
|
||||
const url = `${teamServer.url.replace(/\/$/, '')}/api/teams/${teamSlug}/capability-policies`;
|
||||
const res = await fetchTeamServer(url, {
|
||||
headers: { 'Authorization': `Bearer ${teamServer.token}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`${res.status}`);
|
||||
const policies = await res.json();
|
||||
|
||||
policyCache.set(cacheKey, { permissions: policies, fetchedAt: Date.now() });
|
||||
return { connected: true, permissions: policies };
|
||||
} catch {
|
||||
// Return cached if available, otherwise null
|
||||
if (cached) return { connected: true, permissions: cached.permissions, stale: true };
|
||||
return { connected: true, permissions: null };
|
||||
}
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// F3: Local team entity CRUD — works in solo mode with local userId
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
const db = getTeamsDb(dataDir);
|
||||
const userId = getLocalUserId(dataDir);
|
||||
|
||||
// POST /api/teams — create a team
|
||||
fastify.post<{
|
||||
Body: { name: string; description?: string };
|
||||
}>('/api/teams', async (request, reply) => {
|
||||
const { name, description } = request.body ?? {};
|
||||
if (!name || typeof name !== 'string' || name.trim().length === 0) {
|
||||
return reply.code(400).send({ error: 'name is required' });
|
||||
}
|
||||
|
||||
const id = `team-${crypto.randomUUID().slice(0, 8)}`;
|
||||
const uid = getLocalUserId(dataDir);
|
||||
const displayName = getLocalDisplayName(dataDir);
|
||||
const now = new Date().toISOString();
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO teams (id, name, description, owner_id, created, updated)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`).run(id, name.trim(), description?.trim() ?? '', uid, now, now);
|
||||
|
||||
// Auto-add creator as owner member
|
||||
db.prepare(`
|
||||
INSERT INTO team_members (team_id, user_id, role, display_name, joined)
|
||||
VALUES (?, ?, 'owner', ?, ?)
|
||||
`).run(id, uid, displayName, now);
|
||||
|
||||
emitAuditEvent(fastify, { workspaceId: 'global', eventType: 'workspace_create', input: JSON.stringify({ teamId: id, name }) });
|
||||
|
||||
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(id) as TeamRow;
|
||||
const members = db.prepare('SELECT * FROM team_members WHERE team_id = ?').all(id) as MemberRow[];
|
||||
return reply.code(201).send({ ...normalizeTeam(team), members: members.map(normalizeMember) });
|
||||
});
|
||||
|
||||
// GET /api/teams — list teams for current user
|
||||
fastify.get('/api/teams', async () => {
|
||||
const uid = getLocalUserId(dataDir);
|
||||
const rows = db.prepare(`
|
||||
SELECT t.* FROM teams t
|
||||
JOIN team_members m ON t.id = m.team_id
|
||||
WHERE m.user_id = ?
|
||||
ORDER BY t.created DESC
|
||||
`).all(uid) as TeamRow[];
|
||||
|
||||
return { teams: rows.map(normalizeTeam) };
|
||||
});
|
||||
|
||||
// GET /api/teams/:id — team detail with members
|
||||
fastify.get<{ Params: { id: string } }>('/api/teams/:id', async (request, reply) => {
|
||||
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
|
||||
if (!team) return reply.code(404).send({ error: 'Team not found' });
|
||||
|
||||
const members = db.prepare('SELECT * FROM team_members WHERE team_id = ?').all(team.id) as MemberRow[];
|
||||
|
||||
// Team workspaces
|
||||
const allWorkspaces = fastify.workspaceManager.list();
|
||||
const teamWorkspaces = allWorkspaces.filter((ws) => ws.teamId === team.id || ws.team === team.id);
|
||||
|
||||
return {
|
||||
...normalizeTeam(team),
|
||||
members: members.map(normalizeMember),
|
||||
workspaces: teamWorkspaces,
|
||||
};
|
||||
});
|
||||
|
||||
// PUT /api/teams/:id — update team
|
||||
fastify.put<{
|
||||
Params: { id: string };
|
||||
Body: { name?: string; description?: string };
|
||||
}>('/api/teams/:id', async (request, reply) => {
|
||||
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
|
||||
if (!team) return reply.code(404).send({ error: 'Team not found' });
|
||||
|
||||
const uid = getLocalUserId(dataDir);
|
||||
const member = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, uid) as MemberRow | undefined;
|
||||
if (!member || (member.role !== 'owner' && member.role !== 'admin')) {
|
||||
return reply.code(403).send({ error: 'Only owner or admin can update team' });
|
||||
}
|
||||
|
||||
const { name, description } = request.body ?? {};
|
||||
const updates: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
|
||||
if (name !== undefined) { updates.push('name = ?'); params.push(name.trim()); }
|
||||
if (description !== undefined) { updates.push('description = ?'); params.push(description.trim()); }
|
||||
|
||||
if (updates.length > 0) {
|
||||
updates.push("updated = datetime('now')");
|
||||
params.push(team.id);
|
||||
db.prepare(`UPDATE teams SET ${updates.join(', ')} WHERE id = ?`).run(...params);
|
||||
}
|
||||
|
||||
return db.prepare('SELECT * FROM teams WHERE id = ?').get(team.id);
|
||||
});
|
||||
|
||||
// DELETE /api/teams/:id — delete team (owner only)
|
||||
fastify.delete<{ Params: { id: string } }>('/api/teams/:id', async (request, reply) => {
|
||||
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
|
||||
if (!team) return reply.code(404).send({ error: 'Team not found' });
|
||||
|
||||
const uid = getLocalUserId(dataDir);
|
||||
if (team.owner_id !== uid) {
|
||||
return reply.code(403).send({ error: 'Only the team owner can delete the team' });
|
||||
}
|
||||
|
||||
// Remove all members first (CASCADE should handle this but be explicit)
|
||||
db.prepare('DELETE FROM team_members WHERE team_id = ?').run(team.id);
|
||||
db.prepare('DELETE FROM teams WHERE id = ?').run(team.id);
|
||||
|
||||
// Unlink workspaces from this team
|
||||
const allWorkspaces = fastify.workspaceManager.list();
|
||||
for (const ws of allWorkspaces) {
|
||||
if (ws.teamId === team.id || ws.team === team.id) {
|
||||
fastify.workspaceManager.update(ws.id, { teamId: undefined, team: null });
|
||||
}
|
||||
}
|
||||
|
||||
emitAuditEvent(fastify, { workspaceId: 'global', eventType: 'workspace_delete', input: JSON.stringify({ teamId: team.id }) });
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// ── Member management ────────────────────────────────────────────
|
||||
|
||||
// POST /api/teams/:id/members — invite/add member
|
||||
fastify.post<{
|
||||
Params: { id: string };
|
||||
Body: { userId?: string; email?: string; displayName?: string; role?: TeamRole };
|
||||
}>('/api/teams/:id/members', async (request, reply) => {
|
||||
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
|
||||
if (!team) return reply.code(404).send({ error: 'Team not found' });
|
||||
|
||||
// Check permission: owner or admin can add members
|
||||
const uid = getLocalUserId(dataDir);
|
||||
const self = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, uid) as MemberRow | undefined;
|
||||
if (!self || (self.role !== 'owner' && self.role !== 'admin')) {
|
||||
return reply.code(403).send({ error: 'Only owner or admin can add members' });
|
||||
}
|
||||
|
||||
const { userId: newUserId, email, displayName, role } = request.body ?? {};
|
||||
const memberUserId = newUserId ?? email ?? `user-${crypto.randomUUID().slice(0, 8)}`;
|
||||
const memberRole: TeamRole = role && ['owner', 'admin', 'member', 'viewer'].includes(role) ? role : 'member';
|
||||
|
||||
// Check if already a member
|
||||
const existing = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, memberUserId);
|
||||
if (existing) {
|
||||
return reply.code(409).send({ error: 'User is already a team member' });
|
||||
}
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO team_members (team_id, user_id, role, display_name, email, joined)
|
||||
VALUES (?, ?, ?, ?, ?, datetime('now'))
|
||||
`).run(team.id, memberUserId, memberRole, displayName ?? memberUserId, email ?? null);
|
||||
|
||||
const member = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, memberUserId) as MemberRow;
|
||||
return reply.code(201).send(normalizeMember(member));
|
||||
});
|
||||
|
||||
// PUT /api/teams/:id/members/:userId — change member role
|
||||
fastify.put<{
|
||||
Params: { id: string; userId: string };
|
||||
Body: { role: TeamRole };
|
||||
}>('/api/teams/:id/members/:userId', async (request, reply) => {
|
||||
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
|
||||
if (!team) return reply.code(404).send({ error: 'Team not found' });
|
||||
|
||||
const uid = getLocalUserId(dataDir);
|
||||
const self = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, uid) as MemberRow | undefined;
|
||||
if (!self || self.role !== 'owner') {
|
||||
return reply.code(403).send({ error: 'Only the team owner can change roles' });
|
||||
}
|
||||
|
||||
const { role } = request.body ?? {};
|
||||
if (!role || !['owner', 'admin', 'member', 'viewer'].includes(role)) {
|
||||
return reply.code(400).send({ error: 'Invalid role. Must be: owner, admin, member, or viewer' });
|
||||
}
|
||||
|
||||
const target = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, request.params.userId) as MemberRow | undefined;
|
||||
if (!target) return reply.code(404).send({ error: 'Member not found' });
|
||||
|
||||
db.prepare('UPDATE team_members SET role = ? WHERE team_id = ? AND user_id = ?').run(role, team.id, request.params.userId);
|
||||
const updated = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, request.params.userId) as MemberRow;
|
||||
return normalizeMember(updated);
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:id/members/:userId — alias for PUT (common API convention)
|
||||
fastify.patch<{
|
||||
Params: { id: string; userId: string };
|
||||
Body: { role: TeamRole };
|
||||
}>('/api/teams/:id/members/:userId', async (request, reply) => {
|
||||
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
|
||||
if (!team) return reply.code(404).send({ error: 'Team not found' });
|
||||
const uid = getLocalUserId(dataDir);
|
||||
const self = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, uid) as MemberRow | undefined;
|
||||
if (!self || (self.role !== 'owner' && self.role !== 'admin')) {
|
||||
return reply.code(403).send({ error: 'Only owner or admin can change roles' });
|
||||
}
|
||||
const { role } = request.body ?? {};
|
||||
if (!role || !['owner', 'admin', 'member', 'viewer'].includes(role)) {
|
||||
return reply.code(400).send({ error: 'Invalid role. Must be: owner, admin, member, or viewer' });
|
||||
}
|
||||
const target = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, request.params.userId) as MemberRow | undefined;
|
||||
if (!target) return reply.code(404).send({ error: 'Member not found' });
|
||||
db.prepare('UPDATE team_members SET role = ? WHERE team_id = ? AND user_id = ?').run(role, team.id, request.params.userId);
|
||||
const updated = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, request.params.userId) as MemberRow;
|
||||
return normalizeMember(updated);
|
||||
});
|
||||
|
||||
// DELETE /api/teams/:id/members/:userId — remove member
|
||||
fastify.delete<{
|
||||
Params: { id: string; userId: string };
|
||||
}>('/api/teams/:id/members/:userId', async (request, reply) => {
|
||||
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
|
||||
if (!team) return reply.code(404).send({ error: 'Team not found' });
|
||||
|
||||
const uid = getLocalUserId(dataDir);
|
||||
const self = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, uid) as MemberRow | undefined;
|
||||
|
||||
// Can remove: owner/admin can remove anyone, members can remove themselves
|
||||
const targetUserId = request.params.userId;
|
||||
const isSelf = targetUserId === uid;
|
||||
if (!isSelf && (!self || (self.role !== 'owner' && self.role !== 'admin'))) {
|
||||
return reply.code(403).send({ error: 'Insufficient permissions' });
|
||||
}
|
||||
|
||||
// Can't remove the owner
|
||||
if (team.owner_id === targetUserId) {
|
||||
return reply.code(400).send({ error: 'Cannot remove the team owner. Transfer ownership first.' });
|
||||
}
|
||||
|
||||
db.prepare('DELETE FROM team_members WHERE team_id = ? AND user_id = ?').run(team.id, targetUserId);
|
||||
return { deleted: true, userId: targetUserId, teamId: team.id };
|
||||
});
|
||||
|
||||
// GET /api/teams/:id/activity — aggregated events from team workspaces (uses F2 audit trail)
|
||||
fastify.get<{
|
||||
Params: { id: string };
|
||||
Querystring: { limit?: string; from?: string };
|
||||
}>('/api/teams/:id/activity', async (request, reply) => {
|
||||
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
|
||||
if (!team) return reply.code(404).send({ error: 'Team not found' });
|
||||
|
||||
const limit = Math.min(parseInt(request.query.limit ?? '50', 10) || 50, 200);
|
||||
const from = request.query.from ?? new Date(Date.now() - 7 * 86400000).toISOString();
|
||||
|
||||
// Find all workspaces linked to this team
|
||||
const allWorkspaces = fastify.workspaceManager.list();
|
||||
const teamWsIds = allWorkspaces
|
||||
.filter((ws) => ws.teamId === team.id || ws.team === team.id)
|
||||
.map((ws) => ws.id);
|
||||
|
||||
if (teamWsIds.length === 0) {
|
||||
return { items: [], teamId: team.id };
|
||||
}
|
||||
|
||||
// Query audit events for all team workspaces
|
||||
try {
|
||||
const { getAuditDb } = await import('./events.js');
|
||||
const auditDb = getAuditDb(dataDir);
|
||||
const placeholders = teamWsIds.map(() => '?').join(',');
|
||||
const events = auditDb.prepare(`
|
||||
SELECT * FROM audit_events
|
||||
WHERE workspace_id IN (${placeholders}) AND timestamp >= ?
|
||||
ORDER BY id DESC LIMIT ?
|
||||
`).all(...teamWsIds, from, limit) as Array<Record<string, unknown>>;
|
||||
|
||||
const items = events.map(e => ({
|
||||
id: e.id,
|
||||
timestamp: e.timestamp,
|
||||
workspaceId: e.workspace_id,
|
||||
eventType: e.event_type,
|
||||
toolName: e.tool_name,
|
||||
sessionId: e.session_id,
|
||||
}));
|
||||
|
||||
return { items, teamId: team.id };
|
||||
} catch {
|
||||
return { items: [], teamId: team.id };
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/team/memory/search?q=query — search team memory frames
|
||||
fastify.get<{ Querystring: { q?: string; limit?: string } }>(
|
||||
'/api/team/memory/search',
|
||||
async (request, reply) => {
|
||||
const config = new WaggleConfig(fastify.localConfig.dataDir);
|
||||
const teamServer = config.getTeamServer();
|
||||
if (!teamServer?.url || !teamServer?.token) {
|
||||
return reply.code(400).send({ error: 'Not connected to team server' });
|
||||
}
|
||||
|
||||
const { q, limit: limitStr } = request.query;
|
||||
if (!q) return reply.code(400).send({ error: 'q parameter required' });
|
||||
const limit = Math.min(parseInt(limitStr ?? '20', 10), 50);
|
||||
|
||||
try {
|
||||
const url = `${teamServer.url}/api/entities?type=memory_frame&limit=${limit}`;
|
||||
const res = await fetchTeamServer(url, {
|
||||
headers: { 'Authorization': `Bearer ${teamServer.token}` },
|
||||
});
|
||||
if (!res.ok) return { results: [], count: 0 };
|
||||
|
||||
const entities = await res.json() as Array<{
|
||||
id: string; name: string;
|
||||
properties: Record<string, unknown>;
|
||||
sharedBy?: string; createdAt: string;
|
||||
}>;
|
||||
|
||||
// Client-side keyword filter (team server doesn't have FTS yet)
|
||||
const terms = q.toLowerCase().split(/\s+/).filter(t => t.length > 1);
|
||||
const matched = entities.filter(e => {
|
||||
const content = ((e.properties?.content as string) ?? '').toLowerCase();
|
||||
return terms.some(t => content.includes(t));
|
||||
});
|
||||
|
||||
const results = matched.slice(0, limit).map(e => ({
|
||||
id: e.id,
|
||||
content: (e.properties?.content as string) ?? '',
|
||||
authorId: (e.properties?.authorId as string) ?? e.sharedBy ?? '',
|
||||
authorName: (e.properties?.authorName as string) ?? 'Team member',
|
||||
importance: (e.properties?.importance as string) ?? 'normal',
|
||||
timestamp: e.createdAt,
|
||||
source: 'team',
|
||||
}));
|
||||
|
||||
return { results, count: results.length };
|
||||
} catch {
|
||||
return { results: [], count: 0 };
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
function normalizeTeam(row: TeamRow) {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
ownerId: row.owner_id,
|
||||
created: row.created,
|
||||
updated: row.updated,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeMember(row: MemberRow) {
|
||||
return {
|
||||
userId: row.user_id,
|
||||
role: row.role,
|
||||
displayName: row.display_name,
|
||||
email: row.email,
|
||||
joined: row.joined,
|
||||
};
|
||||
}
|
||||
@@ -1,382 +0,0 @@
|
||||
import type { FastifyInstance, FastifyPluginAsync, FastifyRequest } from 'fastify';
|
||||
import fp from 'fastify-plugin';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import { evaluateExternalMemoryIngress } from '@waggle/core';
|
||||
import { PERSONAL_SCOPE } from '@waggle/memory-contract';
|
||||
import {
|
||||
validateMessageTypeCombo,
|
||||
WaggleDanceDispatcher,
|
||||
type DispatchDeps,
|
||||
} from '@waggle/waggle-dance';
|
||||
import type {
|
||||
CollaborationWorkerRun,
|
||||
WaggleMessage,
|
||||
MessageType,
|
||||
MessageSubtype,
|
||||
} from '@waggle/shared';
|
||||
import { SignalBus } from '../signal-bus.js';
|
||||
import { installWaggleDanceBridge } from '../waggle-dance-bridge.js';
|
||||
|
||||
/**
|
||||
* AI-OS Phase 1B — local-sidecar surface for the WaggleDance v2
|
||||
* cross-tool activity bus.
|
||||
*
|
||||
* Endpoints:
|
||||
*
|
||||
* POST /api/waggle-dance/signal
|
||||
* Body: { type, subtype, content, senderId?, teamId?,
|
||||
* referenceId?, routing? }
|
||||
* Returns: { dispatched, message }
|
||||
*
|
||||
* Normalizes the incoming payload into a full WaggleMessage
|
||||
* (auto-fills id, createdAt, sensible defaults), validates the
|
||||
* type/subtype combo, then dispatches through WaggleDanceDispatcher
|
||||
* with real v2 deps (emit→bus, response→bus).
|
||||
*
|
||||
* GET /api/waggle-dance/signals
|
||||
* Query: { subtype?, tool?, teamId?, limit?, since? }
|
||||
* Returns: WaggleMessage[]
|
||||
*
|
||||
* Returns the in-memory ring buffer snapshot, newest first,
|
||||
* filtered by the optional query params.
|
||||
*
|
||||
* Design notes:
|
||||
*
|
||||
* - The signal bus is created once per server instance and exposed
|
||||
* via `server.signalBus`. Tests can replace it via decoration.
|
||||
* - The dispatcher's emitSignal pushes into the bus AND records the
|
||||
* message (so GET /signals returns it). recordResponse does the
|
||||
* same — responses are also visible in the activity feed.
|
||||
* - Personal-tier eligibility: when teamId is absent, defaults to
|
||||
* `personal::<senderId>` so a user's own bus does not require
|
||||
* a real Teams subscription. This is the moat.
|
||||
* - Model recommendation: stubbed to null in this route (real
|
||||
* wiring lives in Phase 3); dispatcher returns a friendly
|
||||
* "no recommender configured" string.
|
||||
*/
|
||||
|
||||
// Local request schema — relaxed from the cloud sendMessageSchema
|
||||
// because hook senders don't have user-UUID identities. We accept
|
||||
// any non-empty senderId string ('claude-code-hook', 'cursor-hook')
|
||||
// or auto-default to 'local'.
|
||||
const signalRequestSchema = z.object({
|
||||
type: z.enum(['broadcast', 'request', 'response']),
|
||||
subtype: z.enum([
|
||||
'knowledge_check', 'task_delegation', 'skill_request', 'model_recommendation',
|
||||
'knowledge_match', 'task_claim', 'discovery', 'routed_share',
|
||||
'skill_share', 'model_recipe',
|
||||
]),
|
||||
content: z.record(z.unknown()),
|
||||
senderId: z.string().min(1).max(200).optional(),
|
||||
teamId: z.string().min(1).max(200).optional(),
|
||||
referenceId: z.string().min(1).max(200).nullable().optional(),
|
||||
routing: z
|
||||
.array(z.object({ userId: z.string(), reason: z.string() }))
|
||||
.nullable()
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const signalsQuerySchema = z.object({
|
||||
subtype: z.string().optional(),
|
||||
tool: z.string().optional(),
|
||||
teamId: z.string().optional(),
|
||||
limit: z.coerce.number().int().positive().max(1000).optional(),
|
||||
since: z.string().optional(),
|
||||
});
|
||||
|
||||
const QUARANTINED_AGENT_SIGNAL = '[Quarantined agent signal]';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
/** AI-OS Phase 1B signal bus — shared across waggle-dance routes. */
|
||||
signalBus?: SignalBus;
|
||||
}
|
||||
}
|
||||
|
||||
const waggleDanceRoutesImpl: FastifyPluginAsync = async (server) => {
|
||||
// Lazily create the bus on first plugin registration. The decorator
|
||||
// makes it available to other plugins (Phase 1C SSE adapter, tests).
|
||||
// Wrapped with fastify-plugin below so the decoration is visible
|
||||
// on the parent FastifyInstance, not just inside this plugin.
|
||||
if (!server.signalBus) {
|
||||
server.decorate('signalBus', new SignalBus());
|
||||
// Bridge the v2 bus into the legacy /api/waggle/signals stream so
|
||||
// the existing UI surfaces cross-tool activity with zero frontend
|
||||
// changes. Phase 1C wiring.
|
||||
installWaggleDanceBridge(server.signalBus!);
|
||||
}
|
||||
const bus = server.signalBus!;
|
||||
|
||||
// ── POST /api/waggle-dance/signal ─────────────────────────────────
|
||||
server.post('/api/waggle-dance/signal', async (request, reply) => {
|
||||
const parsed = signalRequestSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply
|
||||
.code(400)
|
||||
.send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const body = parsed.data;
|
||||
const runAuth = authenticateRunRequest(server, request);
|
||||
if (runAuth === null) {
|
||||
return reply.code(401).send({ error: 'Unauthorized', code: 'INVALID_RUN_TOKEN' });
|
||||
}
|
||||
|
||||
// Validate type/subtype combo via the protocol module.
|
||||
if (
|
||||
!validateMessageTypeCombo(
|
||||
body.type as MessageType,
|
||||
body.subtype as MessageSubtype,
|
||||
)
|
||||
) {
|
||||
return reply.code(400).send({
|
||||
error: `Invalid type-subtype combination: ${body.type}/${body.subtype}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (runAuth) {
|
||||
const violation = validateRunEnvelope(runAuth, body);
|
||||
if (violation) return reply.code(403).send({ error: 'Forbidden', code: 'RUN_SCOPE_VIOLATION', message: violation });
|
||||
}
|
||||
const senderId = runAuth ? `run::${runAuth.id}` : (body.senderId ?? 'local');
|
||||
const teamId = runAuth ? `room::${runAuth.roomId}` : (body.teamId ?? `personal::${senderId}`);
|
||||
const signalContent = runAuth && isDurableAuthenticatedSignal(
|
||||
body.type as MessageType,
|
||||
body.subtype as MessageSubtype,
|
||||
)
|
||||
? guardAuthenticatedSignalSummary(body.content)
|
||||
: body.content;
|
||||
|
||||
const message: WaggleMessage = {
|
||||
id: randomUUID(),
|
||||
teamId,
|
||||
senderId,
|
||||
type: body.type as MessageType,
|
||||
subtype: body.subtype as MessageSubtype,
|
||||
content: runAuth ? {
|
||||
...signalContent,
|
||||
roomId: runAuth.roomId,
|
||||
runId: runAuth.id,
|
||||
workspaceId: runAuth.workspaceId,
|
||||
} : signalContent,
|
||||
referenceId: body.referenceId ?? null,
|
||||
routing: body.routing ?? null,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
// Real v2 deps: emit→bus, response→bus, recommendModel→null stub.
|
||||
// v1 deps are stubbed locally (the cross-tool bus does not run
|
||||
// the team-internal task_delegation / knowledge_check paths
|
||||
// through this route — those go through the team workspace).
|
||||
const deps: DispatchDeps = {
|
||||
searchMemory: async () => 'memory search not available on local bus',
|
||||
resolveCapability: () => [],
|
||||
spawnWorker: async (task: string, role: string) =>
|
||||
`local bus does not spawn workers (task=${task}, role=${role})`,
|
||||
emitSignal: async (msg) => {
|
||||
bus.record(msg);
|
||||
},
|
||||
recordResponse: async (msg) => {
|
||||
bus.record(msg);
|
||||
},
|
||||
recommendModel: async () => null,
|
||||
};
|
||||
|
||||
const dispatcher = new WaggleDanceDispatcher(deps);
|
||||
const dispatchResult = await dispatcher.dispatch(message);
|
||||
|
||||
if (!dispatchResult.handled) {
|
||||
return reply
|
||||
.code(400)
|
||||
.send({ error: dispatchResult.error, message });
|
||||
}
|
||||
|
||||
// Request handlers execute their local behavior but do not persist the
|
||||
// envelope. Record successful requests once so Room peers can receive and
|
||||
// answer them; broadcasts and responses are recorded by their callbacks.
|
||||
if (message.type === 'request') {
|
||||
bus.record(message);
|
||||
}
|
||||
if (runAuth) recordAuthenticatedRunSignal(server, runAuth, message);
|
||||
|
||||
return reply.code(201).send({
|
||||
dispatched: true,
|
||||
response: dispatchResult.response,
|
||||
message,
|
||||
});
|
||||
});
|
||||
|
||||
// ── GET /api/waggle-dance/signals ─────────────────────────────────
|
||||
server.get('/api/waggle-dance/signals', async (request, reply) => {
|
||||
const parsed = signalsQuerySchema.safeParse(request.query);
|
||||
if (!parsed.success) {
|
||||
return reply
|
||||
.code(400)
|
||||
.send({ error: 'Invalid query', details: parsed.error.flatten() });
|
||||
}
|
||||
const q = parsed.data;
|
||||
const runAuth = authenticateRunRequest(server, request);
|
||||
if (runAuth === null) {
|
||||
return reply.code(401).send({ error: 'Unauthorized', code: 'INVALID_RUN_TOKEN' });
|
||||
}
|
||||
const runTeamId = runAuth ? `room::${runAuth.roomId}` : undefined;
|
||||
if (runTeamId && q.teamId && q.teamId !== runTeamId) {
|
||||
return reply.code(403).send({ error: 'Forbidden', code: 'RUN_SCOPE_VIOLATION' });
|
||||
}
|
||||
|
||||
// Validate subtype against the protocol enum if provided.
|
||||
const allowedSubtypes: MessageSubtype[] = [
|
||||
'knowledge_check', 'task_delegation', 'skill_request', 'model_recommendation',
|
||||
'knowledge_match', 'task_claim', 'discovery', 'routed_share',
|
||||
'skill_share', 'model_recipe',
|
||||
];
|
||||
if (q.subtype && !allowedSubtypes.includes(q.subtype as MessageSubtype)) {
|
||||
return reply.code(400).send({ error: `Unknown subtype: ${q.subtype}` });
|
||||
}
|
||||
|
||||
const signals = bus.query({
|
||||
subtype: q.subtype as MessageSubtype | undefined,
|
||||
tool: q.tool,
|
||||
teamId: runTeamId ?? q.teamId,
|
||||
limit: q.limit,
|
||||
since: q.since,
|
||||
});
|
||||
return reply.code(200).send({ signals, total: signals.length });
|
||||
});
|
||||
};
|
||||
|
||||
function recordAuthenticatedRunSignal(
|
||||
server: FastifyInstance,
|
||||
run: CollaborationWorkerRun,
|
||||
message: WaggleMessage,
|
||||
): void {
|
||||
if (!isDurableAuthenticatedSignal(message.type, message.subtype)) return;
|
||||
const summary = signalSummary(message.content);
|
||||
if (!summary) return;
|
||||
const durableSummary = summary.slice(0, 4_000);
|
||||
const safeSummary = evaluateExternalMemoryIngress({ content: durableSummary }).action === 'allow'
|
||||
? durableSummary
|
||||
: QUARANTINED_AGENT_SIGNAL;
|
||||
const current = server.agentRunRegistry.get(run.id);
|
||||
if (!current || current.kind !== 'worker') return;
|
||||
|
||||
const workspaceFrameIds = { ...(current.memoryRefs.workspaceFrameIds ?? {}) };
|
||||
const rawFrameId = message.content.frameId;
|
||||
const frameId = typeof rawFrameId === 'string' && rawFrameId.trim()
|
||||
? rawFrameId.trim()
|
||||
: typeof rawFrameId === 'number' ? String(rawFrameId) : undefined;
|
||||
const workspaceStored = frameId !== undefined
|
||||
&& message.content.memoryWorkspace === run.workspaceId;
|
||||
if (workspaceStored) {
|
||||
workspaceFrameIds[run.workspaceId] = [
|
||||
...new Set([...(workspaceFrameIds[run.workspaceId] ?? []), frameId]),
|
||||
];
|
||||
}
|
||||
|
||||
server.agentRunRegistry.update(run.id, {
|
||||
...(['queued', 'starting'].includes(current.status) ? { status: 'running' } : {}),
|
||||
progress: { phase: message.subtype, message: safeSummary.slice(0, 500) },
|
||||
result: { summary: safeSummary },
|
||||
memoryRefs: { workspaceFrameIds },
|
||||
});
|
||||
|
||||
// Index the signal in personal memory; the run's memoryRefs follow when the write lands.
|
||||
void server.memory.remember({
|
||||
scope: PERSONAL_SCOPE,
|
||||
text: `[Agent collaboration signal]\nRoom: ${run.roomId}\nRun: ${run.id}\nWorkspace: ${run.workspaceId}\nTool: ${run.executor.toolId ?? 'agent'}\nSubtype: ${message.subtype}\nSummary: ${safeSummary.slice(0, 1_000)}`,
|
||||
kind: 'note',
|
||||
source: 'agent_inferred',
|
||||
origin: 'agent-signals',
|
||||
metadata: {
|
||||
messageId: message.id,
|
||||
roomId: run.roomId,
|
||||
runId: run.id,
|
||||
workspaceId: run.workspaceId,
|
||||
toolId: run.executor.toolId ?? null,
|
||||
subtype: message.subtype,
|
||||
},
|
||||
}).then(([change]) => {
|
||||
const latest = server.agentRunRegistry.get(run.id);
|
||||
if (!change || !latest) return;
|
||||
const personalFrameIds = [...new Set([...latest.memoryRefs.personalFrameIds, change.record.id])];
|
||||
server.agentRunRegistry.update(run.id, {
|
||||
memoryRefs: {
|
||||
status: workspaceStored ? 'complete' : latest.memoryRefs.status,
|
||||
personalFrameIds,
|
||||
},
|
||||
});
|
||||
}).catch((err: unknown) => {
|
||||
server.log.warn({ err, runId: run.id }, 'failed to index authenticated agent signal');
|
||||
});
|
||||
}
|
||||
|
||||
function isDurableAuthenticatedSignal(type: MessageType, subtype: MessageSubtype): boolean {
|
||||
return type !== 'request' && subtype !== 'task_claim';
|
||||
}
|
||||
|
||||
function guardAuthenticatedSignalSummary(content: Record<string, unknown>): Record<string, unknown> {
|
||||
for (const key of ['summary', 'result', 'text', 'topic', 'message']) {
|
||||
const value = content[key];
|
||||
if (typeof value !== 'string' || !value.trim()) continue;
|
||||
const reflectedSummary = value.trim();
|
||||
const durableSummary = reflectedSummary.slice(0, 4_000);
|
||||
const durableDecision = evaluateExternalMemoryIngress({ content: durableSummary });
|
||||
const reflectedDecision = reflectedSummary === durableSummary
|
||||
? durableDecision
|
||||
: evaluateExternalMemoryIngress({ content: reflectedSummary });
|
||||
return durableDecision.action === 'allow' && reflectedDecision.action === 'allow'
|
||||
? content
|
||||
: { ...content, [key]: QUARANTINED_AGENT_SIGNAL };
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
function signalSummary(content: Record<string, unknown>): string | undefined {
|
||||
for (const key of ['summary', 'result', 'text', 'topic', 'message']) {
|
||||
const value = content[key];
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function authenticateRunRequest(
|
||||
server: FastifyInstance,
|
||||
request: FastifyRequest,
|
||||
): CollaborationWorkerRun | undefined | null {
|
||||
const raw = request.headers['x-waggle-run-token'];
|
||||
if (raw === undefined) return undefined;
|
||||
if (typeof raw !== 'string') return null;
|
||||
return server.agentRunRegistry?.authenticateCredential(raw) ?? null;
|
||||
}
|
||||
|
||||
function validateRunEnvelope(
|
||||
run: CollaborationWorkerRun,
|
||||
body: {
|
||||
senderId?: string;
|
||||
teamId?: string;
|
||||
content: Record<string, unknown>;
|
||||
},
|
||||
): string | undefined {
|
||||
if (body.senderId && body.senderId !== `run::${run.id}`) return 'senderId is outside the credential scope';
|
||||
if (body.teamId && body.teamId !== `room::${run.roomId}`) return 'teamId is outside the credential scope';
|
||||
const reserved: Array<[string, string]> = [
|
||||
['roomId', run.roomId], ['runId', run.id], ['workspaceId', run.workspaceId],
|
||||
];
|
||||
for (const [key, expected] of reserved) {
|
||||
const value = body.content[key];
|
||||
if (value !== undefined && value !== expected) return `${key} is outside the credential scope`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin wrapped with fastify-plugin so the `signalBus` decoration
|
||||
* propagates to the parent FastifyInstance. Without this wrapper,
|
||||
* Fastify's default encapsulation would scope the decoration to
|
||||
* this plugin only, and tests / other plugins (Phase 1C SSE adapter)
|
||||
* could not access the shared bus.
|
||||
*/
|
||||
export const waggleDanceRoutes: FastifyPluginAsync = fp(waggleDanceRoutesImpl, {
|
||||
name: 'waggle-dance-routes',
|
||||
});
|
||||
@@ -4,15 +4,13 @@ import path from 'node:path';
|
||||
import Database from 'better-sqlite3';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { MindDB, WaggleConfig, createFileStore, reconcileFtsIndex } from '@waggle/core';
|
||||
import { MindDB, createFileStore, reconcileFtsIndex } from '@waggle/core';
|
||||
import { assertSafeSegment } from './validate.js';
|
||||
import { validateBody } from '../../validate-body.js';
|
||||
import { getBoundTeamServer } from '../team-server-binding.js';
|
||||
import { fetchTeamServer } from '../team-server-egress.js';
|
||||
|
||||
/** POST /api/workspaces body — create a workspace (name + group required). Model
|
||||
* format + local-path existence get deeper checks in the handler; enum fields
|
||||
* are constrained here so a bad `tone`/`storageType`/`teamRole` 400s cleanly. */
|
||||
* are constrained here so a bad `tone`/`storageType` 400s cleanly. */
|
||||
const createWorkspaceSchema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
group: z.string().min(1).max(200),
|
||||
@@ -26,10 +24,6 @@ const createWorkspaceSchema = z.object({
|
||||
storageType: z.enum(['virtual', 'local', 'team']).optional(),
|
||||
storagePath: z.string().optional(),
|
||||
storageConfig: z.record(z.string(), z.unknown()).optional(),
|
||||
teamId: z.string().optional(),
|
||||
teamServerUrl: z.string().optional(),
|
||||
teamRole: z.enum(['owner', 'admin', 'member', 'viewer']).optional(),
|
||||
teamUserId: z.string().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -322,13 +316,9 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
|
||||
storageType?: 'virtual' | 'local' | 'team';
|
||||
storagePath?: string;
|
||||
storageConfig?: Record<string, unknown>;
|
||||
teamId?: string;
|
||||
teamServerUrl?: string;
|
||||
teamRole?: 'owner' | 'admin' | 'member' | 'viewer';
|
||||
teamUserId?: string;
|
||||
};
|
||||
}>('/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;
|
||||
const { name, group, icon, model, personaId, directory, tone, storageType, storagePath, storageConfig } = request.body;
|
||||
|
||||
// BUG-R3-03: Validate model ID if provided
|
||||
if (model && !isValidModelId(model)) {
|
||||
@@ -358,23 +348,6 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
|
||||
}
|
||||
}
|
||||
|
||||
let boundTeamServerUrl = teamServerUrl;
|
||||
let teamServerToken: string | undefined;
|
||||
const hasTeamId = typeof teamId === 'string' && teamId.trim().length > 0;
|
||||
const hasTeamServerUrl = typeof teamServerUrl === 'string' && teamServerUrl.trim().length > 0;
|
||||
if ((teamId !== undefined || teamServerUrl !== undefined) && (!hasTeamId || !hasTeamServerUrl)) {
|
||||
return reply.status(400).send({ error: 'Team workspaces require both teamId and teamServerUrl' });
|
||||
}
|
||||
if (teamId && teamServerUrl) {
|
||||
const configuredTeamServer = new WaggleConfig(server.localConfig.dataDir).getTeamServer();
|
||||
const boundTeamServer = getBoundTeamServer(teamServerUrl, configuredTeamServer);
|
||||
if (!boundTeamServer) {
|
||||
return reply.status(400).send({ error: 'Team workspace URL must match the configured Team server' });
|
||||
}
|
||||
boundTeamServerUrl = boundTeamServer.url;
|
||||
teamServerToken = boundTeamServer.token;
|
||||
}
|
||||
|
||||
let preparedLocalProvider: { ensureStructure?: () => void } | undefined;
|
||||
const createdLocalDirectories: string[] = [];
|
||||
const rollbackPreparedLocalDirectories = () => {
|
||||
@@ -432,7 +405,6 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
|
||||
try {
|
||||
const created = server.workspaceManager.create({
|
||||
name, group, icon, model, personaId, directory, tone,
|
||||
teamId, teamServerUrl: boundTeamServerUrl, teamRole, teamUserId,
|
||||
...(resolvedTemplateId && { templateId: resolvedTemplateId }),
|
||||
});
|
||||
createdWorkspaceId = created.id;
|
||||
@@ -541,33 +513,6 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
|
||||
}).catch(() => { /* pack install is best-effort */ });
|
||||
}
|
||||
|
||||
// Register workspace on team server (fire-and-forget)
|
||||
if (teamId && boundTeamServerUrl && teamServerToken) {
|
||||
try {
|
||||
fetchTeamServer(`${boundTeamServerUrl}/api/teams/${teamId}/entities`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${teamServerToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
entityType: 'workspace',
|
||||
name: ws.id,
|
||||
properties: {
|
||||
displayName: ws.name,
|
||||
group: ws.group,
|
||||
model: ws.model,
|
||||
personaId: ws.personaId,
|
||||
createdBy: teamUserId ?? 'local-user',
|
||||
},
|
||||
}),
|
||||
signal: AbortSignal.timeout(5000),
|
||||
}).catch(err => {
|
||||
log.warn(`[waggle] Team workspace registration failed:`, err.message);
|
||||
});
|
||||
} catch { /* team registration is best-effort */ }
|
||||
}
|
||||
|
||||
return reply.status(201).send(ws);
|
||||
});
|
||||
|
||||
|
||||
@@ -40,6 +40,13 @@ export interface SignalFilter {
|
||||
|
||||
export type SignalSubscriber = (signal: WaggleMessage) => void;
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
/** Room signal bus shared by the local collaboration routes; decorated by buildLocalServer. */
|
||||
signalBus?: SignalBus;
|
||||
}
|
||||
}
|
||||
|
||||
export class SignalBus {
|
||||
private buffer: WaggleMessage[] = [];
|
||||
private subscribers: Set<SignalSubscriber> = new Set();
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import type { TeamServerConfig } from '@waggle/core';
|
||||
import { normalizeTeamServerBaseUrl } from './team-server-egress.js';
|
||||
|
||||
/** Bind a stored workspace destination to the currently configured Team credentials. */
|
||||
export function getBoundTeamServer(
|
||||
workspaceUrl: string | undefined,
|
||||
configured: TeamServerConfig | null,
|
||||
): TeamServerConfig | null {
|
||||
if (!workspaceUrl || !configured?.url) return null;
|
||||
const workspaceBaseUrl = normalizeTeamServerBaseUrl(workspaceUrl);
|
||||
const configuredBaseUrl = normalizeTeamServerBaseUrl(configured.url);
|
||||
if (!workspaceBaseUrl || !configuredBaseUrl || workspaceBaseUrl !== configuredBaseUrl) return null;
|
||||
return { ...configured, url: configuredBaseUrl };
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { allowLocalFromEnv, safeFetch } from '@waggle/agent';
|
||||
|
||||
function hasAllowedProtocol(url: URL, allowLocal: boolean): boolean {
|
||||
const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
||||
const isExplicitLoopback = hostname === 'localhost'
|
||||
|| hostname.endsWith('.localhost')
|
||||
|| hostname === '::1'
|
||||
|| /^127(?:\.\d{1,3}){3}$/.test(hostname);
|
||||
return url.protocol === 'https:' || (url.protocol === 'http:' && allowLocal && isExplicitLoopback);
|
||||
}
|
||||
|
||||
export function normalizeTeamServerBaseUrl(
|
||||
value: string,
|
||||
allowLocal = allowLocalFromEnv(),
|
||||
): string | null {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.username || url.password || url.search || url.hash || !hasAllowedProtocol(url, allowLocal)) {
|
||||
return null;
|
||||
}
|
||||
return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchTeamServer(url: string, init: RequestInit = {}): Promise<Response> {
|
||||
const parsed = new URL(url);
|
||||
const allowLocal = allowLocalFromEnv();
|
||||
if (parsed.username || parsed.password || parsed.hash || !hasAllowedProtocol(parsed, allowLocal)) {
|
||||
throw new Error('Blocked insecure Team server URL');
|
||||
}
|
||||
return safeFetch(url, init, { allowLocal, maxRedirects: 0 });
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
/**
|
||||
* AI-OS Phase 1C — bridge the new WaggleDance v2 signal bus into the
|
||||
* legacy `/api/waggle/signals` stream consumed by the WaggleDanceApp UI.
|
||||
*
|
||||
* Why a bridge:
|
||||
*
|
||||
* The existing UI hook (`useWaggleDance`) talks to `/api/waggle/signals`
|
||||
* + `/api/waggle/stream` (SSE). Those endpoints have a higher-level
|
||||
* signal shape (`{type, workspaceId, content, metadata, timestamp,
|
||||
* acknowledged}`) where `type` is one of five UX categories —
|
||||
* discovery / handoff / insight / alert / coordination.
|
||||
*
|
||||
* The new v2 bus uses the protocol shape (`WaggleMessage` with
|
||||
* `subtype` of one of ten Waggle Dance protocol subtypes). To let
|
||||
* the UI surface cross-tool activity with NO frontend changes, we
|
||||
* subscribe the bus and re-emit each signal through the legacy
|
||||
* `emitWaggleSignal` with a mapped shape.
|
||||
*
|
||||
* The mapping is many-to-five:
|
||||
*
|
||||
* discovery / knowledge_check / skill_request → 'discovery'
|
||||
* task_delegation / skill_share / routed_share → 'handoff'
|
||||
* knowledge_match → 'insight'
|
||||
* task_claim / model_recipe / model_recommendation → 'coordination'
|
||||
* (content.priority === 'critical') → 'alert' (overrides)
|
||||
*
|
||||
* Provenance is preserved in `metadata`:
|
||||
* { subtype, senderId, tool, teamId, referenceId, routing }
|
||||
*
|
||||
* Tests cover both the mapping (unit) and the end-to-end flow
|
||||
* (POST /api/waggle-dance/signal → GET /api/waggle/signals).
|
||||
*/
|
||||
|
||||
import type { WaggleMessage, MessageSubtype } from '@waggle/shared';
|
||||
import { SignalBus } from './signal-bus.js';
|
||||
import { emitWaggleSignal } from './routes/waggle-signals.js';
|
||||
|
||||
/**
|
||||
* Categorize a Waggle Dance subtype into one of the five UX
|
||||
* signal categories the existing UI knows how to render.
|
||||
*
|
||||
* Exported for unit testing.
|
||||
*/
|
||||
export function categorizeSubtype(
|
||||
subtype: MessageSubtype,
|
||||
): 'discovery' | 'handoff' | 'insight' | 'alert' | 'coordination' {
|
||||
switch (subtype) {
|
||||
case 'discovery':
|
||||
case 'knowledge_check':
|
||||
case 'skill_request':
|
||||
return 'discovery';
|
||||
case 'task_delegation':
|
||||
case 'skill_share':
|
||||
case 'routed_share':
|
||||
return 'handoff';
|
||||
case 'knowledge_match':
|
||||
return 'insight';
|
||||
case 'task_claim':
|
||||
case 'model_recipe':
|
||||
case 'model_recommendation':
|
||||
return 'coordination';
|
||||
default:
|
||||
// Defense in depth — runtime-malformed subtypes get a safe
|
||||
// bucket so the UI doesn't drop them silently.
|
||||
return 'coordination';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the human-readable `content` field for the legacy signal
|
||||
* from a v2 WaggleMessage. The UI shows this as the primary text.
|
||||
*/
|
||||
export function buildLegacyContent(message: WaggleMessage): string {
|
||||
const { content, subtype } = message;
|
||||
// Prefer a topic / title / query field if present, then fall back
|
||||
// to a structural summary.
|
||||
const topic =
|
||||
(content.topic as string) ??
|
||||
(content.title as string) ??
|
||||
(content.query as string) ??
|
||||
(content.task as string) ??
|
||||
(content.skill as string) ??
|
||||
null;
|
||||
if (topic) return `${subtype}: ${topic}`;
|
||||
// For broadcasts/responses without a topic, summarize the keys.
|
||||
const keys = Object.keys(content);
|
||||
if (keys.length === 0) return `${subtype}`;
|
||||
return `${subtype} (${keys.slice(0, 3).join(', ')})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine the priority for the legacy signal. `content.priority`
|
||||
* wins if present and valid; otherwise infer a default from subtype.
|
||||
*/
|
||||
function inferPriority(message: WaggleMessage): 'low' | 'normal' | 'high' | 'critical' {
|
||||
const explicit = message.content.priority;
|
||||
if (
|
||||
explicit === 'low' ||
|
||||
explicit === 'normal' ||
|
||||
explicit === 'high' ||
|
||||
explicit === 'critical'
|
||||
) {
|
||||
return explicit;
|
||||
}
|
||||
// Importance hint from hooks may surface as content.importance
|
||||
const importance = message.content.importance;
|
||||
if (importance === 'high') return 'high';
|
||||
if (importance === 'critical') return 'critical';
|
||||
return 'normal';
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to the v2 signal bus and re-emit each signal through
|
||||
* the legacy `emitWaggleSignal` so the existing UI sees cross-tool
|
||||
* activity with zero frontend changes.
|
||||
*
|
||||
* Returns the unsubscribe function so the bridge can be torn down
|
||||
* (used in tests).
|
||||
*/
|
||||
export function installWaggleDanceBridge(bus: SignalBus): () => void {
|
||||
return bus.subscribe((msg) => {
|
||||
const priority = inferPriority(msg);
|
||||
// Critical priority always renders as 'alert' regardless of subtype.
|
||||
const type = priority === 'critical' ? 'alert' : categorizeSubtype(msg.subtype);
|
||||
emitWaggleSignal({
|
||||
type: `waggle-dance:${type}`,
|
||||
workspaceId: msg.teamId,
|
||||
content: buildLegacyContent(msg),
|
||||
metadata: {
|
||||
subtype: msg.subtype,
|
||||
senderId: msg.senderId,
|
||||
tool: msg.content.tool ?? null,
|
||||
teamId: msg.teamId,
|
||||
referenceId: msg.referenceId,
|
||||
routing: msg.routing,
|
||||
priority,
|
||||
// Keep the protocol message verbatim for any UI that wants
|
||||
// to drill into the raw protocol payload.
|
||||
protocolMessage: msg,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
/**
|
||||
* WsTeamClient — WebSocket client connecting local server to team server
|
||||
* for real-time Waggle Dance agent-to-agent communication.
|
||||
*
|
||||
* Protocol:
|
||||
* 1. Connect to ws://{serverUrl}/ws
|
||||
* 2. Send: { type: 'authenticate', token: '...' }
|
||||
* 3. Receive: { type: 'authenticated', userId: '...' }
|
||||
* 4. Send: { type: 'join_team', teamSlug: '...' }
|
||||
* 5. Receive: { type: 'joined_team', teamSlug: '...' }
|
||||
* 6. Receive: { type: 'waggle_message', message: WaggleMessage }
|
||||
*/
|
||||
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { WebSocket as WsWebSocket, RawData } from 'ws';
|
||||
import { createLogger } from './logger.js';
|
||||
const log = createLogger('team-ws');
|
||||
|
||||
export interface WsTeamClientConfig {
|
||||
serverUrl: string;
|
||||
token: string;
|
||||
teamSlug: string;
|
||||
}
|
||||
|
||||
/** Inbound events from the team WebSocket server. */
|
||||
interface TeamServerEvent {
|
||||
type: string;
|
||||
teamSlug?: string;
|
||||
message?: unknown;
|
||||
}
|
||||
|
||||
export class WsTeamClient extends EventEmitter {
|
||||
private config: WsTeamClientConfig;
|
||||
private ws: WsWebSocket | null = null;
|
||||
private reconnectDelay = 1000;
|
||||
private maxReconnectDelay = 30000;
|
||||
private shouldReconnect = true;
|
||||
private _authenticated = false;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor(config: WsTeamClientConfig) {
|
||||
super();
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
if (this.ws) return; // Already connecting/connected
|
||||
|
||||
try {
|
||||
const { default: WebSocket } = await import('ws');
|
||||
const url = this.config.serverUrl.replace(/^http/, 'ws') + '/ws';
|
||||
|
||||
this.ws = new WebSocket(url);
|
||||
|
||||
this.ws.on('open', () => {
|
||||
this.reconnectDelay = 1000; // Reset backoff on success
|
||||
// Step 1: Authenticate
|
||||
this.send({ type: 'authenticate', token: this.config.token });
|
||||
});
|
||||
|
||||
this.ws.on('message', (data: RawData) => {
|
||||
try {
|
||||
const event = JSON.parse(data.toString()) as TeamServerEvent;
|
||||
this.handleEvent(event);
|
||||
} catch { /* invalid JSON — ignore */ }
|
||||
});
|
||||
|
||||
this.ws.on('close', () => {
|
||||
this._authenticated = false;
|
||||
this.ws = null;
|
||||
this.emit('disconnect');
|
||||
this.scheduleReconnect();
|
||||
});
|
||||
|
||||
this.ws.on('error', (err: Error) => {
|
||||
log.warn('WS team client error:', err.message);
|
||||
// 'close' event will follow — reconnect happens there
|
||||
});
|
||||
} catch (err) {
|
||||
log.warn('WS team client connect failed:', (err as Error).message);
|
||||
this.ws = null;
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private handleEvent(event: TeamServerEvent): void {
|
||||
switch (event.type) {
|
||||
case 'authenticated':
|
||||
this._authenticated = true;
|
||||
// Step 2: Join team
|
||||
this.send({ type: 'join_team', teamSlug: this.config.teamSlug });
|
||||
break;
|
||||
case 'joined_team':
|
||||
this.emit('connected', { teamSlug: event.teamSlug });
|
||||
break;
|
||||
case 'waggle_message':
|
||||
this.emit('message', event.message);
|
||||
break;
|
||||
case 'error':
|
||||
log.warn('WS team server error:', event.message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (!this.shouldReconnect) return;
|
||||
if (this.reconnectTimer) return; // Already scheduled
|
||||
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
this.connect().catch(() => { /* handled in connect */ });
|
||||
}, this.reconnectDelay);
|
||||
|
||||
this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay);
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.shouldReconnect = false;
|
||||
this._authenticated = false;
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
if (this.ws) {
|
||||
try { this.ws.close(); } catch { /* ignore */ }
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
|
||||
isConnected(): boolean {
|
||||
return this._authenticated && this.ws?.readyState === 1; // WebSocket.OPEN
|
||||
}
|
||||
|
||||
send(event: unknown): void {
|
||||
if (this.ws?.readyState === 1) {
|
||||
this.ws.send(JSON.stringify(event));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user