@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,799 @@
1
+ /**
2
+ * Conversations, agents and the idle sweeper (D5/D8). One conversation = one
3
+ * persistent pi session found-or-resumed on demand. The host is reached only
4
+ * through the narrow {@link HostPort}, so the service is unit-testable with a
5
+ * fake. See change: add-team-plugin.
6
+ */
7
+ import { randomBytes, randomUUID } from "node:crypto";
8
+ import fs from "node:fs";
9
+ import type { PluginSpawnOptions } from "@blackbelt-technology/dashboard-plugin-runtime/server";
10
+ import { piSessionDirForCwd } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
11
+ import { PRESET_TOOLS } from "../extension/guard.js";
12
+ import type { Access } from "./access.js";
13
+ import { canonicalize, type TeamPaths, userKey } from "./paths.js";
14
+ import { cpLength } from "./persona.js";
15
+ import type { ProjectRegistry } from "./projects.js";
16
+ import type { LocatedRecord, Locator, RecordStore } from "./records.js";
17
+ import { collectContextFiles } from "./render.js";
18
+ import type { PersonaStore } from "./store-types.js";
19
+ import {
20
+ type AvatarSpec,
21
+ type Caller,
22
+ type ConversationRecord,
23
+ type Persona,
24
+ type PersonaRole,
25
+ type Project,
26
+ type TeamConfig,
27
+ TeamError,
28
+ WORKSPACE_TARGET,
29
+ } from "./types.js";
30
+
31
+ export interface HostSession {
32
+ id: string;
33
+ cwd: string;
34
+ status: "active" | "idle" | "streaming" | "ended";
35
+ sessionFile?: string;
36
+ name?: string;
37
+ firstMessage?: string;
38
+ principalOwner?: { iss: string; sub: string };
39
+ /** `pluginRefs[pluginId]` = the whole ref the plugin filed at spawn. */
40
+ pluginRefs?: Record<string, Record<string, unknown>>;
41
+ }
42
+
43
+ export interface HostPort {
44
+ spawnSession(opts: PluginSpawnOptions): Promise<{ success: boolean; message?: string; spawnToken?: string }>;
45
+ abortSpawnedRun(args: { sessionId?: string; spawnToken?: string; graceful?: boolean }): Promise<boolean> | boolean;
46
+ getSession(id: string): HostSession | undefined;
47
+ listAll(): HostSession[];
48
+ onSessionResolved(h: (sessionId: string, ref: Record<string, unknown>) => void): () => void;
49
+ onEvent(h: (sessionId: string, event: unknown) => void): () => void;
50
+ registerPiHandler(type: string, h: (msg: unknown, sessionId: string) => void): void;
51
+ }
52
+
53
+ export interface Logger {
54
+ info(msg: string): void;
55
+ warn(msg: string): void;
56
+ error(msg: string): void;
57
+ }
58
+
59
+ export interface ServiceDeps {
60
+ host: HostPort;
61
+ access: Access;
62
+ paths: TeamPaths;
63
+ personas: PersonaStore;
64
+ projects: ProjectRegistry;
65
+ records: RecordStore;
66
+ config: () => TeamConfig;
67
+ logger: Logger;
68
+ /** Absolute path of the team guard extension (`-e`). */
69
+ guardExtensionPath: string;
70
+ /** Renders persona.md for (persona, uk) and returns its absolute path. */
71
+ renderPersona: (persona: Persona, uk: string) => string;
72
+ now?: () => number;
73
+ spawnTimeoutMs?: number;
74
+ /** Delivered with each spawn so the guard knows its root + preset. */
75
+ sessionDirFor?: (cwd: string) => string;
76
+ }
77
+
78
+ const GUARD_READY_MESSAGE = "team_guard_ready";
79
+ const DEFAULT_MAX_CONVERSATIONS = 50;
80
+ const DEFAULT_IDLE_MINUTES = 30;
81
+ const DEFAULT_MAX_LIVE_SESSIONS = 10;
82
+ /** `lastActivityAt` writes caused by streaming events are coalesced to at most one per this interval. */
83
+ const ACTIVITY_WRITE_MS = 10_000;
84
+ /** An event older than this is treated as replayed history. */
85
+ const REPLAY_AGE_MS = 120_000;
86
+
87
+ export type ConvStatus = "busy" | "running" | "sleeping";
88
+ type AgentStatus = ConvStatus | "new" | "retired" | "unavailable";
89
+
90
+ export interface ConversationView {
91
+ id: string;
92
+ title: string;
93
+ status: ConvStatus;
94
+ lastActivityAt: string;
95
+ archived: boolean;
96
+ personaStale: boolean;
97
+ }
98
+
99
+ export interface AgentView {
100
+ key: string;
101
+ name: string;
102
+ description: string;
103
+ avatar: AvatarSpec;
104
+ role: PersonaRole;
105
+ model?: string;
106
+ scope: "shared" | "private";
107
+ tools: "chat" | "files" | "full";
108
+ unconfined: boolean;
109
+ status: AgentStatus;
110
+ activeCount: number;
111
+ latest?: { id: string; title: string; status: ConvStatus; lastActivityAt: string };
112
+ personaStale: boolean;
113
+ unassigned: boolean;
114
+ retired: boolean;
115
+ }
116
+
117
+ interface Pending {
118
+ sessionId?: string;
119
+ ready: boolean;
120
+ settle: () => void;
121
+ }
122
+
123
+ /** `end` = `agent_end`, `activity` = turn / message start; replayed history and everything else ⇒ null. */
124
+ function classifyLiveEvent(event: unknown, now: number): "end" | "activity" | null {
125
+ const e = event as { eventType?: string; timestamp?: number; replay?: boolean } | undefined;
126
+ if (!e || e.replay === true) return null;
127
+ if (typeof e.timestamp === "number" && now - e.timestamp > REPLAY_AGE_MS) return null;
128
+ if (e.eventType === "agent_end") return "end";
129
+ return e.eventType === "agent_start" || e.eventType === "message_start" ? "activity" : null;
130
+ }
131
+
132
+ function newConversationId(): string {
133
+ return randomBytes(16).toString("base64url");
134
+ }
135
+
136
+ export class ConversationService {
137
+ private readonly inFlight = new Map<string, Promise<unknown>>();
138
+ private readonly createLocks = new Map<string, Promise<void>>();
139
+ /** Launches admitted but not yet bound, per user (live-cap reservation). */
140
+ private readonly launching = new Map<string, number>();
141
+ private readonly pending = new Map<string, Pending>();
142
+ /** runId → sessionId, from the guard's `team_guard_ready` (bounded). */
143
+ private readonly readyRuns = new Map<string, string>();
144
+ /** Last time a record was persisted for activity (debounce), by session id. */
145
+ private readonly activityWrittenAt = new Map<string, number>();
146
+ private readonly unsubs: Array<() => void> = [];
147
+ private sweepTimer: ReturnType<typeof setInterval> | undefined;
148
+
149
+ constructor(private readonly d: ServiceDeps) {}
150
+
151
+ private now(): number {
152
+ return this.d.now?.() ?? Date.now();
153
+ }
154
+ private iso(ms = this.now()): string {
155
+ return new Date(ms).toISOString();
156
+ }
157
+ private maxConversations(): number {
158
+ const v = this.d.config().maxConversations;
159
+ return typeof v === "number" && v >= 1 ? Math.floor(v) : DEFAULT_MAX_CONVERSATIONS;
160
+ }
161
+ /** Active-conversation cap per user × agent × target (config, default 50). */
162
+ limit(): number {
163
+ return this.maxConversations();
164
+ }
165
+ private idleMs(): number {
166
+ const v = this.d.config().idleMinutes;
167
+ return (typeof v === "number" && v >= 0 ? v : DEFAULT_IDLE_MINUTES) * 60_000;
168
+ }
169
+
170
+ // ── lifecycle ──────────────────────────────────────────────────────────────
171
+
172
+ start(sweepEveryMs = 5 * 60_000): void {
173
+ this.d.records.scanAll();
174
+ this.d.host.registerPiHandler(GUARD_READY_MESSAGE, (msg, sessionId) => {
175
+ const runId = (msg as { payload?: { runId?: unknown } } | undefined)?.payload?.runId;
176
+ if (typeof runId !== "string" || runId.length === 0) return;
177
+ this.readyRuns.set(runId, sessionId);
178
+ if (this.readyRuns.size > 1000) {
179
+ const oldest = this.readyRuns.keys().next().value;
180
+ if (oldest !== undefined) this.readyRuns.delete(oldest);
181
+ }
182
+ this.pending.get(runId)?.settle();
183
+ });
184
+ this.unsubs.push(
185
+ this.d.host.onSessionResolved((sessionId, ref) => {
186
+ const team = ref?.team as { runId?: unknown } | undefined;
187
+ const runId = typeof team?.runId === "string" ? team.runId : undefined;
188
+ if (!runId) return;
189
+ const p = this.pending.get(runId);
190
+ if (!p) {
191
+ // Late arrival of a run we already gave up on: make sure it does not linger.
192
+ void this.d.host.abortSpawnedRun({ sessionId, graceful: false });
193
+ return;
194
+ }
195
+ p.sessionId = sessionId;
196
+ p.settle();
197
+ }),
198
+ this.d.host.onEvent((sessionId, event) => this.onEvent(sessionId, event)),
199
+ );
200
+ this.sweepIdle();
201
+ if (sweepEveryMs > 0) {
202
+ this.sweepTimer = setInterval(() => this.sweepIdle(), sweepEveryMs);
203
+ this.sweepTimer.unref?.();
204
+ }
205
+ }
206
+
207
+ stop(): void {
208
+ for (const u of this.unsubs.splice(0)) u();
209
+ if (this.sweepTimer) clearInterval(this.sweepTimer);
210
+ this.sweepTimer = undefined;
211
+ }
212
+
213
+ private onEvent(sessionId: string, event: unknown): void {
214
+ const loc = this.d.records.locate(sessionId);
215
+ if (!loc) return;
216
+ const kind = classifyLiveEvent(event, this.now());
217
+ if (!kind) return;
218
+ const isEnd = kind === "end";
219
+ // Streaming events fire many times per turn: coalesce activity writes, always persist the turn end.
220
+ if (!isEnd && this.now() - (this.activityWrittenAt.get(sessionId) ?? 0) < ACTIVITY_WRITE_MS) return;
221
+ const rec = this.d.records.read(loc);
222
+ if (!rec || rec.sessionId !== sessionId) return;
223
+ const stamp = this.iso();
224
+ this.activityWrittenAt.set(sessionId, this.now());
225
+ if (isEnd) {
226
+ rec.lastAgentEndAt = stamp;
227
+ rec.lastActivityAt = stamp;
228
+ } else {
229
+ rec.lastActivityAt = stamp;
230
+ }
231
+ const s = this.d.host.getSession(sessionId);
232
+ if (s?.sessionFile && s.sessionFile !== rec.sessionFile) rec.sessionFile = s.sessionFile;
233
+ this.d.records.write(loc, rec);
234
+ }
235
+
236
+ /** End sessions idle past `idleMinutes` (never `busy`). */
237
+ sweepIdle(): void {
238
+ const idle = this.idleMs();
239
+ if (idle === 0) return;
240
+ for (const lr of this.d.records.scanAll()) {
241
+ const r = lr.record;
242
+ if (r.archived) continue;
243
+ const s = this.d.host.getSession(r.sessionId);
244
+ if (!s || s.status === "ended" || s.status === "streaming") continue;
245
+ // Multi-user: only end a session the record's user owns (a misbound record must not reach another user's).
246
+ if (this.d.access.mode() === "multi" && (!s.principalOwner || userKey(s.principalOwner.iss, s.principalOwner.sub) !== lr.uk)) continue;
247
+ const last = Date.parse(r.lastAgentEndAt ?? r.lastActivityAt ?? r.startedAt);
248
+ if (Number.isFinite(last) && this.now() - last > idle) {
249
+ void this.d.host.abortSpawnedRun({ sessionId: r.sessionId, graceful: true });
250
+ }
251
+ }
252
+ }
253
+
254
+ // ── resolution helpers ─────────────────────────────────────────────────────
255
+
256
+ private persona(caller: Caller, key: string): Persona {
257
+ const p = this.d.personas.get(key, caller.uk);
258
+ if (!p) throw new TeamError(404, "persona_not_found");
259
+ return p;
260
+ }
261
+
262
+ /** Persona's `projects` ids still usable by the caller (or `_ws`). */
263
+ private effectiveProjects(p: Persona, usable: ReadonlySet<string>): Set<string> {
264
+ return new Set(p.projects.filter((id) => id === WORKSPACE_TARGET || usable.has(id)));
265
+ }
266
+
267
+ /** Resolve target `t` to its root directory (D13). */
268
+ private target(caller: Caller, persona: Persona, t: string, existing = false): { dir: string; project?: Project } {
269
+ if (t === WORKSPACE_TARGET) {
270
+ if (!persona.projects.includes(WORKSPACE_TARGET)) throw new TeamError(409, "persona_not_in_project");
271
+ const dir = this.d.paths.workspaceDir(caller.uk);
272
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
273
+ return { dir: canonicalize(dir) };
274
+ }
275
+ const project = this.d.projects.get(t);
276
+ if (!project || !this.d.projects.canUse(project, caller, this.d.access.mode())) {
277
+ // An existing conversation on a removed / no-longer-allowed project stays listed but cannot continue.
278
+ throw new TeamError(existing ? 409 : 404, existing ? "project_unavailable" : "project_not_found");
279
+ }
280
+ if (!persona.projects.includes(t)) throw new TeamError(409, "persona_not_in_project");
281
+ if (!project.available || !project.path) throw new TeamError(409, "project_unavailable");
282
+ return { dir: project.path, project };
283
+ }
284
+
285
+ private owner(caller: Caller): { iss: string; sub: string } | undefined {
286
+ return this.d.access.mode() === "multi" ? { iss: caller.iss, sub: caller.sub } : undefined;
287
+ }
288
+
289
+ private ownerMatches(s: HostSession, caller: Caller): boolean {
290
+ if (this.d.access.mode() === "single") return true;
291
+ return s.principalOwner?.iss === caller.iss && s.principalOwner?.sub === caller.sub;
292
+ }
293
+
294
+ private loc(caller: Caller, personaKey: string, t: string, c: string): Locator {
295
+ return { uk: caller.uk, t, personaKey, c };
296
+ }
297
+
298
+ private requireRecord(caller: Caller, personaKey: string, t: string, c: string): { l: Locator; rec: ConversationRecord } {
299
+ const l = this.loc(caller, personaKey, t, c);
300
+ const rec = this.d.records.read(l);
301
+ if (!rec) throw new TeamError(404, "conversation_not_found");
302
+ return { l, rec };
303
+ }
304
+
305
+ /**
306
+ * The host stores the WHOLE ref we filed under `pluginRefs.<pluginId>`, i.e.
307
+ * `pluginRefs.team = { team: { personaKey, project, conversationId, uk, runId }, principalOwner }`.
308
+ */
309
+ private teamRef(s: HostSession | undefined): { personaKey?: unknown; project?: unknown; conversationId?: unknown } | undefined {
310
+ const filed = s?.pluginRefs?.team as { team?: unknown } | undefined;
311
+ const t = filed?.team;
312
+ return t && typeof t === "object" ? (t as { personaKey?: unknown; project?: unknown; conversationId?: unknown }) : undefined;
313
+ }
314
+
315
+ private ownLive(rec: ConversationRecord, c: string): HostSession | undefined {
316
+ const s = this.d.host.getSession(rec.sessionId);
317
+ if (!s || this.teamRef(s)?.conversationId !== c) return undefined;
318
+ return s;
319
+ }
320
+
321
+ private statusOf(rec: ConversationRecord, c: string): ConvStatus {
322
+ const s = this.ownLive(rec, c);
323
+ if (!s || s.status === "ended") return "sleeping";
324
+ return s.status === "streaming" ? "busy" : "running";
325
+ }
326
+
327
+ private titleOf(rec: ConversationRecord, c: string): string {
328
+ if (rec.title) return rec.title;
329
+ const s = this.d.host.getSession(rec.sessionId);
330
+ if (s?.name) return s.name;
331
+ if (s?.firstMessage) return [...s.firstMessage.trim()].slice(0, 60).join("");
332
+ return `Beszélgetés · ${rec.createdAt.slice(0, 10)}`;
333
+ }
334
+
335
+ /**
336
+ * "Restart to apply" only makes sense for a LIVE session: a sleeping conversation (idle-ended or
337
+ * just restarted) already picks the current persona up on its next start.
338
+ */
339
+ private isStale(rec: ConversationRecord, c: string, persona: Persona | null): boolean {
340
+ return !!persona && persona.updatedAt > rec.personaUpdatedAt && this.statusOf(rec, c) !== "sleeping";
341
+ }
342
+
343
+ private view(lr: { c: string; record: ConversationRecord }, persona: Persona | null): ConversationView {
344
+ const rec = lr.record;
345
+ return {
346
+ id: lr.c,
347
+ title: this.titleOf(rec, lr.c),
348
+ status: this.statusOf(rec, lr.c),
349
+ lastActivityAt: rec.lastActivityAt,
350
+ archived: rec.archived,
351
+ personaStale: this.isStale(rec, lr.c, persona),
352
+ };
353
+ }
354
+
355
+ // ── spawn + bind ───────────────────────────────────────────────────────────
356
+
357
+ private logEnsure(caller: Caller, personaKey: string, t: string, c: string, outcome: string, sessionId?: string): void {
358
+ this.d.logger.info(
359
+ `team.ensure uk=${caller.uk} personaKey=${personaKey} t=${t} c=${c} outcome=${outcome} sessionId=${sessionId ?? "-"}`,
360
+ );
361
+ }
362
+
363
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: many small independent branches (field / state rendering); splitting would scatter one linear flow
364
+ private async launch(
365
+ caller: Caller,
366
+ persona: Persona,
367
+ t: string,
368
+ c: string,
369
+ root: { dir: string; project?: Project },
370
+ resumeFile?: string,
371
+ ): Promise<{ sessionId: string; sessionFile?: string; runId: string; spawnToken: string; release: () => void }> {
372
+ if (!fs.existsSync(this.d.guardExtensionPath)) throw new TeamError(503, "guard_unavailable");
373
+ // An unconfined (`full`) persona must never run in multi-user mode, whatever mode it was authored in.
374
+ if (persona.tools === "full" && this.d.access.mode() === "multi") throw new TeamError(409, "persona_unavailable");
375
+ const personaFile = this.d.renderPersona(persona, caller.uk);
376
+ if (!fs.existsSync(personaFile)) {
377
+ this.d.logger.error(`team.persona_render_failed personaKey=${persona.key}`);
378
+ throw new TeamError(500, "persona_render_failed");
379
+ }
380
+ const contextFiles = root.project?.contextFiles ? collectContextFiles(root.dir) : [];
381
+ const runId = randomUUID();
382
+ const spawnToken = randomUUID();
383
+ const catalog = this.d.config().skillCatalog ?? {};
384
+ const skills = (persona.skills ?? []).map((n) => catalog[n]).filter((p): p is string => typeof p === "string");
385
+ const ownerStamp = this.owner(caller);
386
+
387
+ let settleFn: () => void = () => {};
388
+ const settled = new Promise<void>((resolve) => {
389
+ settleFn = resolve;
390
+ });
391
+ const entry: Pending = { ready: false, settle: () => {} };
392
+ const readyAndBound = () => !!entry.sessionId && this.readyRuns.get(runId) === entry.sessionId;
393
+ entry.settle = () => {
394
+ if (readyAndBound()) settleFn();
395
+ };
396
+ const releaseSlot = this.reserveLiveSlot(caller);
397
+ this.pending.set(runId, entry);
398
+
399
+ const timeoutMs = this.d.spawnTimeoutMs ?? 30_000;
400
+ let timer: ReturnType<typeof setTimeout> | undefined;
401
+ const timedOut = new Promise<"timeout">((resolve) => {
402
+ timer = setTimeout(() => resolve("timeout"), timeoutMs);
403
+ timer.unref?.();
404
+ });
405
+
406
+ try {
407
+ const res = await this.d.host.spawnSession({
408
+ cwd: root.dir,
409
+ ...(persona.model ? { model: persona.model } : {}),
410
+ pluginRef: {
411
+ team: { personaKey: persona.key, project: t, conversationId: c, uk: caller.uk, runId },
412
+ ...(ownerStamp ? { principalOwner: ownerStamp } : {}),
413
+ },
414
+ lifecycle: { recover: false, finalizeOnSocketClose: true },
415
+ scope: {
416
+ tools: [...PRESET_TOOLS[persona.tools]],
417
+ ...(skills.length ? { skills } : {}),
418
+ extensions: [this.d.guardExtensionPath],
419
+ extensionConfig: { team: { persona: personaFile, root: root.dir, tools: persona.tools, runId } },
420
+ appendSystemPrompt: [personaFile, ...contextFiles],
421
+ noContextFiles: true,
422
+ noProjectTrust: true,
423
+ sessionDir: (this.d.sessionDirFor ?? ((cwd: string) => piSessionDirForCwd(cwd)))(root.dir),
424
+ },
425
+ spawnToken,
426
+ ...(resumeFile ? { resume: { sessionFile: resumeFile } } : {}),
427
+ });
428
+ if (!res.success) {
429
+ this.pending.delete(runId);
430
+ throw new TeamError(503, "spawn_failed");
431
+ }
432
+ entry.settle();
433
+ const outcome = await Promise.race([settled.then(() => "ok" as const), timedOut]);
434
+ if (outcome === "timeout") {
435
+ const sid = entry.sessionId;
436
+ this.pending.delete(runId);
437
+ await this.d.host.abortSpawnedRun(sid ? { sessionId: sid, graceful: false } : { spawnToken });
438
+ if (sid) throw new TeamError(503, "guard_unavailable");
439
+ throw new TeamError(504, "spawn_timeout");
440
+ }
441
+ this.pending.delete(runId);
442
+ const sessionId = entry.sessionId as string;
443
+ const s = this.d.host.getSession(sessionId);
444
+ // The caller releases the slot AFTER the record is written, so the new session is never uncounted.
445
+ return { sessionId, sessionFile: s?.sessionFile, runId, spawnToken, release: releaseSlot };
446
+ } catch (err) {
447
+ this.pending.delete(runId);
448
+ releaseSlot();
449
+ throw err;
450
+ } finally {
451
+ if (timer) clearTimeout(timer);
452
+ this.readyRuns.delete(runId);
453
+ }
454
+ }
455
+
456
+ // ── create / ensure ────────────────────────────────────────────────────────
457
+
458
+ /** Live pi processes are bounded per user (not only per conversation list), `maxLiveSessions` default 10. */
459
+ private reserveLiveSlot(caller: Caller): () => void {
460
+ const cap = this.d.config().maxLiveSessions;
461
+ const limit = typeof cap === "number" && cap >= 1 ? Math.floor(cap) : DEFAULT_MAX_LIVE_SESSIONS;
462
+ let live = 0;
463
+ for (const lr of this.d.records.scanAll()) {
464
+ if (lr.uk !== caller.uk) continue;
465
+ const s = this.d.host.getSession(lr.record.sessionId);
466
+ if (s && s.status !== "ended") live++;
467
+ }
468
+ // In-flight launches count too: admission is synchronous, so concurrent creates cannot all see room.
469
+ const inFlight = this.launching.get(caller.uk) ?? 0;
470
+ if (live + inFlight >= limit) throw new TeamError(429, "session_limit");
471
+ this.launching.set(caller.uk, inFlight + 1);
472
+ return () => {
473
+ const n = (this.launching.get(caller.uk) ?? 1) - 1;
474
+ if (n <= 0) this.launching.delete(caller.uk);
475
+ else this.launching.set(caller.uk, n);
476
+ };
477
+ }
478
+
479
+ private activeCount(caller: Caller, t: string, personaKey: string): number {
480
+ return this.d.records.list(caller.uk, t, personaKey).filter((r) => !r.record.archived).length;
481
+ }
482
+
483
+ private snapshot(p: Persona) {
484
+ return { name: p.name, description: p.description, avatar: p.avatar, role: p.role, ...(p.model ? { model: p.model } : {}) };
485
+ }
486
+
487
+ async createConversation(caller: Caller, personaKey: string, t: string): Promise<{ id: string; sessionId: string }> {
488
+ const persona = this.persona(caller, personaKey);
489
+ const root = this.target(caller, persona, t);
490
+ const lockKey = `${caller.uk}|${personaKey}|${t}`;
491
+ const prev = this.createLocks.get(lockKey) ?? Promise.resolve();
492
+ let release: () => void = () => {};
493
+ const mine = new Promise<void>((r) => {
494
+ release = r;
495
+ });
496
+ const tail = prev.then(() => mine);
497
+ this.createLocks.set(lockKey, tail);
498
+ await prev;
499
+ try {
500
+ if (this.activeCount(caller, t, personaKey) >= this.maxConversations()) throw new TeamError(409, "conversation_limit");
501
+ const c = newConversationId();
502
+ let bound: Awaited<ReturnType<ConversationService["launch"]>>;
503
+ try {
504
+ bound = await this.launch(caller, persona, t, c, root);
505
+ } catch (err) {
506
+ if (err instanceof TeamError && (err.code === "spawn_timeout" || err.code === "guard_unavailable")) {
507
+ this.logEnsure(caller, personaKey, t, c, err.code === "spawn_timeout" ? "timeout" : "guard_unavailable");
508
+ }
509
+ throw err;
510
+ }
511
+ try {
512
+ const stamp = this.iso();
513
+ const rec: ConversationRecord = {
514
+ schemaVersion: 1,
515
+ c,
516
+ personaKey,
517
+ project: t,
518
+ sessionId: bound.sessionId,
519
+ ...(bound.sessionFile ? { sessionFile: bound.sessionFile } : {}),
520
+ runId: bound.runId,
521
+ spawnToken: bound.spawnToken,
522
+ createdAt: stamp,
523
+ startedAt: stamp,
524
+ lastActivityAt: stamp,
525
+ personaUpdatedAt: persona.updatedAt,
526
+ archived: false,
527
+ personaSnapshot: this.snapshot(persona),
528
+ };
529
+ this.d.records.write(this.loc(caller, personaKey, t, c), rec);
530
+ this.logEnsure(caller, personaKey, t, c, "create", bound.sessionId);
531
+ return { id: c, sessionId: bound.sessionId };
532
+ } finally {
533
+ bound.release();
534
+ }
535
+ } finally {
536
+ release();
537
+ void tail.then(() => {
538
+ if (this.createLocks.get(lockKey) === tail) this.createLocks.delete(lockKey);
539
+ });
540
+ }
541
+ }
542
+
543
+ async ensureConversation(caller: Caller, personaKey: string, t: string, c: string): Promise<{ sessionId: string }> {
544
+ const { rec } = this.requireRecord(caller, personaKey, t, c);
545
+ if (rec.archived) throw new TeamError(409, "conversation_archived");
546
+ const key = `${caller.uk}|${personaKey}|${t}|${c}`;
547
+ const existing = this.inFlight.get(key) as Promise<{ sessionId: string }> | undefined;
548
+ if (existing !== undefined) return existing;
549
+ const p = this.ensureInner(caller, personaKey, t, c).finally(() => {
550
+ this.inFlight.delete(key);
551
+ });
552
+ this.inFlight.set(key, p);
553
+ return p;
554
+ }
555
+
556
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: many small independent branches (field / state rendering); splitting would scatter one linear flow
557
+ private async ensureInner(caller: Caller, personaKey: string, t: string, c: string): Promise<{ sessionId: string }> {
558
+ const l = this.loc(caller, personaKey, t, c);
559
+ const rec = this.d.records.read(l);
560
+ if (!rec) throw new TeamError(404, "conversation_not_found");
561
+ const persona = this.persona(caller, personaKey);
562
+ const root = this.target(caller, persona, t, true);
563
+
564
+ // 3. reuse
565
+ const live = this.ownLive(rec, c);
566
+ const team = this.teamRef(live);
567
+ if (
568
+ live &&
569
+ live.status !== "ended" &&
570
+ canonicalize(live.cwd) === root.dir &&
571
+ this.ownerMatches(live, caller) &&
572
+ team?.personaKey === personaKey &&
573
+ team?.project === t
574
+ ) {
575
+ this.logEnsure(caller, personaKey, t, c, "reuse", rec.sessionId);
576
+ return { sessionId: rec.sessionId };
577
+ }
578
+ if (live && live.status !== "ended") {
579
+ // Ownership BEFORE any side effect: a live session that is not this user's is never touched.
580
+ if (!this.ownerMatches(live, caller)) {
581
+ this.logEnsure(caller, personaKey, t, c, "unrecoverable", rec.sessionId);
582
+ throw new TeamError(409, "conversation_unrecoverable");
583
+ }
584
+ // Ours but not reusable (cwd moved): end it before resuming.
585
+ await this.d.host.abortSpawnedRun({ sessionId: rec.sessionId, graceful: true });
586
+ }
587
+
588
+ // 4. resume
589
+ const known = this.d.host.getSession(rec.sessionId);
590
+ const file = rec.sessionFile ?? known?.sessionFile;
591
+ const fileExists = !!file && fs.existsSync(file);
592
+ // Owner-fail-closed (D5 step 4): in multi-user mode an existing transcript is only resumed when the host's
593
+ // persisted session record proves it is this user's; a session the host cannot vouch for is never adopted.
594
+ const ownerOk = known ? this.ownerMatches(known, caller) : !(this.d.access.mode() === "multi" && fileExists);
595
+ const neverTalked = !rec.lastAgentEndAt;
596
+ if (!ownerOk || (!fileExists && !neverTalked)) {
597
+ this.logEnsure(caller, personaKey, t, c, "unrecoverable", rec.sessionId);
598
+ throw new TeamError(409, "conversation_unrecoverable");
599
+ }
600
+
601
+ let bound: Awaited<ReturnType<ConversationService["launch"]>>;
602
+ try {
603
+ bound = await this.launch(caller, persona, t, c, root, fileExists ? file : undefined);
604
+ } catch (err) {
605
+ if (err instanceof TeamError && (err.code === "spawn_timeout" || err.code === "guard_unavailable")) {
606
+ this.logEnsure(caller, personaKey, t, c, err.code === "spawn_timeout" ? "timeout" : "guard_unavailable");
607
+ }
608
+ throw err;
609
+ }
610
+ try {
611
+ // The conversation may have been archived / deleted while the spawn was in flight: never resurrect it.
612
+ const cur = this.d.records.read(l);
613
+ if (!cur || cur.archived) {
614
+ await this.d.host.abortSpawnedRun({ sessionId: bound.sessionId, graceful: true });
615
+ throw new TeamError(cur ? 409 : 404, cur ? "conversation_archived" : "conversation_not_found");
616
+ }
617
+ const stamp = this.iso();
618
+ this.d.records.write(l, {
619
+ ...cur,
620
+ sessionId: bound.sessionId,
621
+ sessionFile: bound.sessionFile ?? (fileExists ? file : undefined),
622
+ runId: bound.runId,
623
+ spawnToken: bound.spawnToken,
624
+ startedAt: stamp,
625
+ lastActivityAt: stamp,
626
+ personaUpdatedAt: persona.updatedAt,
627
+ personaSnapshot: this.snapshot(persona),
628
+ });
629
+ this.logEnsure(caller, personaKey, t, c, fileExists ? "resume" : "create", bound.sessionId);
630
+ return { sessionId: bound.sessionId };
631
+ } finally {
632
+ bound.release();
633
+ }
634
+ }
635
+
636
+ // ── conversation management ───────────────────────────────────────────────
637
+
638
+ listConversations(caller: Caller, personaKey: string, t: string, archived: boolean): ConversationView[] {
639
+ const persona = this.d.personas.get(personaKey, caller.uk);
640
+ return this.d.records
641
+ .list(caller.uk, t, personaKey)
642
+ .filter((r) => r.record.archived === archived)
643
+ .map((r) => this.view(r, persona))
644
+ .sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt));
645
+ }
646
+
647
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: title + archive validation with the merge-after-abort step; each branch is a single guard
648
+ async patchConversation(
649
+ caller: Caller,
650
+ personaKey: string,
651
+ t: string,
652
+ c: string,
653
+ body: { title?: unknown; archived?: unknown },
654
+ ): Promise<ConversationView> {
655
+ const { l, rec } = this.requireRecord(caller, personaKey, t, c);
656
+ if (body.title !== undefined) {
657
+ if (typeof body.title !== "string" || cpLength(body.title.trim()) < 1 || cpLength(body.title) > 80) {
658
+ throw new TeamError(400, "invalid_title");
659
+ }
660
+ rec.title = body.title.trim();
661
+ }
662
+ if (body.archived !== undefined) {
663
+ if (typeof body.archived !== "boolean") throw new TeamError(400, "invalid_archived");
664
+ if (body.archived && !rec.archived) {
665
+ await this.endOwnSession(caller, rec.sessionId);
666
+ // `onEvent` may have persisted activity while we awaited: merge into the fresh record.
667
+ const fresh = this.d.records.read(l);
668
+ if (!fresh) throw new TeamError(404, "conversation_not_found"); // deleted while we awaited: never write it back
669
+ Object.assign(rec, { lastAgentEndAt: fresh.lastAgentEndAt, lastActivityAt: fresh.lastActivityAt });
670
+ }
671
+ if (!body.archived && rec.archived && this.activeCount(caller, t, personaKey) >= this.maxConversations()) {
672
+ throw new TeamError(409, "conversation_limit");
673
+ }
674
+ rec.archived = body.archived;
675
+ }
676
+ this.d.records.write(l, rec);
677
+ return this.view({ c, record: rec }, this.d.personas.get(personaKey, caller.uk));
678
+ }
679
+
680
+ /** End a conversation's session only when it is the caller's: a stale / misbound record never lets one user end another's session. */
681
+ private async endOwnSession(caller: Caller, sessionId: string): Promise<void> {
682
+ const s = this.d.host.getSession(sessionId);
683
+ if (s && !this.ownerMatches(s, caller)) return;
684
+ await this.d.host.abortSpawnedRun({ sessionId, graceful: true });
685
+ }
686
+
687
+ async restartConversation(caller: Caller, personaKey: string, t: string, c: string): Promise<void> {
688
+ const { rec } = this.requireRecord(caller, personaKey, t, c);
689
+ await this.endOwnSession(caller, rec.sessionId);
690
+ }
691
+
692
+ async deleteConversation(caller: Caller, personaKey: string, t: string, c: string): Promise<void> {
693
+ const { l, rec } = this.requireRecord(caller, personaKey, t, c);
694
+ await this.endOwnSession(caller, rec.sessionId);
695
+ this.d.records.delete(l);
696
+ }
697
+
698
+ // ── agents (D8) ───────────────────────────────────────────────────────────
699
+
700
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: many small independent branches (field / state rendering); splitting would scatter one linear flow
701
+ agents(caller: Caller, t: string): AgentView[] {
702
+ const mode = this.d.access.mode();
703
+ const records = this.d.records.list(caller.uk, t);
704
+ const byPersona = new Map<string, LocatedRecord[]>();
705
+ for (const r of records) {
706
+ const arr = byPersona.get(r.personaKey) ?? [];
707
+ arr.push(r);
708
+ byPersona.set(r.personaKey, arr);
709
+ }
710
+ const personas = [...this.d.personas.listShared(), ...this.d.personas.listPrivate(caller.uk)];
711
+ // Computed ONCE per request (each call re-validates every project path on disk).
712
+ const usable = new Set(this.d.projects.usableBy(caller, mode).map((x) => x.id));
713
+ const out: AgentView[] = [];
714
+ const seen = new Set<string>();
715
+
716
+ for (const p of personas) {
717
+ const assigned = this.effectiveProjects(p, usable).has(t) && p.projects.includes(t);
718
+ const recs = byPersona.get(p.key) ?? [];
719
+ const active = recs.filter((r) => !r.record.archived);
720
+ if (!assigned && active.length === 0) continue;
721
+ seen.add(p.key);
722
+ out.push(this.card(p, recs, assigned, mode));
723
+ }
724
+ // Retired: records whose persona no longer exists.
725
+ for (const [key, recs] of byPersona) {
726
+ if (seen.has(key) || personas.some((p) => p.key === key)) continue;
727
+ const newest = [...recs].sort((a, b) => b.record.lastActivityAt.localeCompare(a.record.lastActivityAt))[0];
728
+ if (!newest) continue;
729
+ const snap = newest.record.personaSnapshot;
730
+ const active = recs.filter((r) => !r.record.archived);
731
+ const latest = this.latestOf(active);
732
+ out.push({
733
+ key,
734
+ name: snap.name,
735
+ description: snap.description,
736
+ avatar: snap.avatar,
737
+ role: snap.role,
738
+ model: snap.model,
739
+ scope: key.startsWith("shared:") ? "shared" : "private",
740
+ tools: "chat",
741
+ unconfined: false,
742
+ status: "retired",
743
+ activeCount: active.length,
744
+ latest,
745
+ personaStale: false,
746
+ unassigned: false,
747
+ retired: true,
748
+ });
749
+ }
750
+ return out;
751
+ }
752
+
753
+ private latestOf(active: LocatedRecord[]): AgentView["latest"] {
754
+ const top = [...active].sort((a, b) => b.record.lastActivityAt.localeCompare(a.record.lastActivityAt))[0];
755
+ if (!top) return undefined;
756
+ return {
757
+ id: top.c,
758
+ title: this.titleOf(top.record, top.c),
759
+ status: this.statusOf(top.record, top.c),
760
+ lastActivityAt: top.record.lastActivityAt,
761
+ };
762
+ }
763
+
764
+ private card(p: Persona, recs: LocatedRecord[], assigned: boolean, mode: "single" | "multi"): AgentView {
765
+ const active = recs.filter((r) => !r.record.archived);
766
+ const fullBlocked = p.tools === "full" && mode === "multi";
767
+ let status: AgentStatus;
768
+ if (!assigned || fullBlocked) status = "unavailable";
769
+ else if (active.length === 0) status = "new";
770
+ else {
771
+ const statuses = active.map((r) => this.statusOf(r.record, r.c));
772
+ status = statuses.includes("busy") ? "busy" : statuses.includes("running") ? "running" : "sleeping";
773
+ }
774
+ return {
775
+ key: p.key,
776
+ name: p.name,
777
+ description: p.description,
778
+ avatar: p.avatar,
779
+ role: p.role,
780
+ model: p.model,
781
+ scope: p.scope,
782
+ tools: p.tools,
783
+ unconfined: p.tools === "full",
784
+ status,
785
+ activeCount: active.length,
786
+ latest: this.latestOf(active),
787
+ personaStale: active.some((r) => this.isStale(r.record, r.c, p)),
788
+ unassigned: !assigned,
789
+ retired: false,
790
+ };
791
+ }
792
+
793
+ /** Counts for the folder row: agents assigned to the project + active conversations. */
794
+ folderCounts(caller: Caller, projectId: string): { agents: number; active: number } {
795
+ const cards = this.agents(caller, projectId).filter((a) => !a.retired && a.status !== "unavailable");
796
+ return { agents: cards.length, active: cards.filter((a) => a.status === "running" || a.status === "busy").length };
797
+ }
798
+ }
799
+