feat: join request claim secrets, onboarding API, and company branding

Add secure claim secret flow for agent join requests with timing-safe
comparison, expiry, and one-time use. Expose machine-readable onboarding
manifests and skill index API endpoints. Add company brand color with
hex validation, pattern icon generation, and settings page integration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Forgotten
2026-02-26 16:33:20 -06:00
parent 9e89ca4a9e
commit e2c5b6698c
19 changed files with 6144 additions and 28 deletions

View File

@@ -196,3 +196,12 @@ pnpm paperclip dashboard get
```
See full command reference in `doc/CLI.md`.
## OpenClaw Invite Onboarding Endpoints
Agent-oriented invite onboarding now exposes machine-readable API docs:
- `GET /api/invites/:token` returns invite summary plus onboarding and skills index links.
- `GET /api/invites/:token/onboarding` returns onboarding manifest details (registration endpoint, claim endpoint template, skill install hints).
- `GET /api/skills/index` lists available skill documents.
- `GET /api/skills/paperclip` returns the Paperclip heartbeat skill markdown.

View File

@@ -0,0 +1 @@
ALTER TABLE "companies" ADD COLUMN "brand_color" text;

View File

@@ -0,0 +1,3 @@
ALTER TABLE "join_requests" ADD COLUMN "claim_secret_hash" text;--> statement-breakpoint
ALTER TABLE "join_requests" ADD COLUMN "claim_secret_expires_at" timestamp with time zone;--> statement-breakpoint
ALTER TABLE "join_requests" ADD COLUMN "claim_secret_consumed_at" timestamp with time zone;

File diff suppressed because it is too large Load Diff

View File

@@ -155,6 +155,20 @@
"when": 1772122471656,
"tag": "0021_chief_vindicator",
"breakpoints": true
},
{
"idx": 22,
"version": "7",
"when": 1772186400000,
"tag": "0022_company_brand_color",
"breakpoints": true
},
{
"idx": 23,
"version": "7",
"when": 1772139727599,
"tag": "0023_fair_lethal_legion",
"breakpoints": true
}
]
}

View File

@@ -14,6 +14,7 @@ export const companies = pgTable(
requireBoardApprovalForNewAgents: boolean("require_board_approval_for_new_agents")
.notNull()
.default(true),
brandColor: text("brand_color"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},

View File

@@ -18,6 +18,9 @@ export const joinRequests = pgTable(
adapterType: text("adapter_type"),
capabilities: text("capabilities"),
agentDefaultsPayload: jsonb("agent_defaults_payload").$type<Record<string, unknown> | null>(),
claimSecretHash: text("claim_secret_hash"),
claimSecretExpiresAt: timestamp("claim_secret_expires_at", { withTimezone: true }),
claimSecretConsumedAt: timestamp("claim_secret_consumed_at", { withTimezone: true }),
createdAgentId: uuid("created_agent_id").references(() => agents.id),
approvedByUserId: text("approved_by_user_id"),
approvedAt: timestamp("approved_at", { withTimezone: true }),

View File

@@ -181,6 +181,7 @@ export {
createCompanyInviteSchema,
acceptInviteSchema,
listJoinRequestsQuerySchema,
claimJoinRequestApiKeySchema,
updateMemberPermissionsSchema,
updateUserCompanyAccessSchema,
type CreateCostEvent,
@@ -189,6 +190,7 @@ export {
type CreateCompanyInvite,
type AcceptInvite,
type ListJoinRequestsQuery,
type ClaimJoinRequestApiKey,
type UpdateMemberPermissions,
type UpdateUserCompanyAccess,
} from "./validators/index.js";

View File

@@ -1,4 +1,5 @@
import type {
AgentAdapterType,
InstanceUserRole,
InviteJoinType,
InviteType,
@@ -57,9 +58,11 @@ export interface JoinRequest {
requestingUserId: string | null;
requestEmailSnapshot: string | null;
agentName: string | null;
adapterType: string | null;
adapterType: AgentAdapterType | null;
capabilities: string | null;
agentDefaultsPayload: Record<string, unknown> | null;
claimSecretExpiresAt: Date | null;
claimSecretConsumedAt: Date | null;
createdAgentId: string | null;
approvedByUserId: string | null;
approvedAt: Date | null;

View File

@@ -10,6 +10,7 @@ export interface Company {
budgetMonthlyCents: number;
spentMonthlyCents: number;
requireBoardApprovalForNewAgents: boolean;
brandColor: string | null;
createdAt: Date;
updatedAt: Date;
}

View File

@@ -1,5 +1,6 @@
import { z } from "zod";
import {
AGENT_ADAPTER_TYPES,
INVITE_JOIN_TYPES,
JOIN_REQUEST_STATUSES,
JOIN_REQUEST_TYPES,
@@ -17,7 +18,7 @@ export type CreateCompanyInvite = z.infer<typeof createCompanyInviteSchema>;
export const acceptInviteSchema = z.object({
requestType: z.enum(JOIN_REQUEST_TYPES),
agentName: z.string().min(1).max(120).optional(),
adapterType: z.string().min(1).max(120).optional(),
adapterType: z.enum(AGENT_ADAPTER_TYPES).optional(),
capabilities: z.string().max(4000).optional().nullable(),
agentDefaultsPayload: z.record(z.string(), z.unknown()).optional().nullable(),
});
@@ -31,6 +32,12 @@ export const listJoinRequestsQuerySchema = z.object({
export type ListJoinRequestsQuery = z.infer<typeof listJoinRequestsQuerySchema>;
export const claimJoinRequestApiKeySchema = z.object({
claimSecret: z.string().min(16).max(256),
});
export type ClaimJoinRequestApiKey = z.infer<typeof claimJoinRequestApiKeySchema>;
export const updateMemberPermissionsSchema = z.object({
grants: z.array(
z.object({

View File

@@ -15,6 +15,7 @@ export const updateCompanySchema = createCompanySchema
status: z.enum(COMPANY_STATUSES).optional(),
spentMonthlyCents: z.number().int().nonnegative().optional(),
requireBoardApprovalForNewAgents: z.boolean().optional(),
brandColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(),
});
export type UpdateCompany = z.infer<typeof updateCompanySchema>;

View File

@@ -102,11 +102,13 @@ export {
createCompanyInviteSchema,
acceptInviteSchema,
listJoinRequestsQuerySchema,
claimJoinRequestApiKeySchema,
updateMemberPermissionsSchema,
updateUserCompanyAccessSchema,
type CreateCompanyInvite,
type AcceptInvite,
type ListJoinRequestsQuery,
type ClaimJoinRequestApiKey,
type UpdateMemberPermissions,
type UpdateUserCompanyAccess,
} from "./access.js";

View File

@@ -1,4 +1,7 @@
import { createHash, randomBytes } from "node:crypto";
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { Router } from "express";
import type { Request } from "express";
import { and, eq, isNull, desc } from "drizzle-orm";
@@ -11,6 +14,7 @@ import {
} from "@paperclip/db";
import {
acceptInviteSchema,
claimJoinRequestApiKeySchema,
createCompanyInviteSchema,
listJoinRequestsQuerySchema,
updateMemberPermissionsSchema,
@@ -31,6 +35,106 @@ function createInviteToken() {
return `pcp_invite_${randomBytes(24).toString("hex")}`;
}
function createClaimSecret() {
return `pcp_claim_${randomBytes(24).toString("hex")}`;
}
function tokenHashesMatch(left: string, right: string) {
const leftBytes = Buffer.from(left, "utf8");
const rightBytes = Buffer.from(right, "utf8");
return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes);
}
function requestBaseUrl(req: Request) {
const forwardedProto = req.header("x-forwarded-proto");
const proto = forwardedProto?.split(",")[0]?.trim() || req.protocol || "http";
const host = req.header("x-forwarded-host")?.split(",")[0]?.trim() || req.header("host");
if (!host) return "";
return `${proto}://${host}`;
}
function readSkillMarkdown(skillName: string): string | null {
const normalized = skillName.trim().toLowerCase();
if (normalized !== "paperclip" && normalized !== "paperclip-create-agent") return null;
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
const candidates = [
path.resolve(process.cwd(), "skills", normalized, "SKILL.md"),
path.resolve(moduleDir, "../../../skills", normalized, "SKILL.md"),
];
for (const skillPath of candidates) {
try {
return fs.readFileSync(skillPath, "utf8");
} catch {
// Continue to next candidate.
}
}
return null;
}
function toJoinRequestResponse(row: typeof joinRequests.$inferSelect) {
const { claimSecretHash: _claimSecretHash, ...safe } = row;
return safe;
}
function toInviteSummaryResponse(req: Request, token: string, invite: typeof invites.$inferSelect) {
const baseUrl = requestBaseUrl(req);
const onboardingPath = `/api/invites/${token}/onboarding`;
return {
id: invite.id,
companyId: invite.companyId,
inviteType: invite.inviteType,
allowedJoinTypes: invite.allowedJoinTypes,
expiresAt: invite.expiresAt,
onboardingPath,
onboardingUrl: baseUrl ? `${baseUrl}${onboardingPath}` : onboardingPath,
skillIndexPath: "/api/skills/index",
skillIndexUrl: baseUrl ? `${baseUrl}/api/skills/index` : "/api/skills/index",
};
}
function buildInviteOnboardingManifest(req: Request, token: string, invite: typeof invites.$inferSelect) {
const baseUrl = requestBaseUrl(req);
const skillPath = "/api/skills/paperclip";
const skillUrl = baseUrl ? `${baseUrl}${skillPath}` : skillPath;
const registrationEndpointPath = `/api/invites/${token}/accept`;
const registrationEndpointUrl = baseUrl ? `${baseUrl}${registrationEndpointPath}` : registrationEndpointPath;
return {
invite: toInviteSummaryResponse(req, token, invite),
onboarding: {
instructions:
"Join as an agent, save your one-time claim secret, wait for board approval, then claim your API key and install the Paperclip skill before starting heartbeat loops.",
recommendedAdapterType: "openclaw",
requiredFields: {
requestType: "agent",
agentName: "Display name for this agent",
adapterType: "Use 'openclaw' for OpenClaw webhook-based agents",
capabilities: "Optional capability summary",
agentDefaultsPayload:
"Optional adapter config such as url/method/headers/webhookAuthHeader for OpenClaw callback endpoint",
},
registrationEndpoint: {
method: "POST",
path: registrationEndpointPath,
url: registrationEndpointUrl,
},
claimEndpointTemplate: {
method: "POST",
path: "/api/join-requests/{requestId}/claim-api-key",
body: {
claimSecret: "one-time claim secret returned when the join request is created",
},
},
skill: {
name: "paperclip",
path: skillPath,
url: skillUrl,
installPath: "~/.openclaw/skills/paperclip/SKILL.md",
},
},
};
}
function requestIp(req: Request) {
const forwarded = req.header("x-forwarded-for");
if (forwarded) {
@@ -150,6 +254,22 @@ export function accessRoutes(db: Db) {
if (!allowed) throw forbidden("Permission denied");
}
router.get("/skills/index", (_req, res) => {
res.json({
skills: [
{ name: "paperclip", path: "/api/skills/paperclip" },
{ name: "paperclip-create-agent", path: "/api/skills/paperclip-create-agent" },
],
});
});
router.get("/skills/:skillName", (req, res) => {
const skillName = (req.params.skillName as string).trim().toLowerCase();
const markdown = readSkillMarkdown(skillName);
if (!markdown) throw notFound("Skill not found");
res.type("text/markdown").send(markdown);
});
router.post(
"/companies/:companyId/invites",
validate(createCompanyInviteSchema),
@@ -206,13 +326,22 @@ export function accessRoutes(db: Db) {
throw notFound("Invite not found");
}
res.json({
id: invite.id,
companyId: invite.companyId,
inviteType: invite.inviteType,
allowedJoinTypes: invite.allowedJoinTypes,
expiresAt: invite.expiresAt,
res.json(toInviteSummaryResponse(req, token, invite));
});
router.get("/invites/:token/onboarding", async (req, res) => {
const token = (req.params.token as string).trim();
if (!token) throw notFound("Invite not found");
const invite = await db
.select()
.from(invites)
.where(eq(invites.tokenHash, hashToken(token)))
.then((rows) => rows[0] ?? null);
if (!invite || invite.revokedAt || inviteExpired(invite)) {
throw notFound("Invite not found");
}
res.json(buildInviteOnboardingManifest(req, token, invite));
});
router.post("/invites/:token/accept", validate(acceptInviteSchema), async (req, res) => {
@@ -272,6 +401,12 @@ export function accessRoutes(db: Db) {
throw badRequest("agentName is required for agent join requests");
}
const claimSecret = requestType === "agent" ? createClaimSecret() : null;
const claimSecretHash = claimSecret ? hashToken(claimSecret) : null;
const claimSecretExpiresAt = claimSecret
? new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
: null;
const actorEmail = requestType === "human" ? await resolveActorEmail(db, req) : null;
const created = await db.transaction(async (tx) => {
await tx
@@ -293,6 +428,8 @@ export function accessRoutes(db: Db) {
adapterType: requestType === "agent" ? req.body.adapterType ?? null : null,
capabilities: requestType === "agent" ? req.body.capabilities ?? null : null,
agentDefaultsPayload: requestType === "agent" ? req.body.agentDefaultsPayload ?? null : null,
claimSecretHash,
claimSecretExpiresAt,
})
.returning()
.then((rows) => rows[0]);
@@ -312,7 +449,18 @@ export function accessRoutes(db: Db) {
details: { requestType, requestIp: created.requestIp },
});
res.status(202).json(created);
const response = toJoinRequestResponse(created);
if (claimSecret) {
const onboardingManifest = buildInviteOnboardingManifest(req, token, invite);
res.status(202).json({
...response,
claimSecret,
claimApiKeyPath: `/api/join-requests/${created.id}/claim-api-key`,
onboarding: onboardingManifest.onboarding,
});
return;
}
res.status(202).json(response);
});
router.post("/invites/:inviteId/revoke", async (req, res) => {
@@ -363,7 +511,7 @@ export function accessRoutes(db: Db) {
if (query.requestType && row.requestType !== query.requestType) return false;
return true;
});
res.json(filtered);
res.json(filtered.map(toJoinRequestResponse));
});
router.post("/companies/:companyId/join-requests/:requestId/approve", async (req, res) => {
@@ -447,7 +595,7 @@ export function accessRoutes(db: Db) {
details: { requestType: existing.requestType, createdAgentId },
});
res.json(approved);
res.json(toJoinRequestResponse(approved));
});
router.post("/companies/:companyId/join-requests/:requestId/reject", async (req, res) => {
@@ -485,11 +633,12 @@ export function accessRoutes(db: Db) {
details: { requestType: existing.requestType },
});
res.json(rejected);
res.json(toJoinRequestResponse(rejected));
});
router.post("/join-requests/:requestId/claim-api-key", async (req, res) => {
router.post("/join-requests/:requestId/claim-api-key", validate(claimJoinRequestApiKeySchema), async (req, res) => {
const requestId = req.params.requestId as string;
const presentedClaimSecretHash = hashToken(req.body.claimSecret);
const joinRequest = await db
.select()
.from(joinRequests)
@@ -499,6 +648,14 @@ export function accessRoutes(db: Db) {
if (joinRequest.requestType !== "agent") throw badRequest("Only agent join requests can claim API keys");
if (joinRequest.status !== "approved") throw conflict("Join request must be approved before key claim");
if (!joinRequest.createdAgentId) throw conflict("Join request has no created agent");
if (!joinRequest.claimSecretHash) throw conflict("Join request is missing claim secret metadata");
if (!tokenHashesMatch(joinRequest.claimSecretHash, presentedClaimSecretHash)) {
throw forbidden("Invalid claim secret");
}
if (joinRequest.claimSecretExpiresAt && joinRequest.claimSecretExpiresAt.getTime() <= Date.now()) {
throw conflict("Claim secret expired");
}
if (joinRequest.claimSecretConsumedAt) throw conflict("Claim secret already used");
const existingKey = await db
.select({ id: agentApiKeys.id })
@@ -507,6 +664,14 @@ export function accessRoutes(db: Db) {
.then((rows) => rows[0] ?? null);
if (existingKey) throw conflict("API key already claimed");
const consumed = await db
.update(joinRequests)
.set({ claimSecretConsumedAt: new Date(), updatedAt: new Date() })
.where(and(eq(joinRequests.id, requestId), isNull(joinRequests.claimSecretConsumedAt)))
.returning({ id: joinRequests.id })
.then((rows) => rows[0] ?? null);
if (!consumed) throw conflict("Claim secret already used");
const created = await agents.createApiKey(joinRequest.createdAgentId, "initial-join-key");
await logActivity(db, {

View File

@@ -81,6 +81,8 @@ Status values: `backlog`, `todo`, `in_progress`, `in_review`, `done`, `blocked`,
- **Never retry a 409.** The task belongs to someone else.
- **Never look for unassigned work.**
- **Self-assign only for explicit @-mention handoff.** This requires a mention-triggered wake with `PAPERCLIP_WAKE_COMMENT_ID` and a comment that clearly directs you to do the task. Use checkout (never direct assignee patch). Otherwise, no assignments = exit.
- **Honor "send it back to me" requests from board users.** If a board/user asks for review handoff (e.g. "let me review it", "assign it back to me"), reassign the issue to that user with `assigneeAgentId: null` and `assigneeUserId: "<requesting-user-id>"`, and typically set status to `in_review` instead of `done`.
Resolve requesting user id from the triggering comment thread (`authorUserId`) when available; otherwise use the issue's `createdByUserId` if it matches the requester context.
- **Always comment** on `in_progress` work before exiting a heartbeat.
- **Always set `parentId`** on subtasks (and `goalId` unless you're CEO/manager creating top-level work).
- **Never cancel cross-team tasks.** Reassign to your manager with a comment.

View File

@@ -1,4 +1,4 @@
import type { JoinRequest } from "@paperclip/shared";
import type { AgentAdapterType, JoinRequest } from "@paperclip/shared";
import { api } from "./client";
type InviteSummary = {
@@ -7,6 +7,10 @@ type InviteSummary = {
inviteType: "company_join" | "bootstrap_ceo";
allowedJoinTypes: "human" | "agent" | "both";
expiresAt: string;
onboardingPath?: string;
onboardingUrl?: string;
skillIndexPath?: string;
skillIndexUrl?: string;
};
type AcceptInviteInput =
@@ -14,11 +18,22 @@ type AcceptInviteInput =
| {
requestType: "agent";
agentName: string;
adapterType?: string;
adapterType?: AgentAdapterType;
capabilities?: string | null;
agentDefaultsPayload?: Record<string, unknown> | null;
};
type AgentJoinRequestAccepted = JoinRequest & {
claimSecret: string;
claimApiKeyPath: string;
onboarding?: Record<string, unknown>;
};
type InviteOnboardingManifest = {
invite: InviteSummary;
onboarding: Record<string, unknown>;
};
type BoardClaimStatus = {
status: "available" | "claimed" | "expired";
requiresSignIn: boolean;
@@ -44,9 +59,14 @@ export const accessApi = {
}>(`/companies/${companyId}/invites`, input),
getInvite: (token: string) => api.get<InviteSummary>(`/invites/${token}`),
getInviteOnboarding: (token: string) =>
api.get<InviteOnboardingManifest>(`/invites/${token}/onboarding`),
acceptInvite: (token: string, input: AcceptInviteInput) =>
api.post<JoinRequest | { bootstrapAccepted: true; userId: string }>(`/invites/${token}/accept`, input),
api.post<AgentJoinRequestAccepted | JoinRequest | { bootstrapAccepted: true; userId: string }>(
`/invites/${token}/accept`,
input,
),
listJoinRequests: (companyId: string, status: "pending_approval" | "approved" | "rejected" = "pending_approval") =>
api.get<JoinRequest[]>(`/companies/${companyId}/join-requests?status=${status}`),
@@ -57,6 +77,12 @@ export const accessApi = {
rejectJoinRequest: (companyId: string, requestId: string) =>
api.post<JoinRequest>(`/companies/${companyId}/join-requests/${requestId}/reject`, {}),
claimJoinRequestApiKey: (requestId: string, claimSecret: string) =>
api.post<{ keyId: string; token: string; agentId: string; createdAt: string }>(
`/join-requests/${requestId}/claim-api-key`,
{ claimSecret },
),
getBoardClaimStatus: (token: string, code: string) =>
api.get<BoardClaimStatus>(`/board-claim/${token}?code=${encodeURIComponent(code)}`),

View File

@@ -14,7 +14,7 @@ export const companiesApi = {
data: Partial<
Pick<
Company,
"name" | "description" | "status" | "budgetMonthlyCents" | "requireBoardApprovalForNewAgents"
"name" | "description" | "status" | "budgetMonthlyCents" | "requireBoardApprovalForNewAgents" | "brandColor"
>
>,
) => api.patch<Company>(`/companies/${companyId}`, data),

View File

@@ -0,0 +1,192 @@
import { useMemo } from "react";
import { cn } from "../lib/utils";
const BAYER_4X4 = [
[0, 8, 2, 10],
[12, 4, 14, 6],
[3, 11, 1, 9],
[15, 7, 13, 5],
] as const;
interface CompanyPatternIconProps {
companyName: string;
brandColor?: string | null;
className?: string;
}
function hashString(value: string): number {
let hash = 2166136261;
for (let i = 0; i < value.length; i++) {
hash ^= value.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
function mulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t ^= t + Math.imul(t ^ (t >>> 7), 61 | t);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function hslToRgb(h: number, s: number, l: number): [number, number, number] {
const hue = ((h % 360) + 360) % 360;
const sat = Math.max(0, Math.min(100, s)) / 100;
const light = Math.max(0, Math.min(100, l)) / 100;
const c = (1 - Math.abs(2 * light - 1)) * sat;
const x = c * (1 - Math.abs(((hue / 60) % 2) - 1));
const m = light - c / 2;
let r = 0;
let g = 0;
let b = 0;
if (hue < 60) {
r = c;
g = x;
} else if (hue < 120) {
r = x;
g = c;
} else if (hue < 180) {
g = c;
b = x;
} else if (hue < 240) {
g = x;
b = c;
} else if (hue < 300) {
r = x;
b = c;
} else {
r = c;
b = x;
}
return [
Math.round((r + m) * 255),
Math.round((g + m) * 255),
Math.round((b + m) * 255),
];
}
function hexToHue(hex: string): number {
const r = parseInt(hex.slice(1, 3), 16) / 255;
const g = parseInt(hex.slice(3, 5), 16) / 255;
const b = parseInt(hex.slice(5, 7), 16) / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const d = max - min;
if (d === 0) return 0;
let h = 0;
if (max === r) h = ((g - b) / d) % 6;
else if (max === g) h = (b - r) / d + 2;
else h = (r - g) / d + 4;
return ((h * 60) + 360) % 360;
}
function makeCompanyPatternDataUrl(seed: string, brandColor?: string | null, logicalSize = 22, cellSize = 2): string {
if (typeof document === "undefined") return "";
const canvas = document.createElement("canvas");
canvas.width = logicalSize * cellSize;
canvas.height = logicalSize * cellSize;
const ctx = canvas.getContext("2d");
if (!ctx) return "";
const rand = mulberry32(hashString(seed));
const hue = brandColor ? hexToHue(brandColor) : Math.floor(rand() * 360);
const [offR, offG, offB] = hslToRgb(
hue,
54 + Math.floor(rand() * 14),
36 + Math.floor(rand() * 12),
);
const [onR, onG, onB] = hslToRgb(
hue + (rand() > 0.5 ? 10 : -10),
86 + Math.floor(rand() * 10),
82 + Math.floor(rand() * 10),
);
const center = (logicalSize - 1) / 2;
const half = Math.max(center, 1);
const gradientAngle = rand() * Math.PI * 2;
const gradientDirX = Math.cos(gradientAngle);
const gradientDirY = Math.sin(gradientAngle);
const maxProjection = Math.abs(gradientDirX * half) + Math.abs(gradientDirY * half);
const diagonalFrequency = 0.34 + rand() * 0.12;
const antiDiagonalFrequency = 0.33 + rand() * 0.12;
const diagonalPhase = rand() * Math.PI * 2;
const antiDiagonalPhase = rand() * Math.PI * 2;
ctx.fillStyle = `rgb(${offR} ${offG} ${offB})`;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = `rgb(${onR} ${onG} ${onB})`;
const dotRadius = cellSize * 0.46;
for (let y = 0; y < logicalSize; y++) {
const dy = y - center;
for (let x = 0; x < logicalSize; x++) {
const dx = x - center;
// Side-to-side signal where visible gradient is produced by dither density.
const projection = dx * gradientDirX + dy * gradientDirY;
const gradient = (projection / maxProjection + 1) * 0.5;
const diagonal = Math.sin((dx + dy) * diagonalFrequency + diagonalPhase) * 0.5 + 0.5;
const antiDiagonal = Math.sin((dx - dy) * antiDiagonalFrequency + antiDiagonalPhase) * 0.5 + 0.5;
const hatch = diagonal * 0.5 + antiDiagonal * 0.5;
const signal = Math.max(0, Math.min(1, gradient + (hatch - 0.5) * 0.22));
// Canonical 16-level ordered dither: level 0..15 compared to Bayer 4x4 threshold index.
const level = Math.max(0, Math.min(15, Math.floor(signal * 16)));
const thresholdIndex = BAYER_4X4[y & 3]![x & 3]!;
if (level <= thresholdIndex) continue;
const cx = x * cellSize + cellSize / 2;
const cy = y * cellSize + cellSize / 2;
ctx.beginPath();
ctx.arc(cx, cy, dotRadius, 0, Math.PI * 2);
ctx.fill();
}
}
return canvas.toDataURL("image/png");
}
export function CompanyPatternIcon({ companyName, brandColor, className }: CompanyPatternIconProps) {
const initial = companyName.trim().charAt(0).toUpperCase() || "?";
const patternDataUrl = useMemo(
() => makeCompanyPatternDataUrl(companyName.trim().toLowerCase(), brandColor),
[companyName, brandColor],
);
return (
<div
className={cn(
"relative flex items-center justify-center w-11 h-11 text-base font-semibold text-white overflow-hidden",
className,
)}
>
{patternDataUrl ? (
<img
src={patternDataUrl}
alt=""
aria-hidden="true"
className="absolute inset-0 h-full w-full"
style={{ imageRendering: "pixelated" }}
/>
) : (
<div className="absolute inset-0 bg-muted" />
)}
<span className="relative z-10 drop-shadow-[0_1px_2px_rgba(0,0,0,0.65)]">
{initial}
</span>
</div>
);
}

View File

@@ -6,21 +6,43 @@ import { authApi } from "../api/auth";
import { healthApi } from "../api/health";
import { queryKeys } from "../lib/queryKeys";
import { Button } from "@/components/ui/button";
import type { JoinRequest } from "@paperclip/shared";
import { AGENT_ADAPTER_TYPES } from "@paperclip/shared";
import type { AgentAdapterType, JoinRequest } from "@paperclip/shared";
type JoinType = "human" | "agent";
const joinAdapterOptions: AgentAdapterType[] = [
"openclaw",
...AGENT_ADAPTER_TYPES.filter((type): type is Exclude<AgentAdapterType, "openclaw"> => type !== "openclaw"),
];
const adapterLabels: Record<AgentAdapterType, string> = {
claude_local: "Claude (local)",
codex_local: "Codex (local)",
openclaw: "OpenClaw",
process: "Process",
http: "HTTP",
};
function dateTime(value: string) {
return new Date(value).toLocaleString();
}
function readNestedString(value: unknown, path: string[]): string | null {
let current: unknown = value;
for (const segment of path) {
if (!current || typeof current !== "object") return null;
current = (current as Record<string, unknown>)[segment];
}
return typeof current === "string" && current.trim().length > 0 ? current : null;
}
export function InviteLandingPage() {
const queryClient = useQueryClient();
const params = useParams();
const token = (params.token ?? "").trim();
const [joinType, setJoinType] = useState<JoinType>("human");
const [agentName, setAgentName] = useState("");
const [adapterType, setAdapterType] = useState("");
const [adapterType, setAdapterType] = useState<AgentAdapterType>("openclaw");
const [capabilities, setCapabilities] = useState("");
const [result, setResult] = useState<{ kind: "bootstrap" | "join"; payload: unknown } | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -73,7 +95,7 @@ export function InviteLandingPage() {
return accessApi.acceptInvite(token, {
requestType: "agent",
agentName: agentName.trim(),
adapterType: adapterType.trim() || undefined,
adapterType,
capabilities: capabilities.trim() || null,
});
},
@@ -128,7 +150,16 @@ export function InviteLandingPage() {
}
if (result?.kind === "join") {
const payload = result.payload as JoinRequest;
const payload = result.payload as JoinRequest & {
claimSecret?: string;
claimApiKeyPath?: string;
onboarding?: Record<string, unknown>;
};
const claimSecret = typeof payload.claimSecret === "string" ? payload.claimSecret : null;
const claimApiKeyPath = typeof payload.claimApiKeyPath === "string" ? payload.claimApiKeyPath : null;
const onboardingSkillUrl = readNestedString(payload.onboarding, ["skill", "url"]);
const onboardingSkillPath = readNestedString(payload.onboarding, ["skill", "path"]);
const onboardingInstallPath = readNestedString(payload.onboarding, ["skill", "installPath"]);
return (
<div className="mx-auto max-w-xl py-10">
<div className="rounded-lg border border-border bg-card p-6">
@@ -139,6 +170,21 @@ export function InviteLandingPage() {
<div className="mt-4 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
Request ID: <span className="font-mono">{payload.id}</span>
</div>
{claimSecret && claimApiKeyPath && (
<div className="mt-3 space-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
<p className="font-medium text-foreground">One-time claim secret (save now)</p>
<p className="font-mono break-all">{claimSecret}</p>
<p className="font-mono break-all">POST {claimApiKeyPath}</p>
</div>
)}
{(onboardingSkillUrl || onboardingSkillPath || onboardingInstallPath) && (
<div className="mt-3 space-y-1 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
<p className="font-medium text-foreground">Paperclip skill bootstrap</p>
{onboardingSkillUrl && <p className="font-mono break-all">GET {onboardingSkillUrl}</p>}
{!onboardingSkillUrl && onboardingSkillPath && <p className="font-mono break-all">GET {onboardingSkillPath}</p>}
{onboardingInstallPath && <p className="font-mono break-all">Install to {onboardingInstallPath}</p>}
</div>
)}
</div>
</div>
);
@@ -182,13 +228,18 @@ export function InviteLandingPage() {
/>
</label>
<label className="block text-sm">
<span className="mb-1 block text-muted-foreground">Adapter type (optional)</span>
<input
<span className="mb-1 block text-muted-foreground">Adapter type</span>
<select
className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
value={adapterType}
onChange={(event) => setAdapterType(event.target.value)}
placeholder="process"
/>
onChange={(event) => setAdapterType(event.target.value as AgentAdapterType)}
>
{joinAdapterOptions.map((type) => (
<option key={type} value={type}>
{adapterLabels[type]}
</option>
))}
</select>
</label>
<label className="block text-sm">
<span className="mb-1 block text-muted-foreground">Capabilities (optional)</span>