1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
|
import { and, desc, eq, ilike, or, sql } from "drizzle-orm";
import { db } from "../db";
import {
agentMarketplaceListings,
agentMarketplaceInstalls,
agentMarketplaceReviews,
users,
} from "../db/schema";
import type {
AgentMarketplaceListing,
AgentMarketplaceInstall,
AgentMarketplaceReview,
} from "../db/schema";
import { createAgentSession, revokeAgentSession } from "./agent-multiplayer";
import type { CreateAgentSessionResult } from "./agent-multiplayer";
export const MARKETPLACE_CATEGORIES = [
"reviewer",
"tester",
"migrator",
"security",
"docs",
"custom",
] as const;
export type MarketplaceCategory = (typeof MARKETPLACE_CATEGORIES)[number];
export const PRICING_MODELS = [
"per_invocation",
"per_repo_per_month",
"free",
] as const;
export type PricingModel = (typeof PRICING_MODELS)[number];
export const LISTING_STATUSES = [
"draft",
"pending_review",
"approved",
"rejected",
] as const;
export type ListingStatus = (typeof LISTING_STATUSES)[number];
export const MARKETPLACE_REVENUE_SPLIT_BPS = 3000;
export function slugifyListing(name: string): string {
return name
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60);
}
export function formatPrice(
priceCents: number,
pricingModel: PricingModel | string
): string {
if (pricingModel === "free" || priceCents <= 0) return "Free";
const dollars = (priceCents / 100).toFixed(2);
if (pricingModel === "per_repo_per_month") return `$${dollars}/repo/mo`;
if (pricingModel === "per_invocation") return `$${dollars}/run`;
return `$${dollars}`;
}
export function isValidCategory(value: unknown): value is MarketplaceCategory {
return (
typeof value === "string" &&
(MARKETPLACE_CATEGORIES as readonly string[]).includes(value)
);
}
export function isValidPricingModel(value: unknown): value is PricingModel {
return (
typeof value === "string" &&
(PRICING_MODELS as readonly string[]).includes(value)
);
}
export function splitRevenueCents(priceCents: number): {
platformCents: number;
publisherCents: number;
} {
const amount = Math.max(0, Math.floor(priceCents));
const platformCents = Math.floor(
(amount * MARKETPLACE_REVENUE_SPLIT_BPS) / 10_000
);
return { platformCents, publisherCents: amount - platformCents };
}
const LOGO_GRADIENTS = [
"linear-gradient(135deg, #8c6dff 0%, #36c5d6 100%)",
"linear-gradient(135deg, #ec4899 0%, #f43f5e 100%)",
"linear-gradient(135deg, #f59e0b 0%, #ef4444 100%)",
"linear-gradient(135deg, #10b981 0%, #14b8a6 100%)",
"linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)",
"linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%)",
"linear-gradient(135deg, #84cc16 0%, #22c55e 100%)",
"linear-gradient(135deg, #f97316 0%, #fb7185 100%)",
];
export function gradientForSlug(slug: string): string {
let h = 0;
for (let i = 0; i < slug.length; i++) h = (h * 31 + slug.charCodeAt(i)) | 0;
const idx =
((h % LOGO_GRADIENTS.length) + LOGO_GRADIENTS.length) %
LOGO_GRADIENTS.length;
return LOGO_GRADIENTS[idx]!;
}
export function listingInitials(name: string): string {
const parts = name
.trim()
.split(/[\s\-_]+/)
.filter(Boolean);
if (parts.length >= 2) return (parts[0]![0]! + parts[1]![0]!).toUpperCase();
return name.slice(0, 2).toUpperCase();
}
export type ListListingsSort = "top" | "new" | "rated";
export interface ListListingsArgs {
category?: string;
search?: string;
sort?: ListListingsSort;
status?: ListingStatus | "any";
limit?: number;
}
export async function listListings(
args: ListListingsArgs = {}
): Promise<AgentMarketplaceListing[]> {
const limit = Math.min(200, Math.max(1, args.limit ?? 100));
const sort: ListListingsSort = args.sort ?? "top";
const where = [] as ReturnType<typeof eq>[];
if (!args.status || args.status === "approved") {
where.push(eq(agentMarketplaceListings.status, "approved"));
} else if (args.status !== "any") {
where.push(eq(agentMarketplaceListings.status, args.status));
}
if (args.category && isValidCategory(args.category)) {
where.push(eq(agentMarketplaceListings.category, args.category));
}
if (args.search) {
const term = `%${args.search}%`;
const matchOr = or(
ilike(agentMarketplaceListings.name, term),
ilike(agentMarketplaceListings.tagline, term),
ilike(agentMarketplaceListings.description, term)
);
if (matchOr) where.push(matchOr as ReturnType<typeof eq>);
}
const orderBy =
sort === "new"
? desc(agentMarketplaceListings.createdAt)
: sort === "rated"
? desc(agentMarketplaceListings.ratingAvg)
: desc(agentMarketplaceListings.installCount);
try {
const rows = await db
.select()
.from(agentMarketplaceListings)
.where(where.length ? and(...where) : undefined)
.orderBy(orderBy)
.limit(limit);
return rows;
} catch {
return [];
}
}
export interface ListingWithPublisher extends AgentMarketplaceListing {
publisherUsername: string | null;
}
export interface ListingDetail {
listing: ListingWithPublisher;
reviews: Array<AgentMarketplaceReview & { reviewerUsername: string | null }>;
}
export async function getListing(slug: string): Promise<ListingDetail | null> {
try {
const [row] = await db
.select({
listing: agentMarketplaceListings,
publisherUsername: users.username,
})
.from(agentMarketplaceListings)
.leftJoin(users, eq(users.id, agentMarketplaceListings.publisherUserId))
.where(eq(agentMarketplaceListings.slug, slug))
.limit(1);
if (!row) return null;
const reviewRows = await db
.select({
review: agentMarketplaceReviews,
reviewerUsername: users.username,
})
.from(agentMarketplaceReviews)
.leftJoin(users, eq(users.id, agentMarketplaceReviews.reviewerUserId))
.where(eq(agentMarketplaceReviews.listingId, row.listing.id))
.orderBy(desc(agentMarketplaceReviews.createdAt))
.limit(20);
return {
listing: {
...row.listing,
publisherUsername: row.publisherUsername,
},
reviews: reviewRows.map((r) => ({
...r.review,
reviewerUsername: r.reviewerUsername,
})),
};
} catch {
return null;
}
}
export interface CreateListingArgs {
publisherUserId: string;
name: string;
tagline?: string;
description?: string;
category?: string;
pricingModel?: string;
priceCents?: number;
agentTemplate?: Record<string, unknown>;
sourceUrl?: string;
initialStatus?: ListingStatus;
}
export async function createListing(
args: CreateListingArgs
): Promise<AgentMarketplaceListing | null> {
const name = args.name.trim();
if (!name) return null;
const category = isValidCategory(args.category)
? args.category
: "custom";
const pricingModel = isValidPricingModel(args.pricingModel)
? args.pricingModel
: "free";
const status: ListingStatus = args.initialStatus ?? "pending_review";
const baseSlug = slugifyListing(name) || "agent";
for (let attempt = 0; attempt < 6; attempt++) {
const slug =
attempt === 0
? baseSlug
: `${baseSlug}-${Math.floor(Math.random() * 0xffff)
.toString(16)
.padStart(4, "0")}`;
try {
const [row] = await db
.insert(agentMarketplaceListings)
.values({
publisherUserId: args.publisherUserId,
slug,
name,
tagline: (args.tagline ?? "").slice(0, 280),
description: args.description ?? "",
category,
pricingModel,
priceCents: Math.max(0, Math.floor(args.priceCents ?? 0)),
agentTemplate: (args.agentTemplate ?? {}) as never,
sourceUrl: args.sourceUrl ?? null,
status,
})
.returning();
return row ?? null;
} catch (err) {
const code = (err as { code?: string } | undefined)?.code;
if (code === "23505") continue;
console.error("[agent-marketplace] createListing:", err);
return null;
}
}
return null;
}
export async function approveListing(
slug: string,
_moderatorUserId: string
): Promise<AgentMarketplaceListing | null> {
try {
const [row] = await db
.update(agentMarketplaceListings)
.set({ status: "approved", updatedAt: new Date() })
.where(eq(agentMarketplaceListings.slug, slug))
.returning();
return row ?? null;
} catch {
return null;
}
}
export async function rejectListing(
slug: string,
_moderatorUserId: string,
_reason: string
): Promise<AgentMarketplaceListing | null> {
try {
const [row] = await db
.update(agentMarketplaceListings)
.set({ status: "rejected", updatedAt: new Date() })
.where(eq(agentMarketplaceListings.slug, slug))
.returning();
return row ?? null;
} catch {
return null;
}
}
export interface InstallListingArgs {
listingId: string;
repositoryId: string;
installedByUserId: string;
}
export interface InstallListingResult {
install: AgentMarketplaceInstall;
agentToken: string;
}
export async function installListing(
args: InstallListingArgs
): Promise<InstallListingResult | null> {
const listing = await fetchListingById(args.listingId);
if (!listing || listing.status !== "approved") return null;
const tpl = listing.agentTemplate ?? {};
const sessionName =
`mkt-${listing.slug}-${args.repositoryId.slice(0, 8)}`.slice(0, 60);
const sess: CreateAgentSessionResult | null = await createAgentSession({
ownerUserId: args.installedByUserId,
name: sessionName,
repositoryId: args.repositoryId,
branchNamespace:
typeof tpl.branchNamespace === "string"
? tpl.branchNamespace
: `agents/${listing.slug}`,
budgetCentsPerDay:
typeof tpl.budgetCentsPerDay === "number" ? tpl.budgetCentsPerDay : 500,
});
if (!sess) return null;
try {
const [install] = await db
.insert(agentMarketplaceInstalls)
.values({
listingId: args.listingId,
repositoryId: args.repositoryId,
installedByUserId: args.installedByUserId,
agentSessionId: sess.session.id,
status: "active",
})
.returning();
if (!install) {
await revokeAgentSession(sess.session.id, args.installedByUserId);
return null;
}
db.update(agentMarketplaceListings)
.set({
installCount: sql`${agentMarketplaceListings.installCount} + 1`,
updatedAt: new Date(),
})
.where(eq(agentMarketplaceListings.id, args.listingId))
.catch(() => undefined);
return { install, agentToken: sess.token };
} catch (err) {
await revokeAgentSession(sess.session.id, args.installedByUserId);
const code = (err as { code?: string } | undefined)?.code;
if (code !== "23505") {
console.error("[agent-marketplace] installListing:", err);
}
return null;
}
}
export async function uninstallListing(args: {
installId: string;
}): Promise<boolean> {
try {
const [row] = await db
.update(agentMarketplaceInstalls)
.set({ status: "uninstalled" })
.where(eq(agentMarketplaceInstalls.id, args.installId))
.returning();
if (!row) return false;
if (row.agentSessionId) {
await revokeAgentSession(row.agentSessionId, row.installedByUserId);
}
return true;
} catch {
return false;
}
}
export async function listInstallsForRepo(
repositoryId: string
): Promise<AgentMarketplaceInstall[]> {
try {
return await db
.select()
.from(agentMarketplaceInstalls)
.where(eq(agentMarketplaceInstalls.repositoryId, repositoryId))
.orderBy(desc(agentMarketplaceInstalls.installedAt));
} catch {
return [];
}
}
async function fetchListingById(
id: string
): Promise<AgentMarketplaceListing | null> {
try {
const [row] = await db
.select()
.from(agentMarketplaceListings)
.where(eq(agentMarketplaceListings.id, id))
.limit(1);
return row ?? null;
} catch {
return null;
}
}
export async function fetchListingBySlug(
slug: string
): Promise<AgentMarketplaceListing | null> {
try {
const [row] = await db
.select()
.from(agentMarketplaceListings)
.where(eq(agentMarketplaceListings.slug, slug))
.limit(1);
return row ?? null;
} catch {
return null;
}
}
export interface RecordReviewArgs {
listingId: string;
reviewerUserId: string;
rating: number;
body?: string;
}
export async function recordReview(
args: RecordReviewArgs
): Promise<AgentMarketplaceReview | null> {
const rating = Math.max(1, Math.min(5, Math.floor(args.rating)));
try {
const [row] = await db
.insert(agentMarketplaceReviews)
.values({
listingId: args.listingId,
reviewerUserId: args.reviewerUserId,
rating,
body: (args.body ?? "").slice(0, 4000),
})
.returning();
if (!row) return null;
await db
.update(agentMarketplaceListings)
.set({
ratingAvg: sql`(
SELECT COALESCE(ROUND(AVG(rating)::numeric, 2), 0)
FROM ${agentMarketplaceReviews}
WHERE ${agentMarketplaceReviews.listingId} = ${args.listingId}
)`,
ratingCount: sql`(
SELECT COUNT(*)::int
FROM ${agentMarketplaceReviews}
WHERE ${agentMarketplaceReviews.listingId} = ${args.listingId}
)`,
updatedAt: new Date(),
})
.where(eq(agentMarketplaceListings.id, args.listingId));
return row;
} catch {
return null;
}
}
|