@blackbelt-technology/pi-dashboard-team-plugin 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +101 -0
  2. package/dist/app/assets/InlineTerminalCard-6GBZ9nXN.css +32 -0
  3. package/dist/app/assets/InlineTerminalCard-BRjmM13k.js +53 -0
  4. package/dist/app/assets/PdfPreview-CCfKQhLL.js +2 -0
  5. package/dist/app/assets/RichDiff-BU1YI0CM.css +19 -0
  6. package/dist/app/assets/RichDiff-zrt7rxm3.js +41 -0
  7. package/dist/app/assets/abnfDiagram-VCTEODGH-BNRJZIa7.js +1 -0
  8. package/dist/app/assets/arc-Ccw1WVCw.js +1 -0
  9. package/dist/app/assets/architectureDiagram-5GKGNRK7-CmpCS5s2.js +36 -0
  10. package/dist/app/assets/blockDiagram-I7D4REHJ-M5oRqDla.js +129 -0
  11. package/dist/app/assets/c4Diagram-7LVT6UL2-C6v6KvuZ.js +38 -0
  12. package/dist/app/assets/channel-1wFLoesq.js +1 -0
  13. package/dist/app/assets/chunk-2Q5K7J3B-BrSnR-LD.js +1 -0
  14. package/dist/app/assets/chunk-5VM5RSS4-BAqdD3be.js +15 -0
  15. package/dist/app/assets/chunk-F27PBJKO-DNLocP_Z.js +1 -0
  16. package/dist/app/assets/chunk-IMKFNOWR-DwFLWoAj.js +231 -0
  17. package/dist/app/assets/chunk-JWPE2WC7-DwOQUkPK.js +1 -0
  18. package/dist/app/assets/chunk-POPQ4Y6H-CN6vxbUi.js +1 -0
  19. package/dist/app/assets/chunk-SVP7TREG-mfOuPsxp.js +88 -0
  20. package/dist/app/assets/chunk-TICWLB2K-R4JNWs6J.js +206 -0
  21. package/dist/app/assets/chunk-XXDRQBXY-Bwj8o9dr.js +1 -0
  22. package/dist/app/assets/classDiagram-ZZMXUADV-DeqkIaZ-.js +1 -0
  23. package/dist/app/assets/classDiagram-v2-VYDZK3BY-DeqkIaZ-.js +1 -0
  24. package/dist/app/assets/cose-bilkent-JH36ORCC-qCY2WMN8.js +1 -0
  25. package/dist/app/assets/cursor-editorTextHighlight-kG3uUOwL.svg +8 -0
  26. package/dist/app/assets/cynefin-OW5HDTMX-CNttFTW2.js +178 -0
  27. package/dist/app/assets/cynefinDiagram-5FMLGOSQ-CBX-RJXy.js +62 -0
  28. package/dist/app/assets/cytoscape.esm-Bch-eiPH.js +331 -0
  29. package/dist/app/assets/dagre-GXQ25YYZ-D-VD0Tcu.js +4 -0
  30. package/dist/app/assets/defaultLocale-DX6XiGOO.js +1 -0
  31. package/dist/app/assets/diagram-S7CK7UJ4-CQReIUYr.js +30 -0
  32. package/dist/app/assets/diagram-UQ7AKVKN-DyEU0WYX.js +41 -0
  33. package/dist/app/assets/diagram-VSXAHHWV-NLLDj0k8.js +3 -0
  34. package/dist/app/assets/diagram-VX7I27RA-Daf-u6xI.js +24 -0
  35. package/dist/app/assets/diagram-Z3DM3KII-B0O71sZp.js +24 -0
  36. package/dist/app/assets/ebnfDiagram-PWID7BFC-BSRAXWwk.js +1 -0
  37. package/dist/app/assets/erDiagram-RLTQ6QDP-DKoQjGux.js +99 -0
  38. package/dist/app/assets/flowDiagram-HODETNUW-gq74Q1SF.js +168 -0
  39. package/dist/app/assets/ganttDiagram-EL5Y4UJY-BIAOolFj.js +292 -0
  40. package/dist/app/assets/gitGraphDiagram-WWUBYQGX-BvZquV67.js +106 -0
  41. package/dist/app/assets/index-BTj-g2DX.js +559 -0
  42. package/dist/app/assets/index-owClP-R3.css +1 -0
  43. package/dist/app/assets/infoDiagram-27XIBGKW-dMwJRmit.js +2 -0
  44. package/dist/app/assets/init-Gi6I4Gst.js +1 -0
  45. package/dist/app/assets/ishikawaDiagram-5VMMS53U-DArpl74K.js +70 -0
  46. package/dist/app/assets/journeyDiagram-3NMN7TZE-B2sUGe5l.js +139 -0
  47. package/dist/app/assets/kanban-definition-UXKFOSKX-Cx6oCBKM.js +89 -0
  48. package/dist/app/assets/layout-BjHuHx4m.js +1 -0
  49. package/dist/app/assets/linear-CgCYMSPy.js +1 -0
  50. package/dist/app/assets/mdi-DoP81khn.js +1 -0
  51. package/dist/app/assets/mermaid.core-DiBBwf02.js +312 -0
  52. package/dist/app/assets/mindmap-definition-YA3MSWOX-DP2Penfk.js +96 -0
  53. package/dist/app/assets/ordinal-Cboi1Yqb.js +1 -0
  54. package/dist/app/assets/pdf-CcZYcL52.js +12 -0
  55. package/dist/app/assets/pdf.worker.min-CNKzwYUy.js +1 -0
  56. package/dist/app/assets/pdf.worker.min-yatZIOMy.mjs +21 -0
  57. package/dist/app/assets/pdf_viewer-BXbC1ghE.js +346 -0
  58. package/dist/app/assets/pdf_viewer-I4ZZuHqo.css +1 -0
  59. package/dist/app/assets/pegDiagram-XKGWAZYB-DuPy_Jk1.js +1 -0
  60. package/dist/app/assets/pieDiagram-E7YTZNPT-BHJIw8Ie.js +39 -0
  61. package/dist/app/assets/quadrantDiagram-AXDQQJYC-CKJDe9v8.js +7 -0
  62. package/dist/app/assets/railroadDiagram-O6MQD6OU-CPmw2XqA.js +1 -0
  63. package/dist/app/assets/requirementDiagram-BXWQKSXE-CbgXwlu-.js +84 -0
  64. package/dist/app/assets/sankeyDiagram-P5KCCOFB-xTHr7bNV.js +40 -0
  65. package/dist/app/assets/sequenceDiagram-WJ2MYXX4-BJO_VejT.js +162 -0
  66. package/dist/app/assets/sizeCapture-INFHLROL-BOIqspBs.js +1 -0
  67. package/dist/app/assets/stateDiagram-D77RDMKH-B1M9C9C6.js +1 -0
  68. package/dist/app/assets/stateDiagram-v2-MP3YSRHH-BWPtAAkO.js +1 -0
  69. package/dist/app/assets/swimlanes-42K2YHIH-BtpfWryU.js +1 -0
  70. package/dist/app/assets/swimlanesDiagram-VR7AAH4N-CRZvPlTl.js +8 -0
  71. package/dist/app/assets/timeline-definition-24CTP7MA-BaspCbTG.js +120 -0
  72. package/dist/app/assets/vennDiagram-4TSXK5OY-Rzs4n1uC.js +34 -0
  73. package/dist/app/assets/wardleyDiagram-VM6X3IG4-7u6IS5Iz.js +78 -0
  74. package/dist/app/assets/xychartDiagram-S5SC5T6Z-D-TnlcEC.js +7 -0
  75. package/dist/app/index.html +13 -0
  76. package/package.json +82 -0
  77. package/src/client/FolderTeamSection.tsx +96 -0
  78. package/src/client/TeamProjectDialog.tsx +202 -0
  79. package/src/client/index.tsx +9 -0
  80. package/src/client/match-store.ts +107 -0
  81. package/src/client/team-open.ts +27 -0
  82. package/src/configSchema.json +104 -0
  83. package/src/extension/guard.ts +97 -0
  84. package/src/extension/index.ts +44 -0
  85. package/src/i18n.ts +64 -0
  86. package/src/server/access.ts +43 -0
  87. package/src/server/conversations.ts +799 -0
  88. package/src/server/index.ts +39 -0
  89. package/src/server/paths.ts +164 -0
  90. package/src/server/persona.ts +167 -0
  91. package/src/server/personas-service.ts +178 -0
  92. package/src/server/projects.ts +294 -0
  93. package/src/server/records.ts +130 -0
  94. package/src/server/render.ts +50 -0
  95. package/src/server/routes.ts +239 -0
  96. package/src/server/static.ts +73 -0
  97. package/src/server/store-types.ts +8 -0
  98. package/src/server/store.ts +94 -0
  99. package/src/server/team.ts +105 -0
  100. package/src/server/text-write.ts +15 -0
  101. package/src/server/types.ts +112 -0
  102. package/src/server/users.ts +47 -0
