-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathindex.ts
More file actions
630 lines (616 loc) · 32 KB
/
Copy pathindex.ts
File metadata and controls
630 lines (616 loc) · 32 KB
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
import type { Express, NextFunction, Request, RequestHandler, Response } from 'express';
import type {
InstalledPluginRecord,
PluginDuplicateProjectRequest,
PluginDuplicateProjectResponse,
Project,
ProjectMetadata,
WorkspaceCollabContext,
} from '@open-design/contracts';
import { TeamResourceCopyForbiddenError } from '@open-design/contracts';
import {
duplicatePluginExampleIntoProject,
PluginDuplicateProjectError,
} from '../../plugins/duplicate-project.js';
import {
enforceTeamResourceCopyAllowed,
type TeamResourceStateProvider,
} from '../../collab/team-resource-state.js';
import {
enforceVerifiedWorkspaceResourceMutation,
resolveOptionalWorkspaceRequestAuthority,
type VerifyWorkspaceRequestAuthority,
} from '../../collab/workspace-resource-mutation.js';
import {
authorizeCreatedProjectWorkspace,
bindCreatedProjectToWorkspace,
sendCreatedProjectWorkspaceError,
} from '../../collab/created-project-workspace.js';
import type { WorkspaceDirectoryFetchResult } from '../../collab/vela-workspace-context.js';
import type { PluginShareAction } from '../../services/plugin-share-tasks.js';
import type { AuthorizeProjectRequest } from '../../collab/project-request-authority.js';
export interface RegisterPluginEventRoutesDeps {
http: { requireLocalDaemonRequest: RequestHandler };
}
interface SqliteRowId {
id: string;
}
interface SqliteDbLike {
prepare(sql: string): {
all(...params: unknown[]): unknown[];
get(...params: unknown[]): unknown;
run(...params: unknown[]): unknown;
};
transaction<T>(run: () => T): () => T;
}
interface InstalledPluginLike {
id?: string;
title?: string;
manifest?: Record<string, unknown>;
fsPath?: string;
capabilitiesGranted?: string[];
appliedPlugin?: { capabilitiesGranted?: string[]; [key: string]: unknown };
assistantMessageId?: string;
[key: string]: unknown;
}
interface AppliedPluginSnapshotLike {
snapshotId: string;
pluginId: string;
[key: string]: unknown;
}
// The narrow slice of a `workspace_resources` row the mutation gate needs —
// see collab/workspace-resource-mutation.ts's `WorkspaceResourceAccessInput`,
// which this mirrors so `enforceWorkspaceResourceMutation` accepts it as-is.
interface WorkspaceResourceBindingRow {
visibility?: string | null;
resourceState?: string | null;
createdByWorkspaceMemberId?: string | null;
}
interface MissingInputErrorLike extends Error {
fields: string[];
}
interface PluginApplyResult {
result: {
capabilitiesGranted: string[];
appliedPlugin: { capabilitiesGranted: string[]; [key: string]: unknown };
[key: string]: unknown;
};
warnings: unknown[];
manifestSourceDigest?: string;
}
interface PluginShareTaskLike {
projectId: string;
status: 'queued' | 'running' | 'done' | 'failed';
progress: string[];
waiters: Set<() => void>;
}
interface PluginRouteHelpers {
PLUGIN_PREVIEWS_DIR: string;
pluginUpload: {
single(field: string): RequestHandler;
array(field: string, maxCount?: number): RequestHandler;
};
pluginInstallation: {
stageUploadedPluginZip(buffer: Buffer, source: string): Promise<unknown>;
stageUploadedPluginFolder(files: Array<{ buffer: Buffer; originalname: string }>, rawPaths: unknown): Promise<unknown>;
};
connectorService: unknown;
resolvedPortRef: { current: number | null | undefined };
pluginShareTaskStore: {
get(id: string): PluginShareTaskLike | null;
snapshot(task: PluginShareTaskLike, since?: number): unknown;
};
applyBakedPreviews(plugins: InstalledPluginLike[], previewsDir: string): unknown;
assembleExample(templateHtml: string, slidesHtml: string, title: string): string;
sendMulterError(res: Response, err: unknown): unknown;
decodeMultipartFilename(name: string): string;
installOrUpgradePlugin(
req: Request,
res: Response,
mode: 'install' | 'upgrade',
authority: WorkspaceCollabContext | null,
): Promise<unknown>;
loadPluginRegistryView(): Promise<unknown>;
buildConnectorProbe(service: unknown): unknown;
handleShareProject(req: Request, res: Response): Promise<unknown>;
handlePluginTrust(req: Request, res: Response): Promise<unknown>;
handlePluginStats(res: Response): Promise<unknown> | unknown;
requireLocalDaemonRequest: RequestHandler;
handleAppliedPluginExport(req: Request, res: Response): Promise<unknown>;
handleProjectInstallFolder(req: Request, res: Response): Promise<unknown>;
handleProjectPluginCli(req: Request, res: Response, action: PluginShareAction): Promise<unknown>;
getProject(db: SqliteDbLike, id: string): unknown;
sendApiError(res: Response, status: number, code: string, message: string): unknown;
isLocalSameOrigin(req: Request, port: number | null | undefined): boolean;
handleCandidateDraft(req: Request, res: Response): Promise<unknown>;
handleCandidateShareTask(req: Request, res: Response): Promise<unknown>;
handleProjectShareTask(req: Request, res: Response): Promise<unknown>;
}
export interface RegisterPluginRoutesDeps {
db: SqliteDbLike;
authorizeProjectRequest: AuthorizeProjectRequest;
/** Team-resource copy red-line (D3). When present, a frozen team plugin cannot
* be duplicated into a personal project. Omit to skip the guard (no-op). */
teamResources?: TeamResourceStateProvider;
paths: { PROJECTS_DIR: string; PLUGIN_REGISTRY_ROOTS: string[]; PLUGIN_LOCKFILE_PATH: string };
ids: { randomId(): string };
projectStore: {
insertProject(db: SqliteDbLike, project: unknown): Project | null;
getProject(db: SqliteDbLike, id: string): Project | null;
ensureWorkspaceProject(db: SqliteDbLike, input: unknown): unknown;
dbDeleteProject(db: SqliteDbLike, id: string): unknown;
removeProjectDir(projectsRoot: string, projectId: string): Promise<unknown>;
};
fetchProjectCreationWorkspaceDirectory?: () => Promise<WorkspaceDirectoryFetchResult>;
verifyWorkspaceRequestAuthority?: VerifyWorkspaceRequestAuthority;
conversations: {
insertConversation(db: SqliteDbLike, conversation: unknown): unknown;
};
/**
* Read access to the generic `workspace_resources` binding table (db.ts),
* pre-bound to no particular resource type — routes below pass `'plugin'`
* explicitly so a future skill/design-system route can reuse the exact
* same deps shape. Optional so callers that never reach the uninstall
* route (`registerProjectPluginRoutes`, existing narrow-scope tests) don't
* have to wire it; `registerPluginRoutes`'s uninstall handler treats an
* absent value as "no gate" rather than crashing.
*/
workspaceResources?: {
getWorkspaceResource: (
db: SqliteDbLike,
resourceType: string,
workspaceId: string,
resourceId: string,
) => WorkspaceResourceBindingRow | null | undefined;
getWorkspaceResourceByResourceId: (
db: SqliteDbLike,
resourceType: string,
resourceId: string,
) => WorkspaceResourceBindingRow | null | undefined;
workspaceTeamPluginBindingAllowsRead?: (
db: SqliteDbLike,
workspaceId: string,
pluginId: string,
) => boolean;
};
plugins: {
listInstalledPlugins: (
db: SqliteDbLike,
workspaceId?: string | null,
) => InstalledPluginLike[] | Promise<InstalledPluginLike[]>;
getInstalledPlugin: (db: SqliteDbLike, id: string) => InstalledPluginLike | null;
getWorkspacePlugin?: (
db: SqliteDbLike,
id: string,
workspaceId: string | null,
) => InstalledPluginLike | null | Promise<InstalledPluginLike | null>;
installPlugin: (db: SqliteDbLike, args: unknown) => AsyncIterable<unknown>;
isSafePluginId: (id: string) => boolean;
uninstallPlugin: (db: SqliteDbLike, id: string, roots: string[]) => Promise<{ ok: boolean; removedFolder?: boolean; warning?: string }>;
installFromLocalFolder: (db: SqliteDbLike, args: unknown) => AsyncIterable<unknown>;
applyPlugin: (args: unknown) => PluginApplyResult;
doctorPlugin: (plugin: InstalledPluginLike, registry: unknown, extras: unknown) => unknown;
getSnapshot: (db: SqliteDbLike, id: string) => AppliedPluginSnapshotLike | null;
pruneExpiredSnapshots: (db: SqliteDbLike, opts?: { before?: number }) => { removed: number; ids: string[] };
readPluginLockfile: (path: string) => Promise<unknown>;
resolvePluginSnapshot: (args: unknown) => unknown;
MissingInputError: new (...args: unknown[]) => MissingInputErrorLike;
pluginPromptBlock: (snap: AppliedPluginSnapshotLike) => string;
listSkillPluginCandidates: (db: SqliteDbLike, projectId: string, includeDismissed?: boolean) => InstalledPluginLike[];
dismissSkillPluginCandidate: (db: SqliteDbLike, projectId: string, candidateId: string) => InstalledPluginLike | null;
generateSkillPluginDraft: (db: SqliteDbLike, projectRoot: string, projectId: string, candidateId: string) => Promise<unknown>;
FIRST_PARTY_ATOMS: unknown[];
};
helpers: PluginRouteHelpers;
}
export function registerPluginEventRoutes(app: Express, deps: RegisterPluginEventRoutesDeps): void {
app.get('/api/plugins/events/snapshot', async (req, res) => {
const since = Number(typeof req.query.since === 'string' ? req.query.since : 0);
const { pluginEventSnapshot } = await import('../../plugins/events.js');
const events = pluginEventSnapshot(Number.isFinite(since) && since > 0 ? since : 0);
res.json({ events, count: events.length, generatedAt: Date.now() });
});
app.get('/api/plugins/events/stats', async (_req, res) => {
const { pluginEventSnapshot, summarisePluginEvents } = await import('../../plugins/events.js');
res.json({ stats: summarisePluginEvents(pluginEventSnapshot()), generatedAt: Date.now() });
});
app.post('/api/plugins/events/purge', deps.http.requireLocalDaemonRequest, async (_req, res) => {
try {
const { purgePluginEventBuffer } = await import('../../plugins/events.js');
res.json({ ok: true, ...purgePluginEventBuffer() });
} catch (err) { res.status(500).json({ error: String(err) }); }
});
app.get('/api/plugins/events', async (req, res) => {
const since = Number(typeof req.query.since === 'string' ? req.query.since : 0);
const { pluginEventSnapshot, subscribePluginEvents } = await import('../../plugins/events.js');
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders?.();
for (const ev of pluginEventSnapshot(Number.isFinite(since) && since > 0 ? since : 0)) res.write(`event: backlog\ndata: ${JSON.stringify(ev)}\n\n`);
const unsubscribe = subscribePluginEvents((ev) => res.write(`event: plugin\ndata: ${JSON.stringify(ev)}\n\n`));
req.on('close', () => { unsubscribe(); });
});
}
export function registerPluginRoutes(app: Express, deps: RegisterPluginRoutesDeps): void {
const { db, paths, ids, projectStore, conversations, plugins, helpers, teamResources, workspaceResources } = deps;
const resolveWorkspaceAuthority = async (
req: Request,
res: Response,
): Promise<WorkspaceCollabContext | null | undefined> => {
const authority = await resolveOptionalWorkspaceRequestAuthority(
req,
deps.verifyWorkspaceRequestAuthority,
);
if (!authority.ok) {
helpers.sendApiError(
res,
authority.status,
authority.code,
authority.message,
);
return undefined;
}
return authority.context;
};
const resolveRequestPlugin = async (
id: string,
authority: WorkspaceCollabContext | null,
) => {
const workspaceId = authority?.workspaceId ?? null;
return plugins.getWorkspacePlugin
? plugins.getWorkspacePlugin(db, id, workspaceId)
: plugins.getInstalledPlugin(db, id);
};
app.get('/api/plugins', async (req, res) => { try { const authority = await resolveWorkspaceAuthority(req, res); if (authority === undefined) return; const visible = await plugins.listInstalledPlugins(db, authority?.workspaceId ?? null); res.json({ plugins: helpers.applyBakedPreviews(visible, helpers.PLUGIN_PREVIEWS_DIR) }); } catch (err) { res.status(500).json({ error: String(err) }); } });
app.get('/api/plugins/:id', async (req, res) => { try { const authority = await resolveWorkspaceAuthority(req, res); if (authority === undefined) return; const plugin = await resolveRequestPlugin(req.params.id, authority); if (!plugin) return res.status(404).json({ error: 'plugin not found' }); res.json(plugin); } catch (err) { res.status(500).json({ error: String(err) }); } });
app.post('/api/plugins/upload-zip', (req, res) => helpers.pluginUpload.single('file')(req, res, async (err: unknown) => { if (err) return helpers.sendMulterError(res, err); try { const file = req.file; if (!file?.buffer) return res.status(400).json({ error: 'file is required' }); const result = await helpers.pluginInstallation.stageUploadedPluginZip(file.buffer, `upload:zip:${helpers.decodeMultipartFilename(file.originalname || 'plugin.zip')}`); res.status((result as { ok?: boolean }).ok ? 200 : 400).json(result); } catch (uploadErr: unknown) { res.status(400).json({ ok: false, warnings: [], message: uploadErr instanceof Error ? uploadErr.message : String(uploadErr), log: [] }); } }));
app.post('/api/plugins/upload-folder', (req, res) => helpers.pluginUpload.array('files', 500)(req, res, async (err: unknown) => { if (err) return helpers.sendMulterError(res, err); try { const files = Array.isArray(req.files) ? req.files as Array<{ buffer: Buffer; originalname: string }> : []; if (files.length === 0) return res.status(400).json({ error: 'files are required' }); const result = await helpers.pluginInstallation.stageUploadedPluginFolder(files, req.body?.paths); res.status((result as { ok?: boolean } | null)?.ok ? 200 : 400).json(result); } catch (uploadErr: unknown) { res.status(400).json({ ok: false, warnings: [], message: uploadErr instanceof Error ? uploadErr.message : String(uploadErr), log: [] }); } }));
app.post('/api/plugins/install', async (req, res) => {
const authority = await resolveWorkspaceAuthority(req, res);
if (authority === undefined) return;
return helpers.installOrUpgradePlugin(req, res, 'install', authority);
});
// This route used to carry NO permission check at all: any caller (any
// workspace, any role) could uninstall any plugin. Now gated the same way
// project mutations are, via the shared
// `enforceWorkspaceResourceMutation` (collab/workspace-resource-mutation.ts).
//
// The gate only applies when the plugin has an actual `workspace_resources`
// binding row (i.e. it was installed through the workspace-aware
// `/api/plugins/install` after this shipped). A plugin installed BEFORE
// this round — bundled or user-installed — has no binding row at all;
// per the design's "no retroactive tagging" rule (same one design-systems'
// `designSystemVisibleFromWorkspace` already ships), an unbound resource
// stays outside the isolation regime rather than becoming permanently
// un-uninstallable the moment a caller happens to carry workspace headers.
app.post('/api/plugins/:id/uninstall', async (req, res) => {
try {
if (!plugins.isSafePluginId(req.params.id)) return res.status(400).json({ error: 'invalid plugin id' });
const authority = await resolveWorkspaceAuthority(req, res);
if (authority === undefined) return;
const requestedPlugin = await resolveRequestPlugin(req.params.id, authority);
if (
typeof requestedPlugin?.source === 'string' &&
requestedPlugin.source.startsWith('team:plugin:')
) {
return res.status(403).json({ error: 'WORKSPACE_RESOURCE_MANAGE_DENIED' });
}
const binding = workspaceResources?.getWorkspaceResourceByResourceId(db, 'plugin', req.params.id);
if (binding && workspaceResources && !await enforceVerifiedWorkspaceResourceMutation(
'plugin',
req,
res,
helpers.sendApiError,
(dbArg, workspaceId, resourceId) => workspaceResources.getWorkspaceResource(dbArg as SqliteDbLike, 'plugin', workspaceId, resourceId),
(dbArg, resourceId) => workspaceResources.getWorkspaceResourceByResourceId(dbArg as SqliteDbLike, 'plugin', resourceId),
db,
req.params.id,
'delete',
deps.verifyWorkspaceRequestAuthority,
)) return;
const result = await plugins.uninstallPlugin(db, req.params.id, paths.PLUGIN_REGISTRY_ROOTS); if (!result.ok && !result.removedFolder) return res.status(404).json({ error: 'plugin not found', warning: result.warning }); res.json(result);
} catch (err) { res.status(500).json({ error: String(err) }); }
});
app.post('/api/plugins/:id/upgrade', async (req, res) => {
const authority = await resolveWorkspaceAuthority(req, res);
if (authority === undefined) return;
const binding = workspaceResources?.getWorkspaceResourceByResourceId(db, 'plugin', req.params.id);
if (binding && workspaceResources && !await enforceVerifiedWorkspaceResourceMutation(
'plugin',
req,
res,
helpers.sendApiError,
(dbArg, workspaceId, resourceId) => workspaceResources.getWorkspaceResource(dbArg as SqliteDbLike, 'plugin', workspaceId, resourceId),
(dbArg, resourceId) => workspaceResources.getWorkspaceResourceByResourceId(dbArg as SqliteDbLike, 'plugin', resourceId),
db,
req.params.id,
'writeFiles',
deps.verifyWorkspaceRequestAuthority,
)) return;
return helpers.installOrUpgradePlugin(req, res, 'upgrade', authority);
});
app.post('/api/plugins/:id/apply', async (req, res) => {
try {
const authority = await resolveWorkspaceAuthority(req, res);
if (authority === undefined) return;
const plugin = await resolveRequestPlugin(req.params.id, authority);
if (!plugin) return res.status(404).json({ error: 'plugin not found' });
const body = req.body && typeof req.body === 'object'
? req.body as Record<string, unknown>
: {};
const inputs = body.inputs && typeof body.inputs === 'object' ? body.inputs : {};
const grantCaps = Array.isArray(body.grantCaps)
? body.grantCaps.filter((c: unknown): c is string => typeof c === 'string')
: [];
const locale = typeof body.locale === 'string' ? body.locale : undefined;
const registry = await helpers.loadPluginRegistryView();
const exactWorkspaceId = authority?.workspaceId?.trim();
if (
typeof plugin.source === 'string' &&
plugin.source.startsWith('team:plugin:') &&
(
!exactWorkspaceId ||
!workspaceResources?.workspaceTeamPluginBindingAllowsRead ||
!workspaceResources.workspaceTeamPluginBindingAllowsRead(
db,
exactWorkspaceId,
req.params.id,
)
)
) {
return res.status(404).json({ error: 'plugin not found' });
}
const connectorProbe = helpers.buildConnectorProbe(helpers.connectorService);
const computed = plugins.applyPlugin({ plugin, inputs, registry, locale, connectorProbe });
if (grantCaps.length > 0) {
const merged = new Set([...computed.result.capabilitiesGranted, ...grantCaps]);
computed.result.capabilitiesGranted = Array.from(merged);
computed.result.appliedPlugin.capabilitiesGranted = Array.from(merged);
}
res.json({
ok: true,
...computed.result,
warnings: computed.warnings,
manifestSourceDigest: computed.manifestSourceDigest,
});
} catch (err: unknown) {
if (err instanceof plugins.MissingInputError) {
return res.status(422).json({ error: 'missing_inputs', fields: err.fields });
}
res.status(500).json({ error: String(err) });
}
});
app.post('/api/plugins/:id/duplicate-project', helpers.requireLocalDaemonRequest, async (req, res) => {
let cleanupProjectId: string | null = null;
let insertedProject = false;
try {
const pluginId = Array.isArray(req.params.id) ? req.params.id[0] ?? '' : req.params.id ?? '';
const authority = await resolveWorkspaceAuthority(req, res);
if (authority === undefined) return;
const plugin = await resolveRequestPlugin(pluginId, authority);
if (!plugin) return res.status(404).json({ error: { code: 'plugin-not-found', message: 'plugin not found' } });
if (typeof plugin.id !== 'string' || typeof plugin.fsPath !== 'string') {
return res.status(422).json({ error: { code: 'plugin-not-duplicable', message: 'plugin record is missing a filesystem source' } });
}
// AC-9 copy red-line (D3): a frozen team plugin cannot be duplicated into a
// personal project. Runs before any project is created (nothing to clean up
// if it throws). No-op until the resource-hub reports this plugin as a
// frozen team resource.
if (teamResources) {
await enforceTeamResourceCopyAllowed(teamResources, { kind: 'plugin', resourceId: plugin.id });
}
const createWorkspace = await authorizeCreatedProjectWorkspace(
req,
deps.fetchProjectCreationWorkspaceDirectory,
);
if (!createWorkspace.ok) {
return sendCreatedProjectWorkspaceError(res, createWorkspace);
}
const body = req.body && typeof req.body === 'object'
? req.body as PluginDuplicateProjectRequest
: {};
const projectName = typeof body.name === 'string' && body.name.trim().length > 0
? body.name.trim().slice(0, 120)
: `${plugin.title || plugin.id}`;
const now = Date.now();
const projectId = ids.randomId();
const conversationId = ids.randomId();
cleanupProjectId = projectId;
const metadata: ProjectMetadata = {
kind: 'prototype',
templateId: `plugin:${plugin.id}`,
templateLabel: plugin.title || plugin.id,
duplicatedFromPluginId: plugin.id,
skipDiscoveryBrief: true,
};
const duplicate = await duplicatePluginExampleIntoProject({
plugin: plugin as InstalledPluginRecord,
projectsRoot: paths.PROJECTS_DIR,
projectId,
metadata,
assembleExample: helpers.assembleExample,
});
metadata.duplicatedFromPluginEntry = duplicate.sourceEntry;
metadata.entryFile = duplicate.relPath;
const project = db.transaction(() => {
const createdProject = projectStore.insertProject(db, {
id: projectId,
name: projectName,
skillId: null,
designSystemId: null,
pendingPrompt: null,
metadata,
createdAt: now,
updatedAt: now,
});
insertedProject = true;
conversations.insertConversation(db, {
id: conversationId,
projectId,
title: null,
createdAt: now,
updatedAt: now,
});
bindCreatedProjectToWorkspace(
(input) => projectStore.ensureWorkspaceProject(db, input),
createWorkspace.context,
projectId,
now,
);
return createdProject;
})();
const loadedProject = projectStore.getProject(db, projectId) ?? project;
if (!loadedProject) {
throw new PluginDuplicateProjectError(
500,
'project-load-failed',
'created project could not be loaded',
);
}
const response: PluginDuplicateProjectResponse = {
ok: true,
projectId,
conversationId,
relPath: duplicate.relPath,
project: loadedProject,
sourcePluginId: plugin.id,
sourceEntry: duplicate.sourceEntry,
copiedFiles: duplicate.copiedFiles,
skippedFiles: duplicate.skippedFiles,
warnings: duplicate.warnings,
};
res.status(201).json(response);
} catch (err: unknown) {
if (cleanupProjectId) {
try {
if (insertedProject) projectStore.dbDeleteProject(db, cleanupProjectId);
} catch {
// The transaction normally rolled the rows back already. A failed
// compensating DELETE must never strand the managed filesystem copy.
} finally {
await projectStore.removeProjectDir(paths.PROJECTS_DIR, cleanupProjectId).catch(() => {});
}
}
if (err instanceof TeamResourceCopyForbiddenError) {
return res.status(403).json({ error: { code: err.code, message: err.message } });
}
if (err instanceof PluginDuplicateProjectError) {
return res.status(err.status).json({ error: { code: err.code, message: err.message } });
}
res.status(500).json({ error: { code: 'plugin-duplicate-failed', message: err instanceof Error ? err.message : String(err) } });
}
});
app.post('/api/plugins/:id/share-project', async (req, res) => helpers.handleShareProject(req, res));
app.post('/api/plugins/:id/doctor', async (req, res) => { try { const authority = await resolveWorkspaceAuthority(req, res); if (authority === undefined) return; const plugin = await resolveRequestPlugin(req.params.id, authority); if (!plugin) return res.status(404).json({ error: 'plugin not found' }); const registry = await helpers.loadPluginRegistryView(); const connectorProbe = helpers.buildConnectorProbe(helpers.connectorService); res.json(plugins.doctorPlugin(plugin, registry, { connectorProbe })); } catch (err) { res.status(500).json({ error: String(err) }); } });
app.post('/api/plugins/:id/trust', async (req, res) => helpers.handlePluginTrust(req, res));
app.get('/api/plugins/stats', async (_req, res) => helpers.handlePluginStats(res));
app.get('/api/applied-plugins/:snapshotId', (req, res) => { try { const snap = plugins.getSnapshot(db, req.params.snapshotId); if (!snap) return res.status(404).json({ error: 'snapshot not found' }); res.json(snap); } catch (err) { res.status(500).json({ error: String(err) }); } });
app.get('/api/applied-plugins/:snapshotId/canon', (req, res) => { try { const snap = plugins.getSnapshot(db, req.params.snapshotId); if (!snap) return res.status(404).json({ error: 'snapshot not found' }); const block = plugins.pluginPromptBlock(snap); const accepts = String(req.headers.accept ?? '').toLowerCase(); if (accepts.includes('text/plain')) { res.setHeader('Content-Type', 'text/plain; charset=utf-8'); res.send(block); return; } res.json({ snapshotId: snap.snapshotId, pluginId: snap.pluginId, block }); } catch (err) { res.status(500).json({ error: String(err) }); } });
app.get('/api/applied-plugins', (_req, res) => { try { const rows = db.prepare(`SELECT id FROM applied_plugin_snapshots ORDER BY applied_at DESC LIMIT 500`).all() as SqliteRowId[]; res.json({ snapshots: rows.map((r) => plugins.getSnapshot(db, r.id)).filter((x): x is AppliedPluginSnapshotLike => x !== null) }); } catch (err) { res.status(500).json({ error: String(err) }); } });
app.get('/api/projects/:projectId/applied-plugins', async (req, res) => {
try {
if (!await deps.authorizeProjectRequest(
req,
res,
req.params.projectId,
{ mode: 'read' },
)) return;
const rows = db.prepare(
`SELECT id FROM applied_plugin_snapshots WHERE project_id = ? ORDER BY applied_at DESC`,
).all(req.params.projectId) as SqliteRowId[];
res.json({
snapshots: rows
.map((row) => plugins.getSnapshot(db, row.id))
.filter((snapshot): snapshot is AppliedPluginSnapshotLike => snapshot !== null),
});
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
app.post('/api/applied-plugins/export', helpers.requireLocalDaemonRequest, async (req, res) => helpers.handleAppliedPluginExport(req, res));
app.post('/api/applied-plugins/prune', async (req, res) => { try { const body = req.body && typeof req.body === 'object' ? req.body : {}; const before = typeof body.before === 'number' ? body.before : undefined; const result = plugins.pruneExpiredSnapshots(db, before ? { before } : {}); if (result.removed > 0) { try { const { recordPluginEvent } = await import('../../plugins/events.js'); recordPluginEvent({ kind: 'plugin.snapshot-pruned', pluginId: '', details: { removed: result.removed, ...(before ? { before } : {}) } }); } catch {} } res.json({ ok: true, removed: result.removed, ids: result.ids }); } catch (err) { res.status(500).json({ error: String(err) }); } });
}
export function registerProjectPluginRoutes(app: Express, deps: RegisterPluginRoutesDeps): void {
const { db, paths, plugins, helpers } = deps;
const authorizeWrite = (req: Request, res: Response, projectId: string) =>
deps.authorizeProjectRequest(
req,
res,
projectId,
{ mode: 'write', capability: 'writeFiles' },
);
app.post('/api/projects/:id/plugins/install-folder', async (req, res) => {
if (!await authorizeWrite(req, res, req.params.id)) return;
return helpers.handleProjectInstallFolder(req, res);
});
app.post('/api/projects/:id/plugins/publish-github', async (req, res) => {
if (!await authorizeWrite(req, res, req.params.id)) return;
return helpers.handleProjectPluginCli(req, res, 'publish-github');
});
app.get('/api/projects/:id/plugin-candidates', async (req, res) => {
try {
const project = helpers.getProject(db, req.params.id);
if (!project) {
return helpers.sendApiError(res, 404, 'PROJECT_NOT_FOUND', 'project not found');
}
if (!await deps.authorizeProjectRequest(req, res, req.params.id, { mode: 'read' })) return;
const includeDismissed = req.query.includeDismissed === 'true';
res.json({
candidates: plugins.listSkillPluginCandidates(db, req.params.id, includeDismissed),
});
} catch (err: unknown) {
res.status(400).json({ error: err instanceof Error ? err.message : String(err) });
}
});
app.post('/api/projects/:id/plugin-candidates/:candidateId/dismiss', async (req, res) => {
if (!helpers.isLocalSameOrigin(req, helpers.resolvedPortRef.current)) {
return res.status(403).json({ error: 'cross-origin request rejected' });
}
if (!await authorizeWrite(req, res, req.params.id)) return;
const candidate = plugins.dismissSkillPluginCandidate(
db,
req.params.id,
req.params.candidateId,
);
if (!candidate) {
return helpers.sendApiError(res, 404, 'NOT_FOUND', 'plugin candidate not found');
}
if (candidate.assistantMessageId) {
db.prepare(`DELETE FROM messages WHERE id = ?`).run(candidate.assistantMessageId);
}
res.json({ ok: true, candidate });
});
app.post('/api/projects/:id/plugin-candidates/:candidateId/draft', async (req, res) => {
if (!await authorizeWrite(req, res, req.params.id)) return;
return helpers.handleCandidateDraft(req, res);
});
app.post('/api/projects/:id/plugin-candidates/:candidateId/share-tasks', async (req, res) => {
if (!await authorizeWrite(req, res, req.params.id)) return;
return helpers.handleCandidateShareTask(req, res);
});
app.post('/api/projects/:id/plugins/contribute-open-design', async (req, res) => {
if (!await authorizeWrite(req, res, req.params.id)) return;
return helpers.handleProjectPluginCli(req, res, 'contribute-open-design');
});
app.post('/api/projects/:id/plugins/share-tasks', async (req, res) => {
if (!await authorizeWrite(req, res, req.params.id)) return;
return helpers.handleProjectShareTask(req, res);
});
app.post('/api/plugins/share-tasks/:id/wait', async (req, res) => {
if (!helpers.isLocalSameOrigin(req, helpers.resolvedPortRef.current)) return res.status(403).json({ error: 'cross-origin request rejected' });
const task = helpers.pluginShareTaskStore.get(req.params.id);
if (!task) return res.status(404).json({ error: 'task not found' });
if (!await deps.authorizeProjectRequest(req, res, task.projectId, { mode: 'read' })) return;
const since = Number.isFinite(req.body?.since) ? Number(req.body.since) : 0;
const requestedTimeout = Number.isFinite(req.body?.timeoutMs) ? Number(req.body.timeoutMs) : 25_000;
const timeoutMs = Math.min(Math.max(requestedTimeout, 0), 25_000);
const respond = () => { if (!res.writableEnded) res.json(helpers.pluginShareTaskStore.snapshot(task, since)); };
if (task.status === 'done' || task.status === 'failed' || task.progress.length > since) return respond();
let resolved = false;
const wake = () => { if (resolved) return; resolved = true; task.waiters.delete(wake); clearTimeout(timer); respond(); };
task.waiters.add(wake);
const timer = setTimeout(wake, timeoutMs);
res.on('close', wake);
});
}