@@ -0,0 +1,239 @@
1
+ /**
2
+ * REST surface (D9) under `/api/plugins/team`, in an encapsulated scope with
3
+ * the shared rate limiter. See change: add-team-plugin.
4
+ */
5
+ import rateLimit from "@fastify/rate-limit";
6
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
7
+ import type { Access } from "./access.js";
8
+ import type { ConversationService } from "./conversations.js";
9
+ import { isTargetId } from "./paths.js";
10
+ import type { PersonaService } from "./personas-service.js";
11
+ import type { ProjectRegistry } from "./projects.js";
12
+ import { type Caller, TeamError, WORKSPACE_TARGET } from "./types.js";
13
+ import type { UsersStore } from "./users.js";
14
+
15
+ const API_PREFIX = "/api/plugins/team";
16
+
17
+ export interface RouteDeps {
18
+ access: Access;
19
+ personas: PersonaService;
20
+ projects: ProjectRegistry;
21
+ conversations: ConversationService;
22
+ users: UsersStore;
23
+ /** Admin skill catalog names (personas pick names only). */
24
+ skills: () => string[];
25
+ logger: { warn(msg: string): void; error(msg: string): void };
26
+ }
27
+
28
+ /** `POST /projects/match`: one count per project per request, duplicate cwds answered from the first lookup. */
29
+ function matchFolders(d: RouteDeps, c: Caller, cwds: string[]) {
30
+ const mode = d.access.mode();
31
+ const counts = new Map<string, { agents: number; active: number }>();
32
+ const byCwd = new Map<string, unknown>();
33
+ const row = (cwd: string) => {
34
+ const p = d.projects.resolveFolder(c, mode, cwd);
35
+ if (p && !counts.has(p.id)) counts.set(p.id, d.conversations.folderCounts(c, p.id));
36
+ const n = p ? counts.get(p.id) : undefined;
37
+ return {
38
+ cwd,
39
+ project: p ? { id: p.id, name: p.name, available: p.available, source: p.source, agents: n?.agents ?? 0, active: n?.active ?? 0 } : null,
40
+ enableable: d.projects.enableable(c, cwd),
41
+ manageable: !!p && p.source === "folder" && c.admin,
42
+ };
43
+ };
44
+ return {
45
+ results: cwds.map((cwd) => {
46
+ if (!byCwd.has(cwd)) byCwd.set(cwd, row(cwd));
47
+ return byCwd.get(cwd);
48
+ }),
49
+ };
50
+ }
51
+
52
+ export async function mountTeamRoutes(fastify: FastifyInstance, d: RouteDeps): Promise<void> {
53
+ await fastify.register(async (scope) => {
54
+ await scope.register(rateLimit, {
55
+ global: true,
56
+ max: 100_000,
57
+ timeWindow: "1 minute",
58
+ allowList: ["127.0.0.1", "::1"],
59
+ });
60
+
61
+ // Encapsulated: never replaces the dashboard's own error handler.
62
+ scope.setErrorHandler((err: unknown, _req, reply) => {
63
+ if (err instanceof TeamError) {
64
+ const body: Record<string, unknown> = { error: err.code };
65
+ if (err.details && typeof err.details === "object") Object.assign(body, err.details);
66
+ return reply.code(err.status).send(body);
67
+ }
68
+ const e = err as { statusCode?: number; code?: string };
69
+ if (typeof e.statusCode === "number" && e.statusCode >= 400 && e.statusCode < 500) {
70
+ return reply.code(e.statusCode).send({ error: "bad_request" });
71
+ }
72
+ d.logger.error(`team.route_error ${err instanceof Error ? err.message : String(err)}`);
73
+ return reply.code(500).send({ error: "internal_error" });
74
+ });
75
+
76
+ const caller = (req: FastifyRequest): Caller => {
77
+ const c = d.access.callerOf(req);
78
+ if (!c) throw new TeamError(401, "unauthorized");
79
+ return c;
80
+ };
81
+ /** `?project=` — syntax always; existence/allowance only where `mustExist` (agents list, create). */
82
+ const target = (req: FastifyRequest, c: Caller, mustExist = false): string => {
83
+ const t = (req.query as { project?: unknown })?.project;
84
+ if (typeof t !== "string" || !isTargetId(t)) throw new TeamError(400, "invalid_target");
85
+ if (mustExist && t !== WORKSPACE_TARGET) {
86
+ const p = d.projects.get(t);
87
+ if (!p || !d.projects.canUse(p, c, d.access.mode())) throw new TeamError(404, "project_not_found");
88
+ }
89
+ return t;
90
+ };
91
+ const P = (path: string) => `${API_PREFIX}${path}`;
92
+ const wrap =
93
+ (fn: (req: FastifyRequest, reply: FastifyReply, c: Caller) => unknown) =>
94
+ async (req: FastifyRequest, reply: FastifyReply) =>
95
+ fn(req, reply, caller(req));
96
+
97
+ // ── identity ────────────────────────────────────────────────────────────
98
+ scope.get(
99
+ P("/me"),
100
+ wrap((_req, _reply, c) => {
101
+ if (d.access.mode() === "multi") d.users.record(c);
102
+ return { uk: c.uk, iss: c.iss, sub: c.sub, admin: c.admin, mode: d.access.mode(), maxConversations: d.conversations.limit(), skills: d.skills() };
103
+ }),
104
+ );
105
+
106
+ // ── projects ────────────────────────────────────────────────────────────
107
+ scope.get(
108
+ P("/projects"),
109
+ wrap((_req, _reply, c) => ({
110
+ projects: d.projects.usableBy(c, d.access.mode()).map((p) => ({
111
+ id: p.id,
112
+ name: p.name,
113
+ contextFiles: p.contextFiles,
114
+ available: p.available,
115
+ source: p.source,
116
+ ...(c.admin ? { path: p.path, users: p.users } : {}),
117
+ })),
118
+ })),
119
+ );
120
+
121
+ scope.post(
122
+ P("/projects/match"),
123
+ wrap((req, _reply, c) => {
124
+ const cwds = (req.body as { cwds?: unknown } | undefined)?.cwds;
125
+ if (!Array.isArray(cwds) || cwds.length < 1 || cwds.length > 200 || !cwds.every((x) => typeof x === "string")) {
126
+ throw new TeamError(400, "invalid_cwds");
127
+ }
128
+ return matchFolders(d, c, cwds as string[]);
129
+ }),
130
+ );
131
+
132
+ scope.post(
133
+ P("/projects"),
134
+ wrap((req, reply, c) => {
135
+ const r = d.projects.enable(c, (req.body ?? {}) as Record<string, unknown>);
136
+ return reply.code(201).send(r);
137
+ }),
138
+ );
139
+ scope.patch(
140
+ P("/projects/:id"),
141
+ wrap((req, _reply, c) => {
142
+ d.projects.patch(c, (req.params as { id: string }).id, (req.body ?? {}) as Record<string, unknown>);
143
+ return { ok: true };
144
+ }),
145
+ );
146
+ scope.delete(
147
+ P("/projects/:id"),
148
+ wrap((req, _reply, c) => {
149
+ d.projects.disable(c, (req.params as { id: string }).id);
150
+ return { ok: true };
151
+ }),
152
+ );
153
+ scope.get(
154
+ P("/users"),
155
+ wrap((_req, _reply, c) => {
156
+ if (d.access.mode() === "single") throw new TeamError(404, "not_found");
157
+ if (!c.admin) throw new TeamError(403, "admin_required");
158
+ return { users: d.users.list() };
159
+ }),
160
+ );
161
+
162
+ // ── personas ────────────────────────────────────────────────────────────
163
+ scope.get(P("/personas"), wrap((_req, _reply, c) => ({ personas: d.personas.list(c) })));
164
+ scope.post(
165
+ P("/personas"),
166
+ wrap((req, reply, c) => reply.code(201).send(d.personas.create(c, req.body))),
167
+ );
168
+ scope.put(
169
+ P("/personas/:key"),
170
+ wrap((req, _reply, c) => d.personas.update(c, (req.params as { key: string }).key, req.body)),
171
+ );
172
+ scope.delete(
173
+ P("/personas/:key"),
174
+ wrap((req, _reply, c) => {
175
+ d.personas.remove(c, (req.params as { key: string }).key);
176
+ return { ok: true };
177
+ }),
178
+ );
179
+ scope.post(
180
+ P("/personas/:key/fork"),
181
+ wrap((req, reply, c) => reply.code(201).send(d.personas.fork(c, (req.params as { key: string }).key, req.body))),
182
+ );
183
+
184
+ // ── agents + conversations ──────────────────────────────────────────────
185
+ scope.get(
186
+ P("/agents"),
187
+ wrap((req, _reply, c) => ({ agents: d.conversations.agents(c, target(req, c, true)) })),
188
+ );
189
+ scope.get(
190
+ P("/agents/:key/conversations"),
191
+ wrap((req, _reply, c) => {
192
+ const t = target(req, c);
193
+ const archived = (req.query as { archived?: string }).archived === "true";
194
+ return { conversations: d.conversations.listConversations(c, (req.params as { key: string }).key, t, archived) };
195
+ }),
196
+ );
197
+ scope.post(
198
+ P("/agents/:key/conversations"),
199
+ wrap(async (req, reply, c) => {
200
+ const t = target(req, c, true);
201
+ return reply.code(201).send(await d.conversations.createConversation(c, (req.params as { key: string }).key, t));
202
+ }),
203
+ );
204
+ scope.post(
205
+ P("/agents/:key/conversations/:c/session"),
206
+ wrap(async (req, _reply, c) => {
207
+ const t = target(req, c);
208
+ const p = req.params as { key: string; c: string };
209
+ return d.conversations.ensureConversation(c, p.key, t, p.c);
210
+ }),
211
+ );
212
+ scope.patch(
213
+ P("/agents/:key/conversations/:c"),
214
+ wrap(async (req, _reply, c) => {
215
+ const t = target(req, c);
216
+ const p = req.params as { key: string; c: string };
217
+ return d.conversations.patchConversation(c, p.key, t, p.c, (req.body ?? {}) as Record<string, unknown>);
218
+ }),
219
+ );
220
+ scope.post(
221
+ P("/agents/:key/conversations/:c/restart"),
222
+ wrap(async (req, _reply, c) => {
223
+ const t = target(req, c);
224
+ const p = req.params as { key: string; c: string };
225
+ await d.conversations.restartConversation(c, p.key, t, p.c);
226
+ return { ok: true };
227
+ }),
228
+ );
229
+ scope.delete(
230
+ P("/agents/:key/conversations/:c"),
231
+ wrap(async (req, _reply, c) => {
232
+ const t = target(req, c);
233
+ const p = req.params as { key: string; c: string };
234
+ await d.conversations.deleteConversation(c, p.key, t, p.c);
235
+ return { ok: true };
236
+ }),
237
+ );
238
+ });
239
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Same-origin app delivery (D14): `/apps/team` → 308, `/apps/team/*` → file
3
+ * under `dist/app/` (realpath-confined) or `index.html` for deep links.
4
+ * See change: add-team-plugin.
5
+ */
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import type { FastifyInstance, FastifyReply } from "fastify";
9
+
10
+ const APP_PREFIX = "/apps/team";
11
+
12
+ const TYPES: Record<string, string> = {
13
+ ".html": "text/html; charset=utf-8",
14
+ ".js": "text/javascript; charset=utf-8",
15
+ ".mjs": "text/javascript; charset=utf-8",
16
+ ".css": "text/css; charset=utf-8",
17
+ ".json": "application/json; charset=utf-8",
18
+ ".svg": "image/svg+xml",
19
+ ".png": "image/png",
20
+ ".ico": "image/x-icon",
21
+ ".woff2": "font/woff2",
22
+ ".map": "application/json; charset=utf-8",
23
+ ".txt": "text/plain; charset=utf-8",
24
+ };
25
+
26
+ export function mountAppRoutes(fastify: FastifyInstance, distDir: string, logger: { warn(msg: string): void }): void {
27
+ let warned = false;
28
+ const send = (reply: FastifyReply, file: string, immutable: boolean) => {
29
+ const ext = path.extname(file).toLowerCase();
30
+ return reply
31
+ .header("Content-Type", TYPES[ext] ?? "application/octet-stream")
32
+ .header("Cache-Control", immutable ? "public, max-age=31536000, immutable" : "no-store")
33
+ .header("X-Content-Type-Options", "nosniff")
34
+ .send(fs.readFileSync(file));
35
+ };
36
+
37
+ fastify.get(APP_PREFIX, async (_req, reply) => reply.redirect(`${APP_PREFIX}/`, 308));
38
+
39
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: many small independent branches (field / state rendering); splitting would scatter one linear flow
40
+ fastify.get(`${APP_PREFIX}/*`, async (req, reply) => {
41
+ let root: string;
42
+ try {
43
+ root = fs.realpathSync(distDir);
44
+ if (!fs.existsSync(path.join(root, "index.html"))) throw new Error("no index");
45
+ } catch {
46
+ if (!warned) {
47
+ warned = true;
48
+ logger.warn("team.app_build_missing");
49
+ }
50
+ return reply.code(503).header("Content-Type", "text/plain; charset=utf-8").send("team app build missing");
51
+ }
52
+ const rawUrl = req.raw.url ?? "";
53
+ const pathname = rawUrl.split("?")[0].slice(APP_PREFIX.length + 1);
54
+ let rel: string;
55
+ try {
56
+ rel = decodeURIComponent(pathname);
57
+ } catch {
58
+ rel = "";
59
+ }
60
+ // Traversal / NUL ⇒ treat as a deep link (index.html), never a file outside root.
61
+ if (rel && !rel.includes("\0")) {
62
+ const candidate = path.resolve(root, rel);
63
+ try {
64
+ const real = fs.realpathSync(candidate);
65
+ const within = real === root || real.startsWith(root + path.sep);
66
+ if (within && fs.statSync(real).isFile()) return send(reply, real, rel.startsWith("assets/"));
67
+ } catch {
68
+ /* fall through to index */
69
+ }
70
+ }
71
+ return send(reply, path.join(root, "index.html"), false);
72
+ });
73
+ }
@@ -0,0 +1,8 @@
1
+ import type { Persona } from "./types.js";
2
+
3
+ /** Read side of the persona store used by the conversation service. */
4
+ export interface PersonaStore {
5
+ get(key: string, uk: string): Persona | null;
6
+ listShared(): Persona[];
7
+ listPrivate(uk: string): Persona[];
8
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Persona store (D2/D3): one JSON file per persona, atomic writes, unknown
3
+ * schemaVersion skipped on read. See change: add-team-plugin.
4
+ */
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { atomicWriteJson, type FsOps, parsePersonaKey, realFs, type TeamPaths } from "./paths.js";
8
+ import { type Persona, TeamError } from "./types.js";
9
+
10
+ export interface StoreLogger {
11
+ warn(msg: string): void;
12
+ }
13
+
14
+ export class PersonaStore {
15
+ constructor(
16
+ private readonly paths: TeamPaths,
17
+ private readonly logger: StoreLogger,
18
+ private readonly ops: FsOps = realFs,
19
+ ) {}
20
+
21
+ private dirFor(scope: "shared" | "private", uk: string): string {
22
+ return scope === "shared" ? this.paths.sharedPersonasDir() : this.paths.privatePersonasDir(uk);
23
+ }
24
+
25
+ private fileFor(scope: "shared" | "private", slug: string, uk: string): string {
26
+ return this.paths.confine(path.join(this.dirFor(scope, uk), `${slug}.json`));
27
+ }
28
+
29
+ private readDir(dir: string): Persona[] {
30
+ let names: string[];
31
+ try {
32
+ names = fs.readdirSync(dir).filter((n) => n.endsWith(".json"));
33
+ } catch {
34
+ return [];
35
+ }
36
+ const out: Persona[] = [];
37
+ for (const n of names) {
38
+ try {
39
+ const raw = JSON.parse(fs.readFileSync(path.join(dir, n), "utf8")) as Persona;
40
+ if (raw?.schemaVersion !== 1) {
41
+ this.logger.warn(`team.persona_skipped file=${n} reason=schema_version`);
42
+ continue;
43
+ }
44
+ out.push(raw);
45
+ } catch {
46
+ this.logger.warn(`team.persona_skipped file=${n} reason=unreadable`);
47
+ }
48
+ }
49
+ return out.sort((a, b) => a.name.localeCompare(b.name));
50
+ }
51
+
52
+ listShared(): Persona[] {
53
+ return this.readDir(this.paths.sharedPersonasDir());
54
+ }
55
+
56
+ listPrivate(uk: string): Persona[] {
57
+ return this.readDir(this.paths.privatePersonasDir(uk));
58
+ }
59
+
60
+ /** `private:` keys resolve inside the caller's own folder only. */
61
+ get(key: string, uk: string): Persona | null {
62
+ const p = parsePersonaKey(key);
63
+ if (!p) return null;
64
+ try {
65
+ const raw = JSON.parse(fs.readFileSync(this.fileFor(p.scope, p.slug, uk), "utf8")) as Persona;
66
+ return raw?.schemaVersion === 1 ? raw : null;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+
72
+ exists(key: string, uk: string): boolean {
73
+ return this.get(key, uk) !== null;
74
+ }
75
+
76
+ put(persona: Persona, uk: string): void {
77
+ const p = parsePersonaKey(persona.key);
78
+ if (!p) throw new TeamError(400, "invalid_persona_key");
79
+ atomicWriteJson(this.fileFor(p.scope, p.slug, uk), persona, this.ops);
80
+ }
81
+
82
+ remove(key: string, uk: string): boolean {
83
+ const p = parsePersonaKey(key);
84
+ if (!p) return false;
85
+ const file = this.fileFor(p.scope, p.slug, uk);
86
+ if (!fs.existsSync(file)) return false;
87
+ fs.rmSync(file, { force: true });
88
+ return true;
89
+ }
90
+
91
+ count(scope: "shared" | "private", uk: string): number {
92
+ return this.readDir(this.dirFor(scope, uk)).length;
93
+ }
94
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Composition root: builds the team services from narrow host ports, so the
3
+ * whole stack is testable without a real host. See change: add-team-plugin.
4
+ */
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import type { FastifyInstance } from "fastify";
9
+ import { type Access, createAccess, type IdentityLike } from "./access.js";
10
+ import { ConversationService, type HostPort, type Logger } from "./conversations.js";
11
+ import { type FsOps, realFs, resolveTeamHome, TeamPaths } from "./paths.js";
12
+ import { PersonaService } from "./personas-service.js";
13
+ import { ProjectRegistry } from "./projects.js";
14
+ import { RecordStore } from "./records.js";
15
+ import { writePersonaFile } from "./render.js";
16
+ import { mountTeamRoutes } from "./routes.js";
17
+ import { mountAppRoutes } from "./static.js";
18
+ import { PersonaStore } from "./store.js";
19
+ import type { Persona, TeamConfig } from "./types.js";
20
+ import { UsersStore } from "./users.js";
21
+
22
+ export interface TeamDeps {
23
+ host: HostPort;
24
+ identity?: IdentityLike;
25
+ fastify: FastifyInstance;
26
+ config: () => TeamConfig;
27
+ logger: Logger;
28
+ guardExtensionPath: string;
29
+ distAppDir: string;
30
+ env?: NodeJS.ProcessEnv;
31
+ piDir?: string;
32
+ ops?: FsOps;
33
+ spawnTimeoutMs?: number;
34
+ now?: () => number;
35
+ renderPersona?: (persona: Persona, uk: string) => string;
36
+ sweepEveryMs?: number;
37
+ }
38
+
39
+ export interface Team {
40
+ paths: TeamPaths;
41
+ access: Access;
42
+ conversations: ConversationService;
43
+ personas: PersonaService;
44
+ projects: ProjectRegistry;
45
+ start(): Promise<void>;
46
+ stop(): void;
47
+ }
48
+
49
+ export function createTeam(d: TeamDeps): Team {
50
+ const paths = new TeamPaths(resolveTeamHome(d.config().teamHome, d.env));
51
+ const access = createAccess(d.identity, d.config);
52
+ const ops = d.ops ?? realFs;
53
+ const store = new PersonaStore(paths, d.logger, ops);
54
+ const projects = new ProjectRegistry({
55
+ paths,
56
+ config: d.config,
57
+ logger: d.logger,
58
+ piDir: d.piDir ?? path.join(os.homedir(), ".pi"),
59
+ ops,
60
+ });
61
+ const records = new RecordStore(paths, ops);
62
+ const users = new UsersStore(paths, ops);
63
+ const conversations = new ConversationService({
64
+ host: d.host,
65
+ access,
66
+ paths,
67
+ personas: store,
68
+ projects,
69
+ records,
70
+ config: d.config,
71
+ logger: d.logger,
72
+ guardExtensionPath: d.guardExtensionPath,
73
+ renderPersona: d.renderPersona ?? ((persona, uk) => writePersonaFile(paths.runtimeDir(uk, persona.key), persona)),
74
+ spawnTimeoutMs: d.spawnTimeoutMs,
75
+ now: d.now,
76
+ });
77
+ const personas = new PersonaService({ store, projects, access, config: d.config });
78
+
79
+ return {
80
+ paths,
81
+ access,
82
+ conversations,
83
+ personas,
84
+ projects,
85
+ async start() {
86
+ if (!fs.existsSync(d.guardExtensionPath)) {
87
+ d.logger.error("team.guard_missing: starting a conversation will answer 503 guard_unavailable");
88
+ }
89
+ await mountTeamRoutes(d.fastify, {
90
+ access,
91
+ personas,
92
+ projects,
93
+ conversations,
94
+ users,
95
+ skills: () => Object.keys(d.config().skillCatalog ?? {}),
96
+ logger: d.logger,
97
+ });
98
+ mountAppRoutes(d.fastify, d.distAppDir, d.logger);
99
+ conversations.start(d.sweepEveryMs);
100
+ },
101
+ stop() {
102
+ conversations.stop();
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,15 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ /** Atomic text write (tmp + rename). */
5
+ export function atomicWriteText(file: string, data: string): void {
6
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
7
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
8
+ try {
9
+ fs.writeFileSync(tmp, data, { mode: 0o600 });
10
+ fs.renameSync(tmp, file);
11
+ } catch (err) {
12
+ fs.rmSync(tmp, { force: true });
13
+ throw err;
14
+ }
15
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Shared types for the team plugin server. See change: add-team-plugin.
3
+ */
4
+
5
+ export type PersonaScope = "shared" | "private";
6
+ export type PersonaRole = "leader" | "member";
7
+ export type ToolsPreset = "chat" | "files" | "full";
8
+ export type AvatarSpec = { kind: "gallery"; id: string } | { kind: "initials" };
9
+
10
+ /** Target id: a project id or the own workspace. */
11
+ export const WORKSPACE_TARGET = "_ws";
12
+
13
+ export interface Persona {
14
+ schemaVersion: 1;
15
+ /** `"<scope>:<slug>"`. */
16
+ key: string;
17
+ scope: PersonaScope;
18
+ owner?: { iss: string; sub: string };
19
+ name: string;
20
+ description: string;
21
+ avatar: AvatarSpec;
22
+ role: PersonaRole;
23
+ model?: string;
24
+ instructions: string;
25
+ tools: ToolsPreset;
26
+ projects: string[];
27
+ skills?: string[];
28
+ forkedFrom?: string;
29
+ createdAt: string;
30
+ updatedAt: string;
31
+ updatedBy: string;
32
+ }
33
+
34
+ /** The acting user, resolved per request. */
35
+ export interface Caller {
36
+ /** 32-hex user key, or `local`. */
37
+ uk: string;
38
+ iss: string;
39
+ sub: string;
40
+ email?: string;
41
+ name?: string;
42
+ admin: boolean;
43
+ }
44
+
45
+ export type Mode = "single" | "multi";
46
+
47
+ interface PersonaSnapshot {
48
+ name: string;
49
+ description: string;
50
+ avatar: AvatarSpec;
51
+ role: PersonaRole;
52
+ model?: string;
53
+ }
54
+
55
+ export interface ConversationRecord {
56
+ schemaVersion: 1;
57
+ c: string;
58
+ personaKey: string;
59
+ project: string;
60
+ sessionId: string;
61
+ sessionFile?: string;
62
+ runId: string;
63
+ spawnToken: string;
64
+ createdAt: string;
65
+ startedAt: string;
66
+ lastActivityAt: string;
67
+ lastAgentEndAt?: string;
68
+ personaUpdatedAt: string;
69
+ title?: string;
70
+ archived: boolean;
71
+ personaSnapshot: PersonaSnapshot;
72
+ }
73
+
74
+ export interface ProjectConfigEntry {
75
+ name: string;
76
+ path: string;
77
+ users: "*" | { iss: string; sub: string }[];
78
+ contextFiles?: boolean;
79
+ }
80
+
81
+ export interface Project {
82
+ id: string;
83
+ name: string;
84
+ /** Validated realpath; undefined when unavailable. */
85
+ path?: string;
86
+ users: "*" | { iss: string; sub: string }[];
87
+ contextFiles: boolean;
88
+ source: "config" | "folder";
89
+ available: boolean;
90
+ }
91
+
92
+ /** HTTP-level error carrying a machine code. */
93
+ export class TeamError extends Error {
94
+ constructor(
95
+ public readonly status: number,
96
+ public readonly code: string,
97
+ public readonly details?: unknown,
98
+ ) {
99
+ super(code);
100
+ }
101
+ }
102
+
103
+ export interface TeamConfig {
104
+ admins?: { iss: string; sub: string }[];
105
+ skillCatalog?: Record<string, string>;
106
+ idleMinutes?: number;
107
+ maxConversations?: number;
108
+ /** Live pi processes per user (default 10). */
109
+ maxLiveSessions?: number;
110
+ teamHome?: string;
111
+ projects?: Record<string, ProjectConfigEntry>;
112
+ }
@@ -0,0 +1,47 @@
1
+ /** Known team users (recorded on `GET /me`), for the folder-enable user picker. */
2
+ import fs from "node:fs";
3
+ import { atomicWriteJson, type FsOps, realFs, type TeamPaths } from "./paths.js";
4
+ import type { Caller } from "./types.js";
5
+
6
+ export interface KnownUser {
7
+ iss: string;
8
+ sub: string;
9
+ email?: string;
10
+ name?: string;
11
+ lastSeenAt: string;
12
+ }
13
+
14
+ export class UsersStore {
15
+ constructor(
16
+ private readonly paths: TeamPaths,
17
+ private readonly ops: FsOps = realFs,
18
+ ) {}
19
+
20
+ list(): KnownUser[] {
21
+ try {
22
+ const raw = JSON.parse(fs.readFileSync(this.paths.usersFile(), "utf8")) as { schemaVersion?: number; users?: KnownUser[] };
23
+ return raw?.schemaVersion === 1 && Array.isArray(raw.users) ? raw.users : [];
24
+ } catch {
25
+ return [];
26
+ }
27
+ }
28
+
29
+ record(caller: Caller, now: Date = new Date()): void {
30
+ const users = this.list();
31
+ const i = users.findIndex((u) => u.iss === caller.iss && u.sub === caller.sub);
32
+ const prev = users[i];
33
+ const same = prev && prev.email === caller.email && prev.name === caller.name;
34
+ // `lastSeenAt` is a coarse hint: skip the file rewrite unless the profile changed or an hour passed.
35
+ if (same && now.getTime() - Date.parse(prev.lastSeenAt) < 3_600_000) return;
36
+ const entry: KnownUser = {
37
+ iss: caller.iss,
38
+ sub: caller.sub,
39
+ ...(caller.email ? { email: caller.email } : {}),
40
+ ...(caller.name ? { name: caller.name } : {}),
41
+ lastSeenAt: now.toISOString(),
42
+ };
43
+ if (i >= 0) users[i] = entry;
44
+ else users.push(entry);
45
+ atomicWriteJson(this.paths.usersFile(), { schemaVersion: 1, users: users.slice(-1000) }, this.ops);
46
+ }
47
+ }