@vagarylabs/plugin-sdk 1.1.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 (62) hide show
  1. package/README.md +1224 -0
  2. package/dist/bundlers.d.ts +57 -0
  3. package/dist/bundlers.d.ts.map +1 -0
  4. package/dist/bundlers.js +106 -0
  5. package/dist/bundlers.js.map +1 -0
  6. package/dist/define-plugin.d.ts +266 -0
  7. package/dist/define-plugin.d.ts.map +1 -0
  8. package/dist/define-plugin.js +85 -0
  9. package/dist/define-plugin.js.map +1 -0
  10. package/dist/dev-cli.d.ts +3 -0
  11. package/dist/dev-cli.d.ts.map +1 -0
  12. package/dist/dev-cli.js +49 -0
  13. package/dist/dev-cli.js.map +1 -0
  14. package/dist/dev-server.d.ts +34 -0
  15. package/dist/dev-server.d.ts.map +1 -0
  16. package/dist/dev-server.js +194 -0
  17. package/dist/dev-server.js.map +1 -0
  18. package/dist/host-client-factory.d.ts +312 -0
  19. package/dist/host-client-factory.d.ts.map +1 -0
  20. package/dist/host-client-factory.js +623 -0
  21. package/dist/host-client-factory.js.map +1 -0
  22. package/dist/index.d.ts +84 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +84 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/protocol.d.ts +1556 -0
  27. package/dist/protocol.d.ts.map +1 -0
  28. package/dist/protocol.js +369 -0
  29. package/dist/protocol.js.map +1 -0
  30. package/dist/testing.d.ts +183 -0
  31. package/dist/testing.d.ts.map +1 -0
  32. package/dist/testing.js +2265 -0
  33. package/dist/testing.js.map +1 -0
  34. package/dist/types.d.ts +1621 -0
  35. package/dist/types.d.ts.map +1 -0
  36. package/dist/types.js +12 -0
  37. package/dist/types.js.map +1 -0
  38. package/dist/ui/components.d.ts +517 -0
  39. package/dist/ui/components.d.ts.map +1 -0
  40. package/dist/ui/components.js +135 -0
  41. package/dist/ui/components.js.map +1 -0
  42. package/dist/ui/hooks.d.ts +155 -0
  43. package/dist/ui/hooks.d.ts.map +1 -0
  44. package/dist/ui/hooks.js +195 -0
  45. package/dist/ui/hooks.js.map +1 -0
  46. package/dist/ui/index.d.ts +54 -0
  47. package/dist/ui/index.d.ts.map +1 -0
  48. package/dist/ui/index.js +51 -0
  49. package/dist/ui/index.js.map +1 -0
  50. package/dist/ui/runtime.d.ts +3 -0
  51. package/dist/ui/runtime.d.ts.map +1 -0
  52. package/dist/ui/runtime.js +30 -0
  53. package/dist/ui/runtime.js.map +1 -0
  54. package/dist/ui/types.d.ts +400 -0
  55. package/dist/ui/types.d.ts.map +1 -0
  56. package/dist/ui/types.js +17 -0
  57. package/dist/ui/types.js.map +1 -0
  58. package/dist/worker-rpc-host.d.ts +128 -0
  59. package/dist/worker-rpc-host.d.ts.map +1 -0
  60. package/dist/worker-rpc-host.js +1510 -0
  61. package/dist/worker-rpc-host.js.map +1 -0
  62. package/package.json +128 -0
@@ -0,0 +1,2265 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { pluginOperationIssueOriginKind } from "@vagris/shared";
3
+ import { HOST_SUPPORTED_REQUEST_FIELDS } from "./protocol.js";
4
+ // ---------------------------------------------------------------------------
5
+ // Environment event assertion helpers
6
+ // ---------------------------------------------------------------------------
7
+ /** Filter environment events by type. */
8
+ export function filterEnvironmentEvents(events, type) {
9
+ return events.filter((e) => e.type === type);
10
+ }
11
+ /** Assert that environment events occurred in the expected order. */
12
+ export function assertEnvironmentEventOrder(events, expectedOrder) {
13
+ const actual = events.map((e) => e.type);
14
+ const matched = [];
15
+ let cursor = 0;
16
+ for (const eventType of actual) {
17
+ if (cursor < expectedOrder.length && eventType === expectedOrder[cursor]) {
18
+ matched.push(eventType);
19
+ cursor++;
20
+ }
21
+ }
22
+ if (matched.length !== expectedOrder.length) {
23
+ throw new Error(`Environment event order mismatch.\nExpected: ${JSON.stringify(expectedOrder)}\nActual: ${JSON.stringify(actual)}`);
24
+ }
25
+ }
26
+ /** Assert that a full lease lifecycle (acquire → release) occurred for an environment. */
27
+ export function assertLeaseLifecycle(events, environmentId) {
28
+ const acquire = events.find((e) => e.type === "acquireLease" && e.environmentId === environmentId);
29
+ const release = events.find((e) => (e.type === "releaseLease" || e.type === "destroyLease") && e.environmentId === environmentId);
30
+ if (!acquire)
31
+ throw new Error(`No acquireLease event found for environment ${environmentId}`);
32
+ if (!release)
33
+ throw new Error(`No releaseLease/destroyLease event found for environment ${environmentId}`);
34
+ if (acquire.timestamp > release.timestamp) {
35
+ throw new Error(`acquireLease occurred after release for environment ${environmentId}`);
36
+ }
37
+ return { acquire, release };
38
+ }
39
+ /** Assert that workspace realization occurred between lease acquire and release. */
40
+ export function assertWorkspaceRealizationLifecycle(events, environmentId) {
41
+ const lifecycle = assertLeaseLifecycle(events, environmentId);
42
+ const realize = events.find((e) => e.type === "realizeWorkspace" && e.environmentId === environmentId);
43
+ if (!realize)
44
+ throw new Error(`No realizeWorkspace event found for environment ${environmentId}`);
45
+ if (realize.timestamp < lifecycle.acquire.timestamp) {
46
+ throw new Error(`realizeWorkspace occurred before acquireLease for environment ${environmentId}`);
47
+ }
48
+ if (realize.timestamp > lifecycle.release.timestamp) {
49
+ throw new Error(`realizeWorkspace occurred after release for environment ${environmentId}`);
50
+ }
51
+ return realize;
52
+ }
53
+ /** Assert that an execute call occurred within the lease lifecycle. */
54
+ export function assertExecutionLifecycle(events, environmentId) {
55
+ const lifecycle = assertLeaseLifecycle(events, environmentId);
56
+ const execEvents = events.filter((e) => e.type === "execute" && e.environmentId === environmentId);
57
+ if (execEvents.length === 0) {
58
+ throw new Error(`No execute events found for environment ${environmentId}`);
59
+ }
60
+ for (const exec of execEvents) {
61
+ if (exec.timestamp < lifecycle.acquire.timestamp || exec.timestamp > lifecycle.release.timestamp) {
62
+ throw new Error(`Execute event occurred outside lease lifecycle for environment ${environmentId}`);
63
+ }
64
+ }
65
+ return execEvents;
66
+ }
67
+ /** Assert that an event recorded an error. */
68
+ export function assertEnvironmentError(events, type, environmentId) {
69
+ const match = events.find((e) => e.type === type && e.error != null && (!environmentId || e.environmentId === environmentId));
70
+ if (!match) {
71
+ throw new Error(`No error event of type '${type}'${environmentId ? ` for environment ${environmentId}` : ""}`);
72
+ }
73
+ return match;
74
+ }
75
+ /**
76
+ * Create a fake environment driver suitable for contract testing.
77
+ *
78
+ * This returns a driver hooks object compatible with `EnvironmentTestHarnessOptions.environmentDriver`.
79
+ * It simulates the full environment lifecycle with configurable failure injection.
80
+ */
81
+ export function createFakeEnvironmentDriver(options = {}) {
82
+ const driverKey = options.driverKey ?? "fake";
83
+ const leases = new Map();
84
+ let leaseCounter = 0;
85
+ return {
86
+ driverKey,
87
+ async onValidateConfig(params) {
88
+ if (!params.config || typeof params.config !== "object") {
89
+ return { ok: false, errors: ["Config must be an object"] };
90
+ }
91
+ return { ok: true, normalizedConfig: params.config };
92
+ },
93
+ async onProbe(_params) {
94
+ if (options.probeFailure) {
95
+ return { ok: false, summary: "Simulated probe failure", diagnostics: [{ severity: "error", message: "Probe failed" }] };
96
+ }
97
+ return { ok: true, summary: "Fake environment is healthy" };
98
+ },
99
+ async onAcquireLease(params) {
100
+ if (options.acquireFailure) {
101
+ throw new Error(options.acquireFailure);
102
+ }
103
+ if (options.acquireDelayMs) {
104
+ await new Promise((resolve) => setTimeout(resolve, options.acquireDelayMs));
105
+ }
106
+ const providerLeaseId = `fake-lease-${++leaseCounter}`;
107
+ const metadata = { ...options.leaseMetadata, acquiredAt: new Date().toISOString(), runId: params.runId };
108
+ leases.set(providerLeaseId, { providerLeaseId, metadata });
109
+ return { providerLeaseId, metadata };
110
+ },
111
+ async onResumeLease(params) {
112
+ const existing = leases.get(params.providerLeaseId);
113
+ if (!existing) {
114
+ throw new Error(`Lease ${params.providerLeaseId} not found — cannot resume`);
115
+ }
116
+ return { providerLeaseId: existing.providerLeaseId, metadata: { ...existing.metadata, resumed: true } };
117
+ },
118
+ async onReleaseLease(params) {
119
+ if (params.providerLeaseId) {
120
+ leases.delete(params.providerLeaseId);
121
+ }
122
+ },
123
+ async onDestroyLease(params) {
124
+ if (params.providerLeaseId) {
125
+ leases.delete(params.providerLeaseId);
126
+ }
127
+ },
128
+ async onRealizeWorkspace(params) {
129
+ return {
130
+ cwd: params.workspace.localPath ?? params.workspace.remotePath ?? "/tmp/fake-workspace",
131
+ metadata: { realized: true },
132
+ };
133
+ },
134
+ async onExecute(params) {
135
+ if (options.executeFailure) {
136
+ return { exitCode: 1, timedOut: false, stdout: "", stderr: "Simulated execution failure" };
137
+ }
138
+ return {
139
+ exitCode: 0,
140
+ timedOut: false,
141
+ stdout: `Executed: ${params.command} ${(params.args ?? []).join(" ")}`.trim(),
142
+ stderr: "",
143
+ };
144
+ },
145
+ };
146
+ }
147
+ function normalizeScope(input) {
148
+ return {
149
+ scopeKind: input.scopeKind,
150
+ scopeId: input.scopeId,
151
+ namespace: input.namespace ?? "default",
152
+ stateKey: input.stateKey,
153
+ };
154
+ }
155
+ function stateMapKey(input) {
156
+ const normalized = normalizeScope(input);
157
+ return `${normalized.scopeKind}|${normalized.scopeId ?? ""}|${normalized.namespace}|${normalized.stateKey}`;
158
+ }
159
+ function allowsEvent(filter, event) {
160
+ if (!filter)
161
+ return true;
162
+ if (filter.companyId && filter.companyId !== String(event.payload?.companyId ?? ""))
163
+ return false;
164
+ if (filter.projectId && filter.projectId !== String(event.payload?.projectId ?? ""))
165
+ return false;
166
+ if (filter.agentId && filter.agentId !== String(event.payload?.agentId ?? ""))
167
+ return false;
168
+ return true;
169
+ }
170
+ function requireCapability(manifest, allowed, capability) {
171
+ if (allowed.has(capability))
172
+ return;
173
+ throw new Error(`Plugin '${manifest.id}' is missing required capability '${capability}' in test harness`);
174
+ }
175
+ function requireCompanyId(companyId) {
176
+ if (!companyId)
177
+ throw new Error("companyId is required for this operation");
178
+ return companyId;
179
+ }
180
+ function isInCompany(record, companyId) {
181
+ return Boolean(record && record.companyId === companyId);
182
+ }
183
+ /**
184
+ * Create an in-memory host harness for plugin worker tests.
185
+ *
186
+ * The harness enforces declared capabilities and simulates host APIs, so tests
187
+ * can validate plugin behavior without spinning up the Paperclip server runtime.
188
+ */
189
+ export function createTestHarness(options) {
190
+ const manifest = options.manifest;
191
+ const capabilitySet = new Set(options.capabilities ?? manifest.capabilities);
192
+ let currentConfig = { ...(options.config ?? {}) };
193
+ const logs = [];
194
+ const activity = [];
195
+ const metrics = [];
196
+ const telemetry = [];
197
+ const dbQueries = [];
198
+ const dbExecutes = [];
199
+ const state = new Map();
200
+ const entities = new Map();
201
+ const entityExternalIndex = new Map();
202
+ const companies = new Map();
203
+ const projects = new Map();
204
+ const routines = new Map();
205
+ const routineRuns = new Map();
206
+ const issues = new Map();
207
+ const blockedByIssueIds = new Map();
208
+ const issueComments = new Map();
209
+ const issueInteractions = new Map();
210
+ const issueDocuments = new Map();
211
+ const agents = new Map();
212
+ const goals = new Map();
213
+ const accessMembers = new Map();
214
+ const principalGrants = new Map();
215
+ function principalGrantsKey(companyId, principalType, principalId) {
216
+ return `${companyId}:${principalType}:${principalId}`;
217
+ }
218
+ function getPrincipalGrants(companyId, principalType, principalId) {
219
+ return principalGrants.get(principalGrantsKey(companyId, principalType, principalId)) ?? [];
220
+ }
221
+ function setPrincipalGrants(companyId, principalType, principalId, grants) {
222
+ const stamped = grants.map((grant) => ({
223
+ principalType,
224
+ principalId,
225
+ permissionKey: grant.permissionKey,
226
+ scope: grant.scope && typeof grant.scope === "object" ? grant.scope : null,
227
+ }));
228
+ principalGrants.set(principalGrantsKey(companyId, principalType, principalId), stamped);
229
+ const member = [...accessMembers.values()].find((entry) => entry.companyId === companyId
230
+ && entry.principalType === principalType
231
+ && entry.principalId === principalId);
232
+ if (member) {
233
+ accessMembers.set(member.id, { ...member, grants: stamped, updatedAt: new Date().toISOString() });
234
+ }
235
+ return stamped;
236
+ }
237
+ const projectWorkspaces = new Map();
238
+ const executionWorkspaces = new Map();
239
+ const localFolderStatuses = new Map();
240
+ const localFolderFiles = new Map();
241
+ const sessions = new Map();
242
+ const sessionEventCallbacks = new Map();
243
+ const events = [];
244
+ const jobs = new Map();
245
+ const launchers = new Map();
246
+ const dataHandlers = new Map();
247
+ const actionHandlers = new Map();
248
+ const toolHandlers = new Map();
249
+ function localFolderKey(companyId, folderKey) {
250
+ return `${companyId}:${folderKey}`;
251
+ }
252
+ function localFolderFileKey(companyId, folderKey, relativePath) {
253
+ return `${localFolderKey(companyId, folderKey)}:${relativePath}`;
254
+ }
255
+ function stringOrNull(value) {
256
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
257
+ }
258
+ function actorTypeOrSystem(value) {
259
+ return value === "user" || value === "agent" || value === "system" ? value : "system";
260
+ }
261
+ function actionContextFor(params, options) {
262
+ const actorInput = options?.actor ?? null;
263
+ const companyId = stringOrNull(options?.companyId) ?? stringOrNull(actorInput?.companyId) ?? stringOrNull(params.companyId);
264
+ const actor = Object.freeze({
265
+ type: actorTypeOrSystem(actorInput?.type),
266
+ userId: stringOrNull(actorInput?.userId),
267
+ agentId: stringOrNull(actorInput?.agentId),
268
+ runId: stringOrNull(actorInput?.runId),
269
+ companyId,
270
+ });
271
+ return Object.freeze({ actor, companyId });
272
+ }
273
+ function paramsWithHostCompanyScope(params, context, options) {
274
+ if (Object.prototype.hasOwnProperty.call(options ?? {}, "companyId")) {
275
+ return context.companyId ? { ...params, companyId: context.companyId } : { ...params };
276
+ }
277
+ return params;
278
+ }
279
+ function normalizeLocalFolderRelativePath(relativePath) {
280
+ const parts = [];
281
+ for (const segment of relativePath.split(/[\\/]+/)) {
282
+ if (!segment || segment === ".")
283
+ continue;
284
+ if (segment === "..")
285
+ throw new Error("Local folder path traversal is not allowed");
286
+ parts.push(segment);
287
+ }
288
+ return parts.join("/");
289
+ }
290
+ function notConfiguredLocalFolderStatus(folderKey) {
291
+ return {
292
+ folderKey,
293
+ configured: false,
294
+ path: null,
295
+ realPath: null,
296
+ access: "readWrite",
297
+ readable: false,
298
+ writable: false,
299
+ requiredDirectories: [],
300
+ requiredFiles: [],
301
+ missingDirectories: [],
302
+ missingFiles: [],
303
+ healthy: false,
304
+ problems: [{ code: "not_configured", message: "No local folder path is configured." }],
305
+ checkedAt: new Date().toISOString(),
306
+ };
307
+ }
308
+ function issueRelationSummary(issueId) {
309
+ const issue = issues.get(issueId);
310
+ if (!issue)
311
+ throw new Error(`Issue not found: ${issueId}`);
312
+ const summarize = (candidateId) => {
313
+ const related = issues.get(candidateId);
314
+ if (!related || related.companyId !== issue.companyId)
315
+ return null;
316
+ return {
317
+ id: related.id,
318
+ identifier: related.identifier,
319
+ title: related.title,
320
+ status: related.status,
321
+ priority: related.priority,
322
+ assigneeAgentId: related.assigneeAgentId,
323
+ assigneeUserId: related.assigneeUserId,
324
+ };
325
+ };
326
+ const blockedBy = (blockedByIssueIds.get(issueId) ?? [])
327
+ .map(summarize)
328
+ .filter((value) => value !== null);
329
+ const blocks = [...blockedByIssueIds.entries()]
330
+ .filter(([, blockers]) => blockers.includes(issueId))
331
+ .map(([blockedIssueId]) => summarize(blockedIssueId))
332
+ .filter((value) => value !== null);
333
+ return { blockedBy, blocks };
334
+ }
335
+ const defaultPluginOriginKind = `plugin:${manifest.id}`;
336
+ function managedAgentDeclaration(agentKey) {
337
+ const declaration = manifest.agents?.find((agent) => agent.agentKey === agentKey);
338
+ if (!declaration)
339
+ throw new Error(`Managed agent declaration not found: ${agentKey}`);
340
+ return declaration;
341
+ }
342
+ function isManagedAgent(agent, agentKey) {
343
+ const marker = agent.metadata?.paperclipManagedResource;
344
+ return Boolean(marker
345
+ && typeof marker === "object"
346
+ && !Array.isArray(marker)
347
+ && marker.pluginKey === manifest.id
348
+ && marker.resourceKind === "agent"
349
+ && marker.resourceKey === agentKey);
350
+ }
351
+ function managedAgentMetadata(agentKey, existing) {
352
+ return {
353
+ ...(existing ?? {}),
354
+ paperclipManagedResource: {
355
+ pluginKey: manifest.id,
356
+ resourceKind: "agent",
357
+ resourceKey: agentKey,
358
+ },
359
+ };
360
+ }
361
+ function managedResolution(agentKey, companyId, agent, status) {
362
+ return {
363
+ pluginKey: manifest.id,
364
+ resourceKind: "agent",
365
+ resourceKey: agentKey,
366
+ companyId,
367
+ agentId: agent?.id ?? null,
368
+ agent,
369
+ status,
370
+ approvalId: null,
371
+ };
372
+ }
373
+ function normalizePluginOriginKind(originKind = defaultPluginOriginKind) {
374
+ if (originKind == null || originKind === "")
375
+ return defaultPluginOriginKind;
376
+ if (typeof originKind !== "string")
377
+ throw new Error("Plugin issue originKind must be a string");
378
+ if (originKind === defaultPluginOriginKind || originKind.startsWith(`${defaultPluginOriginKind}:`)) {
379
+ return originKind;
380
+ }
381
+ throw new Error(`Plugin may only use originKind values under ${defaultPluginOriginKind}`);
382
+ }
383
+ const ctx = {
384
+ manifest,
385
+ // The test harness stands in for a host of THIS build, so it advertises what this build supports.
386
+ // Not `null`: null means "no advertisement arrived", and a harness that reported unknown would let
387
+ // a plugin's skew handling go untested against the very host it is written for.
388
+ host: {
389
+ supportedRequestFields() {
390
+ return HOST_SUPPORTED_REQUEST_FIELDS;
391
+ },
392
+ supportsRequestField(method, field) {
393
+ const supported = HOST_SUPPORTED_REQUEST_FIELDS[method];
394
+ if (!supported)
395
+ return null;
396
+ return supported.includes(field);
397
+ },
398
+ unsupportedRequestFields(method, fields) {
399
+ const supported = HOST_SUPPORTED_REQUEST_FIELDS[method];
400
+ if (!supported)
401
+ return [];
402
+ return fields.filter((f) => !supported.includes(f));
403
+ },
404
+ },
405
+ config: {
406
+ async get() {
407
+ return { ...currentConfig };
408
+ },
409
+ },
410
+ localFolders: {
411
+ declarations() {
412
+ return manifest.localFolders ?? [];
413
+ },
414
+ async configure(input) {
415
+ requireCapability(manifest, capabilitySet, "local.folders");
416
+ const status = {
417
+ folderKey: input.folderKey,
418
+ configured: true,
419
+ path: input.path,
420
+ realPath: input.path,
421
+ access: input.access ?? "readWrite",
422
+ readable: true,
423
+ writable: input.access === "read" ? false : true,
424
+ requiredDirectories: input.requiredDirectories ?? [],
425
+ requiredFiles: input.requiredFiles ?? [],
426
+ missingDirectories: [],
427
+ missingFiles: [],
428
+ healthy: true,
429
+ problems: [],
430
+ checkedAt: new Date().toISOString(),
431
+ };
432
+ localFolderStatuses.set(localFolderKey(input.companyId, input.folderKey), status);
433
+ return status;
434
+ },
435
+ async status(companyId, folderKey) {
436
+ requireCapability(manifest, capabilitySet, "local.folders");
437
+ return localFolderStatuses.get(localFolderKey(companyId, folderKey)) ?? notConfiguredLocalFolderStatus(folderKey);
438
+ },
439
+ async list(companyId, folderKey, options) {
440
+ requireCapability(manifest, capabilitySet, "local.folders");
441
+ const status = localFolderStatuses.get(localFolderKey(companyId, folderKey));
442
+ if (!status?.configured)
443
+ throw new Error("Local folder is not configured");
444
+ const prefix = normalizeLocalFolderRelativePath(options?.relativePath ?? "");
445
+ const prefixWithSlash = prefix ? `${prefix}/` : "";
446
+ const entries = new Map();
447
+ for (const [key, contents] of localFolderFiles) {
448
+ const filePrefix = `${localFolderKey(companyId, folderKey)}:`;
449
+ if (!key.startsWith(filePrefix))
450
+ continue;
451
+ const filePath = key.slice(filePrefix.length);
452
+ if (prefix && filePath !== prefix && !filePath.startsWith(prefixWithSlash))
453
+ continue;
454
+ const remainder = prefix ? filePath.slice(prefixWithSlash.length) : filePath;
455
+ const [name] = remainder.split("/");
456
+ if (!name)
457
+ continue;
458
+ const entryPath = prefix ? `${prefix}/${name}` : name;
459
+ const isNested = remainder.includes("/");
460
+ if (!options?.recursive && isNested) {
461
+ entries.set(entryPath, {
462
+ path: entryPath,
463
+ name,
464
+ kind: "directory",
465
+ size: null,
466
+ modifiedAt: null,
467
+ });
468
+ continue;
469
+ }
470
+ entries.set(filePath, {
471
+ path: filePath,
472
+ name: filePath.split("/").pop() ?? filePath,
473
+ kind: "file",
474
+ size: Buffer.byteLength(contents, "utf8"),
475
+ modifiedAt: null,
476
+ });
477
+ }
478
+ const maxEntries = options?.maxEntries && options.maxEntries > 0 ? options.maxEntries : entries.size;
479
+ const allEntries = [...entries.values()].sort((a, b) => a.path.localeCompare(b.path));
480
+ return {
481
+ folderKey,
482
+ relativePath: options?.relativePath ?? null,
483
+ entries: allEntries.slice(0, maxEntries),
484
+ truncated: allEntries.length > maxEntries,
485
+ };
486
+ },
487
+ async readText(companyId, folderKey, relativePath) {
488
+ requireCapability(manifest, capabilitySet, "local.folders");
489
+ const normalizedPath = normalizeLocalFolderRelativePath(relativePath);
490
+ const contents = localFolderFiles.get(localFolderFileKey(companyId, folderKey, normalizedPath));
491
+ if (contents === undefined)
492
+ throw new Error(`Local folder file not found: ${relativePath}`);
493
+ return contents;
494
+ },
495
+ async writeTextAtomic(companyId, folderKey, relativePath, contents) {
496
+ requireCapability(manifest, capabilitySet, "local.folders");
497
+ const status = localFolderStatuses.get(localFolderKey(companyId, folderKey)) ?? {
498
+ folderKey,
499
+ configured: true,
500
+ path: `memory://${manifest.id}/${companyId}/${folderKey}`,
501
+ realPath: `memory://${manifest.id}/${companyId}/${folderKey}`,
502
+ access: "readWrite",
503
+ readable: true,
504
+ writable: true,
505
+ requiredDirectories: [],
506
+ requiredFiles: [],
507
+ missingDirectories: [],
508
+ missingFiles: [],
509
+ healthy: true,
510
+ problems: [],
511
+ checkedAt: new Date().toISOString(),
512
+ };
513
+ if (status.access !== "readWrite" || !status.writable) {
514
+ throw new Error("Local folder is not configured for writes");
515
+ }
516
+ localFolderStatuses.set(localFolderKey(companyId, folderKey), status);
517
+ localFolderFiles.set(localFolderFileKey(companyId, folderKey, normalizeLocalFolderRelativePath(relativePath)), contents);
518
+ return status;
519
+ },
520
+ async deleteFile(companyId, folderKey, relativePath) {
521
+ requireCapability(manifest, capabilitySet, "local.folders");
522
+ const status = localFolderStatuses.get(localFolderKey(companyId, folderKey)) ?? notConfiguredLocalFolderStatus(folderKey);
523
+ if (status.configured && (status.access !== "readWrite" || !status.writable)) {
524
+ throw new Error("Local folder is not configured for writes");
525
+ }
526
+ localFolderFiles.delete(localFolderFileKey(companyId, folderKey, normalizeLocalFolderRelativePath(relativePath)));
527
+ return status;
528
+ },
529
+ },
530
+ events: {
531
+ on(name, filterOrFn, maybeFn) {
532
+ requireCapability(manifest, capabilitySet, "events.subscribe");
533
+ let registration;
534
+ if (typeof filterOrFn === "function") {
535
+ registration = { name, fn: filterOrFn };
536
+ }
537
+ else {
538
+ if (!maybeFn)
539
+ throw new Error("event handler is required");
540
+ registration = { name, filter: filterOrFn, fn: maybeFn };
541
+ }
542
+ events.push(registration);
543
+ return () => {
544
+ const idx = events.indexOf(registration);
545
+ if (idx !== -1)
546
+ events.splice(idx, 1);
547
+ };
548
+ },
549
+ async emit(name, companyId, payload) {
550
+ requireCapability(manifest, capabilitySet, "events.emit");
551
+ await harness.emit(`plugin.${manifest.id}.${name}`, payload, { companyId });
552
+ },
553
+ },
554
+ jobs: {
555
+ register(key, fn) {
556
+ requireCapability(manifest, capabilitySet, "jobs.schedule");
557
+ jobs.set(key, fn);
558
+ },
559
+ },
560
+ launchers: {
561
+ register(launcher) {
562
+ launchers.set(launcher.id, launcher);
563
+ },
564
+ },
565
+ db: {
566
+ namespace: manifest.database ? `test_${manifest.id.replace(/[^a-z0-9_]+/g, "_")}` : "",
567
+ async query(sql, params) {
568
+ requireCapability(manifest, capabilitySet, "database.namespace.read");
569
+ dbQueries.push({ sql, params });
570
+ return [];
571
+ },
572
+ async execute(sql, params) {
573
+ requireCapability(manifest, capabilitySet, "database.namespace.write");
574
+ dbExecutes.push({ sql, params });
575
+ return { rowCount: 0 };
576
+ },
577
+ },
578
+ http: {
579
+ async fetch(url, init) {
580
+ requireCapability(manifest, capabilitySet, "http.outbound");
581
+ return fetch(url, init);
582
+ },
583
+ },
584
+ secrets: {
585
+ async resolve(secretRef) {
586
+ requireCapability(manifest, capabilitySet, "secrets.read-ref");
587
+ return `resolved:${secretRef}`;
588
+ },
589
+ },
590
+ activity: {
591
+ async log(entry) {
592
+ requireCapability(manifest, capabilitySet, "activity.log.write");
593
+ activity.push(entry);
594
+ },
595
+ },
596
+ state: {
597
+ async get(input) {
598
+ requireCapability(manifest, capabilitySet, "plugin.state.read");
599
+ return state.has(stateMapKey(input)) ? state.get(stateMapKey(input)) : null;
600
+ },
601
+ async set(input, value) {
602
+ requireCapability(manifest, capabilitySet, "plugin.state.write");
603
+ state.set(stateMapKey(input), value);
604
+ },
605
+ async delete(input) {
606
+ requireCapability(manifest, capabilitySet, "plugin.state.write");
607
+ state.delete(stateMapKey(input));
608
+ },
609
+ },
610
+ entities: {
611
+ async upsert(input) {
612
+ const externalKey = input.externalId
613
+ ? `${input.entityType}|${input.scopeKind}|${input.scopeId ?? ""}|${input.externalId}`
614
+ : null;
615
+ const existingId = externalKey ? entityExternalIndex.get(externalKey) : undefined;
616
+ const existing = existingId ? entities.get(existingId) : undefined;
617
+ const now = new Date().toISOString();
618
+ const previousExternalKey = existing?.externalId
619
+ ? `${existing.entityType}|${existing.scopeKind}|${existing.scopeId ?? ""}|${existing.externalId}`
620
+ : null;
621
+ const record = existing
622
+ ? {
623
+ ...existing,
624
+ entityType: input.entityType,
625
+ scopeKind: input.scopeKind,
626
+ scopeId: input.scopeId ?? null,
627
+ externalId: input.externalId ?? null,
628
+ title: input.title ?? null,
629
+ status: input.status ?? null,
630
+ data: input.data,
631
+ updatedAt: now,
632
+ }
633
+ : {
634
+ id: randomUUID(),
635
+ entityType: input.entityType,
636
+ scopeKind: input.scopeKind,
637
+ scopeId: input.scopeId ?? null,
638
+ externalId: input.externalId ?? null,
639
+ title: input.title ?? null,
640
+ status: input.status ?? null,
641
+ data: input.data,
642
+ createdAt: now,
643
+ updatedAt: now,
644
+ };
645
+ entities.set(record.id, record);
646
+ if (previousExternalKey && previousExternalKey !== externalKey) {
647
+ entityExternalIndex.delete(previousExternalKey);
648
+ }
649
+ if (externalKey)
650
+ entityExternalIndex.set(externalKey, record.id);
651
+ return record;
652
+ },
653
+ async list(query) {
654
+ let out = [...entities.values()];
655
+ if (query.entityType)
656
+ out = out.filter((r) => r.entityType === query.entityType);
657
+ if (query.scopeKind)
658
+ out = out.filter((r) => r.scopeKind === query.scopeKind);
659
+ if (query.scopeId)
660
+ out = out.filter((r) => r.scopeId === query.scopeId);
661
+ if (query.externalId)
662
+ out = out.filter((r) => r.externalId === query.externalId);
663
+ if (query.offset)
664
+ out = out.slice(query.offset);
665
+ if (query.limit)
666
+ out = out.slice(0, query.limit);
667
+ return out;
668
+ },
669
+ },
670
+ projects: {
671
+ async list(input) {
672
+ requireCapability(manifest, capabilitySet, "projects.read");
673
+ const companyId = requireCompanyId(input?.companyId);
674
+ let out = [...projects.values()];
675
+ out = out.filter((project) => project.companyId === companyId);
676
+ if (input?.offset)
677
+ out = out.slice(input.offset);
678
+ if (input?.limit)
679
+ out = out.slice(0, input.limit);
680
+ return out;
681
+ },
682
+ async get(projectId, companyId) {
683
+ requireCapability(manifest, capabilitySet, "projects.read");
684
+ const project = projects.get(projectId);
685
+ return isInCompany(project, companyId) ? project : null;
686
+ },
687
+ async listWorkspaces(projectId, companyId) {
688
+ requireCapability(manifest, capabilitySet, "project.workspaces.read");
689
+ if (!isInCompany(projects.get(projectId), companyId))
690
+ return [];
691
+ return projectWorkspaces.get(projectId) ?? [];
692
+ },
693
+ async getPrimaryWorkspace(projectId, companyId) {
694
+ requireCapability(manifest, capabilitySet, "project.workspaces.read");
695
+ if (!isInCompany(projects.get(projectId), companyId))
696
+ return null;
697
+ const workspaces = projectWorkspaces.get(projectId) ?? [];
698
+ return workspaces.find((workspace) => workspace.isPrimary) ?? null;
699
+ },
700
+ async getWorkspaceForIssue(issueId, companyId) {
701
+ requireCapability(manifest, capabilitySet, "project.workspaces.read");
702
+ const issue = issues.get(issueId);
703
+ if (!isInCompany(issue, companyId))
704
+ return null;
705
+ const projectId = issue?.projectId;
706
+ if (!projectId)
707
+ return null;
708
+ if (!isInCompany(projects.get(projectId), companyId))
709
+ return null;
710
+ const workspaces = projectWorkspaces.get(projectId) ?? [];
711
+ return workspaces.find((workspace) => workspace.isPrimary) ?? null;
712
+ },
713
+ managed: {
714
+ async get(projectKey, companyId) {
715
+ requireCapability(manifest, capabilitySet, "projects.managed");
716
+ const declaration = manifest.projects?.find((project) => project.projectKey === projectKey);
717
+ if (!declaration) {
718
+ return {
719
+ pluginKey: manifest.id,
720
+ resourceKind: "project",
721
+ resourceKey: projectKey,
722
+ companyId,
723
+ projectId: null,
724
+ project: null,
725
+ status: "missing",
726
+ };
727
+ }
728
+ const externalId = `${manifest.id}:project:${projectKey}`;
729
+ const existingEntity = [...entities.values()].find((entity) => entity.entityType === "managed_resource"
730
+ && entity.scopeKind === "company"
731
+ && entity.scopeId === companyId
732
+ && entity.externalId === externalId);
733
+ const existingProject = existingEntity ? projects.get(String(existingEntity.data?.projectId ?? "")) : null;
734
+ if (existingProject && isInCompany(existingProject, companyId)) {
735
+ return {
736
+ pluginKey: manifest.id,
737
+ resourceKind: "project",
738
+ resourceKey: projectKey,
739
+ companyId,
740
+ projectId: existingProject.id,
741
+ project: existingProject,
742
+ status: "resolved",
743
+ };
744
+ }
745
+ const now = new Date();
746
+ const project = {
747
+ id: `project-${projects.size + 1}`,
748
+ companyId,
749
+ urlKey: declaration.projectKey,
750
+ goalId: null,
751
+ goalIds: [],
752
+ goals: [],
753
+ name: declaration.displayName,
754
+ description: declaration.description ?? null,
755
+ status: declaration.status ?? "in_progress",
756
+ leadAgentId: null,
757
+ targetDate: null,
758
+ color: declaration.color ?? null,
759
+ env: null,
760
+ pauseReason: null,
761
+ pausedAt: null,
762
+ executionWorkspacePolicy: null,
763
+ codebase: {
764
+ workspaceId: null,
765
+ repoUrl: null,
766
+ repoRef: null,
767
+ defaultRef: null,
768
+ repoName: null,
769
+ localFolder: null,
770
+ managedFolder: `/tmp/${declaration.projectKey}`,
771
+ effectiveLocalFolder: `/tmp/${declaration.projectKey}`,
772
+ origin: "managed_checkout",
773
+ },
774
+ workspaces: [],
775
+ primaryWorkspace: null,
776
+ managedByPlugin: {
777
+ id: `managed-${projects.size + 1}`,
778
+ pluginId: manifest.id,
779
+ pluginKey: manifest.id,
780
+ pluginDisplayName: manifest.displayName,
781
+ resourceKind: "project",
782
+ resourceKey: projectKey,
783
+ defaultsJson: { displayName: declaration.displayName, settings: declaration.settings ?? {} },
784
+ createdAt: now,
785
+ updatedAt: now,
786
+ },
787
+ archivedAt: null,
788
+ createdAt: now,
789
+ updatedAt: now,
790
+ };
791
+ projects.set(project.id, project);
792
+ const externalKey = `managed_resource|company|${companyId}|${externalId}`;
793
+ const nowIso = now.toISOString();
794
+ const record = {
795
+ id: randomUUID(),
796
+ entityType: "managed_resource",
797
+ scopeKind: "company",
798
+ scopeId: companyId,
799
+ externalId,
800
+ title: declaration.displayName,
801
+ status: null,
802
+ data: { resourceKind: "project", resourceKey: projectKey, projectId: project.id },
803
+ createdAt: nowIso,
804
+ updatedAt: nowIso,
805
+ };
806
+ entities.set(record.id, record);
807
+ entityExternalIndex.set(externalKey, record.id);
808
+ return {
809
+ pluginKey: manifest.id,
810
+ resourceKind: "project",
811
+ resourceKey: projectKey,
812
+ companyId,
813
+ projectId: project.id,
814
+ project,
815
+ status: "created",
816
+ };
817
+ },
818
+ async reconcile(projectKey, companyId) {
819
+ return this.get(projectKey, companyId);
820
+ },
821
+ async reset(projectKey, companyId) {
822
+ const resolved = await this.get(projectKey, companyId);
823
+ return { ...resolved, status: resolved.project ? "reset" : resolved.status };
824
+ },
825
+ },
826
+ },
827
+ executionWorkspaces: {
828
+ async get(workspaceId, companyId) {
829
+ requireCapability(manifest, capabilitySet, "execution.workspaces.read");
830
+ const workspace = executionWorkspaces.get(workspaceId);
831
+ return workspace?.companyId === companyId ? workspace : null;
832
+ },
833
+ },
834
+ routines: {
835
+ managed: {
836
+ async get(routineKey, companyId) {
837
+ requireCapability(manifest, capabilitySet, "routines.managed");
838
+ const declaration = manifest.routines?.find((routine) => routine.routineKey === routineKey);
839
+ if (!declaration) {
840
+ return {
841
+ pluginKey: manifest.id,
842
+ resourceKind: "routine",
843
+ resourceKey: routineKey,
844
+ companyId,
845
+ routineId: null,
846
+ routine: null,
847
+ status: "missing",
848
+ missingRefs: [],
849
+ };
850
+ }
851
+ const externalId = `${manifest.id}:routine:${routineKey}`;
852
+ const existingEntity = [...entities.values()].find((entity) => entity.entityType === "managed_resource"
853
+ && entity.scopeKind === "company"
854
+ && entity.scopeId === companyId
855
+ && entity.externalId === externalId);
856
+ const existingRoutine = existingEntity ? routines.get(String(existingEntity.data?.routineId ?? "")) : null;
857
+ if (existingRoutine && isInCompany(existingRoutine, companyId)) {
858
+ return {
859
+ pluginKey: manifest.id,
860
+ resourceKind: "routine",
861
+ resourceKey: routineKey,
862
+ companyId,
863
+ routineId: existingRoutine.id,
864
+ routine: existingRoutine,
865
+ status: "resolved",
866
+ missingRefs: [],
867
+ };
868
+ }
869
+ return {
870
+ pluginKey: manifest.id,
871
+ resourceKind: "routine",
872
+ resourceKey: routineKey,
873
+ companyId,
874
+ routineId: null,
875
+ routine: null,
876
+ status: "missing",
877
+ missingRefs: [],
878
+ };
879
+ },
880
+ async reconcile(routineKey, companyId, overrides) {
881
+ const existing = await this.get(routineKey, companyId);
882
+ if (existing.routine)
883
+ return existing;
884
+ const declaration = manifest.routines?.find((routine) => routine.routineKey === routineKey);
885
+ if (!declaration)
886
+ return existing;
887
+ const now = new Date();
888
+ const agentRef = declaration.assigneeRef;
889
+ const projectRef = declaration.projectRef;
890
+ const assigneeAgentId = overrides?.assigneeAgentId
891
+ ?? (agentRef?.resourceKind === "agent"
892
+ ? [...agents.values()].find((agent) => isInCompany(agent, companyId) && isManagedAgent(agent, agentRef.resourceKey))?.id
893
+ : null)
894
+ ?? null;
895
+ const projectId = overrides?.projectId
896
+ ?? (projectRef?.resourceKind === "project"
897
+ ? [...projects.values()].find((project) => (isInCompany(project, companyId)
898
+ && project.managedByPlugin?.pluginKey === manifest.id
899
+ && project.managedByPlugin?.resourceKey === projectRef.resourceKey))?.id
900
+ : null)
901
+ ?? null;
902
+ const missingRefs = [];
903
+ if (agentRef && !assigneeAgentId)
904
+ missingRefs.push({ ...agentRef, pluginKey: manifest.id });
905
+ if (projectRef && !projectId)
906
+ missingRefs.push({ ...projectRef, pluginKey: manifest.id });
907
+ if (missingRefs.length > 0) {
908
+ return {
909
+ pluginKey: manifest.id,
910
+ resourceKind: "routine",
911
+ resourceKey: routineKey,
912
+ companyId,
913
+ routineId: null,
914
+ routine: null,
915
+ status: "missing_refs",
916
+ missingRefs,
917
+ };
918
+ }
919
+ const routine = {
920
+ id: `routine-${routines.size + 1}`,
921
+ companyId,
922
+ projectId,
923
+ goalId: declaration.goalId ?? null,
924
+ parentIssueId: null,
925
+ title: declaration.title,
926
+ description: declaration.description ?? null,
927
+ assigneeAgentId,
928
+ priority: declaration.priority ?? "medium",
929
+ status: declaration.status ?? (assigneeAgentId ? "active" : "paused"),
930
+ concurrencyPolicy: declaration.concurrencyPolicy ?? "coalesce_if_active",
931
+ catchUpPolicy: declaration.catchUpPolicy ?? "skip_missed",
932
+ variables: declaration.variables ?? [],
933
+ latestRevisionId: null,
934
+ latestRevisionNumber: 1,
935
+ createdByAgentId: null,
936
+ createdByUserId: null,
937
+ updatedByAgentId: null,
938
+ updatedByUserId: null,
939
+ lastTriggeredAt: null,
940
+ lastEnqueuedAt: null,
941
+ createdAt: now,
942
+ updatedAt: now,
943
+ managedByPlugin: {
944
+ id: `managed-routine-${routines.size + 1}`,
945
+ pluginId: manifest.id,
946
+ pluginKey: manifest.id,
947
+ pluginDisplayName: manifest.displayName,
948
+ resourceKind: "routine",
949
+ resourceKey: routineKey,
950
+ defaultsJson: { title: declaration.title, issueTemplate: declaration.issueTemplate ?? null },
951
+ createdAt: now,
952
+ updatedAt: now,
953
+ },
954
+ };
955
+ routines.set(routine.id, routine);
956
+ const nowIso = now.toISOString();
957
+ const record = {
958
+ id: randomUUID(),
959
+ entityType: "managed_resource",
960
+ scopeKind: "company",
961
+ scopeId: companyId,
962
+ externalId: `${manifest.id}:routine:${routineKey}`,
963
+ title: declaration.title,
964
+ status: null,
965
+ data: { resourceKind: "routine", resourceKey: routineKey, routineId: routine.id },
966
+ createdAt: nowIso,
967
+ updatedAt: nowIso,
968
+ };
969
+ entities.set(record.id, record);
970
+ return {
971
+ pluginKey: manifest.id,
972
+ resourceKind: "routine",
973
+ resourceKey: routineKey,
974
+ companyId,
975
+ routineId: routine.id,
976
+ routine,
977
+ status: "created",
978
+ missingRefs: [],
979
+ };
980
+ },
981
+ async reset(routineKey, companyId, overrides) {
982
+ const resolved = await this.reconcile(routineKey, companyId, overrides);
983
+ return { ...resolved, status: resolved.routine ? "reset" : resolved.status };
984
+ },
985
+ async update(routineKey, companyId, patch) {
986
+ const resolved = await this.get(routineKey, companyId);
987
+ if (!resolved.routine)
988
+ throw new Error(`Managed routine not found: ${routineKey}`);
989
+ const next = {
990
+ ...resolved.routine,
991
+ ...(patch.status !== undefined ? { status: patch.status } : {}),
992
+ updatedAt: new Date(),
993
+ };
994
+ routines.set(next.id, next);
995
+ return next;
996
+ },
997
+ async run(routineKey, companyId) {
998
+ const resolved = await this.get(routineKey, companyId);
999
+ if (!resolved.routine)
1000
+ throw new Error(`Managed routine not found: ${routineKey}`);
1001
+ const now = new Date();
1002
+ const run = {
1003
+ id: `routine-run-${routineRuns.size + 1}`,
1004
+ companyId,
1005
+ routineId: resolved.routine.id,
1006
+ triggerId: null,
1007
+ source: "manual",
1008
+ status: "queued",
1009
+ triggeredAt: now,
1010
+ idempotencyKey: null,
1011
+ triggerPayload: null,
1012
+ dispatchFingerprint: null,
1013
+ linkedIssueId: null,
1014
+ coalescedIntoRunId: null,
1015
+ failureReason: null,
1016
+ completedAt: null,
1017
+ createdAt: now,
1018
+ updatedAt: now,
1019
+ };
1020
+ routineRuns.set(run.id, run);
1021
+ routines.set(resolved.routine.id, {
1022
+ ...resolved.routine,
1023
+ lastTriggeredAt: now,
1024
+ lastEnqueuedAt: now,
1025
+ updatedAt: now,
1026
+ });
1027
+ return run;
1028
+ },
1029
+ },
1030
+ },
1031
+ skills: {
1032
+ managed: {
1033
+ async get(skillKey, companyId) {
1034
+ requireCapability(manifest, capabilitySet, "skills.managed");
1035
+ const declaration = manifest.skills?.find((skill) => skill.skillKey === skillKey);
1036
+ if (!declaration) {
1037
+ return {
1038
+ pluginKey: manifest.id,
1039
+ resourceKind: "skill",
1040
+ resourceKey: skillKey,
1041
+ companyId,
1042
+ skillId: null,
1043
+ skill: null,
1044
+ status: "missing",
1045
+ defaultDrift: null,
1046
+ };
1047
+ }
1048
+ const externalId = `${manifest.id}:skill:${skillKey}`;
1049
+ const existingEntity = [...entities.values()].find((entity) => entity.entityType === "managed_resource"
1050
+ && entity.scopeKind === "company"
1051
+ && entity.scopeId === companyId
1052
+ && entity.externalId === externalId);
1053
+ const existingSkill = existingEntity?.data?.skill;
1054
+ if (existingSkill && existingSkill.companyId === companyId) {
1055
+ return {
1056
+ pluginKey: manifest.id,
1057
+ resourceKind: "skill",
1058
+ resourceKey: skillKey,
1059
+ companyId,
1060
+ skillId: existingSkill.id,
1061
+ skill: existingSkill,
1062
+ status: "resolved",
1063
+ defaultDrift: null,
1064
+ };
1065
+ }
1066
+ return {
1067
+ pluginKey: manifest.id,
1068
+ resourceKind: "skill",
1069
+ resourceKey: skillKey,
1070
+ companyId,
1071
+ skillId: null,
1072
+ skill: null,
1073
+ status: "missing",
1074
+ defaultDrift: null,
1075
+ };
1076
+ },
1077
+ async reconcile(skillKey, companyId) {
1078
+ const existing = await this.get(skillKey, companyId);
1079
+ if (existing.skill)
1080
+ return existing;
1081
+ const declaration = manifest.skills?.find((skill) => skill.skillKey === skillKey);
1082
+ if (!declaration)
1083
+ return existing;
1084
+ const now = new Date();
1085
+ const skill = {
1086
+ id: randomUUID(),
1087
+ companyId,
1088
+ key: `plugin/${manifest.id.replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}/${skillKey}`,
1089
+ slug: declaration.slug ?? skillKey,
1090
+ name: declaration.displayName,
1091
+ description: declaration.description ?? null,
1092
+ markdown: declaration.markdown ?? `# ${declaration.displayName}\n`,
1093
+ sourceType: "catalog",
1094
+ sourceLocator: null,
1095
+ sourceRef: null,
1096
+ trustLevel: "markdown_only",
1097
+ compatibility: "compatible",
1098
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
1099
+ metadata: {
1100
+ sourceKind: "catalog",
1101
+ pluginManagedResource: {
1102
+ pluginKey: manifest.id,
1103
+ resourceKind: "skill",
1104
+ resourceKey: skillKey,
1105
+ },
1106
+ },
1107
+ createdAt: now,
1108
+ updatedAt: now,
1109
+ };
1110
+ const nowIso = now.toISOString();
1111
+ const record = {
1112
+ id: randomUUID(),
1113
+ entityType: "managed_resource",
1114
+ scopeKind: "company",
1115
+ scopeId: companyId,
1116
+ externalId: `${manifest.id}:skill:${skillKey}`,
1117
+ title: declaration.displayName,
1118
+ status: null,
1119
+ data: { resourceKind: "skill", resourceKey: skillKey, skillId: skill.id, skill },
1120
+ createdAt: nowIso,
1121
+ updatedAt: nowIso,
1122
+ };
1123
+ entities.set(record.id, record);
1124
+ return {
1125
+ pluginKey: manifest.id,
1126
+ resourceKind: "skill",
1127
+ resourceKey: skillKey,
1128
+ companyId,
1129
+ skillId: skill.id,
1130
+ skill,
1131
+ status: "created",
1132
+ defaultDrift: null,
1133
+ };
1134
+ },
1135
+ async reset(skillKey, companyId) {
1136
+ requireCapability(manifest, capabilitySet, "skills.managed");
1137
+ const existing = await this.get(skillKey, companyId);
1138
+ const declaration = manifest.skills?.find((skill) => skill.skillKey === skillKey);
1139
+ if (!declaration)
1140
+ return existing;
1141
+ const now = new Date();
1142
+ const skill = {
1143
+ id: existing.skill?.id ?? randomUUID(),
1144
+ companyId,
1145
+ key: `plugin/${manifest.id.replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}/${skillKey}`,
1146
+ slug: declaration.slug ?? skillKey,
1147
+ name: declaration.displayName,
1148
+ description: declaration.description ?? null,
1149
+ markdown: declaration.markdown ?? `# ${declaration.displayName}\n`,
1150
+ sourceType: "catalog",
1151
+ sourceLocator: null,
1152
+ sourceRef: null,
1153
+ trustLevel: "markdown_only",
1154
+ compatibility: "compatible",
1155
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
1156
+ metadata: {
1157
+ sourceKind: "catalog",
1158
+ pluginManagedResource: {
1159
+ pluginKey: manifest.id,
1160
+ resourceKind: "skill",
1161
+ resourceKey: skillKey,
1162
+ },
1163
+ },
1164
+ createdAt: existing.skill?.createdAt ?? now,
1165
+ updatedAt: now,
1166
+ };
1167
+ const nowIso = now.toISOString();
1168
+ const existingEntity = [...entities.values()].find((entity) => entity.entityType === "managed_resource" &&
1169
+ entity.scopeKind === "company" &&
1170
+ entity.scopeId === companyId &&
1171
+ entity.externalId === `${manifest.id}:skill:${skillKey}`);
1172
+ const record = {
1173
+ id: existingEntity?.id ?? randomUUID(),
1174
+ entityType: "managed_resource",
1175
+ scopeKind: "company",
1176
+ scopeId: companyId,
1177
+ externalId: `${manifest.id}:skill:${skillKey}`,
1178
+ title: declaration.displayName,
1179
+ status: null,
1180
+ data: { resourceKind: "skill", resourceKey: skillKey, skillId: skill.id, skill },
1181
+ createdAt: existingEntity?.createdAt ?? nowIso,
1182
+ updatedAt: nowIso,
1183
+ };
1184
+ entities.set(record.id, record);
1185
+ return {
1186
+ pluginKey: manifest.id,
1187
+ resourceKind: "skill",
1188
+ resourceKey: skillKey,
1189
+ companyId,
1190
+ skillId: skill.id,
1191
+ skill,
1192
+ status: "reset",
1193
+ defaultDrift: null,
1194
+ };
1195
+ },
1196
+ },
1197
+ },
1198
+ companies: {
1199
+ async list(input) {
1200
+ requireCapability(manifest, capabilitySet, "companies.read");
1201
+ let out = [...companies.values()];
1202
+ if (input?.offset)
1203
+ out = out.slice(input.offset);
1204
+ if (input?.limit)
1205
+ out = out.slice(0, input.limit);
1206
+ return out;
1207
+ },
1208
+ async get(companyId) {
1209
+ requireCapability(manifest, capabilitySet, "companies.read");
1210
+ return companies.get(companyId) ?? null;
1211
+ },
1212
+ },
1213
+ issues: {
1214
+ async list(input) {
1215
+ requireCapability(manifest, capabilitySet, "issues.read");
1216
+ const companyId = requireCompanyId(input?.companyId);
1217
+ let out = [...issues.values()];
1218
+ out = out.filter((issue) => issue.companyId === companyId);
1219
+ if (input?.projectId)
1220
+ out = out.filter((issue) => issue.projectId === input.projectId);
1221
+ if (input?.assigneeAgentId)
1222
+ out = out.filter((issue) => issue.assigneeAgentId === input.assigneeAgentId);
1223
+ if (input?.originKind) {
1224
+ if (input.originKind.startsWith("plugin:"))
1225
+ normalizePluginOriginKind(input.originKind);
1226
+ out = out.filter((issue) => issue.originKind === input.originKind);
1227
+ }
1228
+ if (input?.originKindPrefix) {
1229
+ const prefix = input.originKindPrefix;
1230
+ out = out.filter((issue) => typeof issue.originKind === "string" && issue.originKind.startsWith(prefix));
1231
+ }
1232
+ if (input?.originId)
1233
+ out = out.filter((issue) => issue.originId === input.originId);
1234
+ if (input?.status)
1235
+ out = out.filter((issue) => issue.status === input.status);
1236
+ if (input?.offset)
1237
+ out = out.slice(input.offset);
1238
+ if (input?.limit)
1239
+ out = out.slice(0, input.limit);
1240
+ return out;
1241
+ },
1242
+ async get(issueId, companyId) {
1243
+ requireCapability(manifest, capabilitySet, "issues.read");
1244
+ const issue = issues.get(issueId);
1245
+ return isInCompany(issue, companyId) ? issue : null;
1246
+ },
1247
+ async create(input) {
1248
+ requireCapability(manifest, capabilitySet, "issues.create");
1249
+ const now = new Date();
1250
+ const originKind = normalizePluginOriginKind(input.surfaceVisibility === "plugin_operation" && !input.originKind
1251
+ ? pluginOperationIssueOriginKind(manifest.id)
1252
+ : input.originKind);
1253
+ const record = {
1254
+ id: randomUUID(),
1255
+ companyId: input.companyId,
1256
+ projectId: input.projectId ?? null,
1257
+ projectWorkspaceId: null,
1258
+ goalId: input.goalId ?? null,
1259
+ parentId: input.parentId ?? null,
1260
+ title: input.title,
1261
+ description: input.description ?? null,
1262
+ status: input.status ?? "todo",
1263
+ workMode: "standard",
1264
+ priority: input.priority ?? "medium",
1265
+ assigneeAgentId: input.assigneeAgentId ?? null,
1266
+ assigneeUserId: input.assigneeUserId ?? null,
1267
+ checkoutRunId: null,
1268
+ executionRunId: null,
1269
+ executionAgentNameKey: null,
1270
+ executionLockedAt: null,
1271
+ createdByAgentId: null,
1272
+ createdByUserId: null,
1273
+ issueNumber: null,
1274
+ identifier: null,
1275
+ originKind,
1276
+ originId: input.originId ?? null,
1277
+ originRunId: input.originRunId ?? null,
1278
+ requestDepth: input.requestDepth ?? 0,
1279
+ billingCode: input.billingCode ?? null,
1280
+ assigneeAdapterOverrides: input.assigneeAdapterOverrides ?? null,
1281
+ executionWorkspaceId: input.executionWorkspaceId ?? null,
1282
+ executionWorkspacePreference: input.executionWorkspacePreference ?? null,
1283
+ executionWorkspaceSettings: input.executionWorkspaceSettings ?? null,
1284
+ startedAt: null,
1285
+ completedAt: null,
1286
+ cancelledAt: null,
1287
+ hiddenAt: null,
1288
+ createdAt: now,
1289
+ updatedAt: now,
1290
+ };
1291
+ issues.set(record.id, record);
1292
+ if (input.blockedByIssueIds)
1293
+ blockedByIssueIds.set(record.id, [...new Set(input.blockedByIssueIds)]);
1294
+ return record;
1295
+ },
1296
+ async update(issueId, patch, companyId) {
1297
+ requireCapability(manifest, capabilitySet, "issues.update");
1298
+ const record = issues.get(issueId);
1299
+ if (!isInCompany(record, companyId))
1300
+ throw new Error(`Issue not found: ${issueId}`);
1301
+ const { blockedByIssueIds: nextBlockedByIssueIds, ...issuePatch } = patch;
1302
+ if (issuePatch.originKind !== undefined) {
1303
+ issuePatch.originKind = normalizePluginOriginKind(issuePatch.originKind);
1304
+ }
1305
+ const updated = {
1306
+ ...record,
1307
+ ...issuePatch,
1308
+ updatedAt: new Date(),
1309
+ };
1310
+ issues.set(issueId, updated);
1311
+ if (nextBlockedByIssueIds !== undefined) {
1312
+ blockedByIssueIds.set(issueId, [...new Set(nextBlockedByIssueIds)]);
1313
+ }
1314
+ return updated;
1315
+ },
1316
+ async assertCheckoutOwner(input) {
1317
+ requireCapability(manifest, capabilitySet, "issues.checkout");
1318
+ const record = issues.get(input.issueId);
1319
+ if (!isInCompany(record, input.companyId))
1320
+ throw new Error(`Issue not found: ${input.issueId}`);
1321
+ if (record.status !== "in_progress" ||
1322
+ record.assigneeAgentId !== input.actorAgentId ||
1323
+ (record.checkoutRunId !== null && record.checkoutRunId !== input.actorRunId)) {
1324
+ throw new Error("Issue run ownership conflict");
1325
+ }
1326
+ return {
1327
+ issueId: record.id,
1328
+ status: record.status,
1329
+ assigneeAgentId: record.assigneeAgentId,
1330
+ checkoutRunId: record.checkoutRunId,
1331
+ adoptedFromRunId: null,
1332
+ };
1333
+ },
1334
+ async requestWakeup(issueId, companyId) {
1335
+ requireCapability(manifest, capabilitySet, "issues.wakeup");
1336
+ const record = issues.get(issueId);
1337
+ if (!isInCompany(record, companyId))
1338
+ throw new Error(`Issue not found: ${issueId}`);
1339
+ if (!record.assigneeAgentId)
1340
+ throw new Error("Issue has no assigned agent to wake");
1341
+ if (["backlog", "done", "cancelled"].includes(record.status)) {
1342
+ throw new Error(`Issue is not wakeable in status: ${record.status}`);
1343
+ }
1344
+ const unresolved = issueRelationSummary(issueId).blockedBy.filter((blocker) => blocker.status !== "done");
1345
+ if (unresolved.length > 0)
1346
+ throw new Error("Issue is blocked by unresolved blockers");
1347
+ return { queued: true, runId: randomUUID() };
1348
+ },
1349
+ async requestWakeups(issueIds, companyId) {
1350
+ requireCapability(manifest, capabilitySet, "issues.wakeup");
1351
+ const results = [];
1352
+ for (const issueId of issueIds) {
1353
+ const record = issues.get(issueId);
1354
+ if (!isInCompany(record, companyId))
1355
+ throw new Error(`Issue not found: ${issueId}`);
1356
+ if (!record.assigneeAgentId)
1357
+ throw new Error("Issue has no assigned agent to wake");
1358
+ if (["backlog", "done", "cancelled"].includes(record.status)) {
1359
+ throw new Error(`Issue is not wakeable in status: ${record.status}`);
1360
+ }
1361
+ const unresolved = issueRelationSummary(issueId).blockedBy.filter((blocker) => blocker.status !== "done");
1362
+ if (unresolved.length > 0)
1363
+ throw new Error("Issue is blocked by unresolved blockers");
1364
+ results.push({ issueId, queued: true, runId: randomUUID() });
1365
+ }
1366
+ return results;
1367
+ },
1368
+ async listComments(issueId, companyId) {
1369
+ requireCapability(manifest, capabilitySet, "issue.comments.read");
1370
+ if (!isInCompany(issues.get(issueId), companyId))
1371
+ return [];
1372
+ return issueComments.get(issueId) ?? [];
1373
+ },
1374
+ async createComment(issueId, body, companyId, options) {
1375
+ requireCapability(manifest, capabilitySet, "issue.comments.create");
1376
+ const parentIssue = issues.get(issueId);
1377
+ if (!isInCompany(parentIssue, companyId)) {
1378
+ throw new Error(`Issue not found: ${issueId}`);
1379
+ }
1380
+ const now = new Date();
1381
+ const comment = {
1382
+ id: randomUUID(),
1383
+ companyId: parentIssue.companyId,
1384
+ issueId,
1385
+ authorType: options?.authorAgentId ? "agent" : "system",
1386
+ authorAgentId: options?.authorAgentId ?? null,
1387
+ authorUserId: null,
1388
+ body,
1389
+ presentation: null,
1390
+ metadata: null,
1391
+ createdAt: now,
1392
+ updatedAt: now,
1393
+ };
1394
+ const current = issueComments.get(issueId) ?? [];
1395
+ current.push(comment);
1396
+ issueComments.set(issueId, current);
1397
+ return comment;
1398
+ },
1399
+ async createInteraction(issueId, interaction, companyId, options) {
1400
+ requireCapability(manifest, capabilitySet, "issue.interactions.create");
1401
+ const parentIssue = issues.get(issueId);
1402
+ if (!isInCompany(parentIssue, companyId)) {
1403
+ throw new Error(`Issue not found: ${issueId}`);
1404
+ }
1405
+ const now = new Date();
1406
+ const current = issueInteractions.get(issueId) ?? [];
1407
+ if (interaction.idempotencyKey) {
1408
+ const existing = current.find((entry) => entry.idempotencyKey === interaction.idempotencyKey);
1409
+ if (existing)
1410
+ return existing;
1411
+ }
1412
+ const created = {
1413
+ id: randomUUID(),
1414
+ companyId: parentIssue.companyId,
1415
+ issueId,
1416
+ kind: interaction.kind,
1417
+ status: "pending",
1418
+ continuationPolicy: interaction.continuationPolicy ?? "wake_assignee",
1419
+ idempotencyKey: interaction.idempotencyKey ?? null,
1420
+ sourceCommentId: interaction.sourceCommentId ?? null,
1421
+ sourceRunId: interaction.sourceRunId ?? null,
1422
+ title: interaction.title ?? null,
1423
+ summary: interaction.summary ?? null,
1424
+ createdByAgentId: options?.authorAgentId ?? null,
1425
+ createdByUserId: null,
1426
+ payload: interaction.payload,
1427
+ result: null,
1428
+ createdAt: now,
1429
+ updatedAt: now,
1430
+ };
1431
+ current.push(created);
1432
+ issueInteractions.set(issueId, current);
1433
+ return created;
1434
+ },
1435
+ async suggestTasks(issueId, interaction, companyId, options) {
1436
+ return this.createInteraction(issueId, { ...interaction, kind: "suggest_tasks" }, companyId, options);
1437
+ },
1438
+ async askUserQuestions(issueId, interaction, companyId, options) {
1439
+ return this.createInteraction(issueId, { ...interaction, kind: "ask_user_questions" }, companyId, options);
1440
+ },
1441
+ async requestConfirmation(issueId, interaction, companyId, options) {
1442
+ return this.createInteraction(issueId, { ...interaction, kind: "request_confirmation" }, companyId, options);
1443
+ },
1444
+ documents: {
1445
+ async list(issueId, companyId) {
1446
+ requireCapability(manifest, capabilitySet, "issue.documents.read");
1447
+ if (!isInCompany(issues.get(issueId), companyId))
1448
+ return [];
1449
+ return [...issueDocuments.values()]
1450
+ .filter((document) => document.issueId === issueId && document.companyId === companyId)
1451
+ .map(({ body: _body, ...summary }) => summary);
1452
+ },
1453
+ async get(issueId, key, companyId) {
1454
+ requireCapability(manifest, capabilitySet, "issue.documents.read");
1455
+ if (!isInCompany(issues.get(issueId), companyId))
1456
+ return null;
1457
+ return issueDocuments.get(`${issueId}|${key}`) ?? null;
1458
+ },
1459
+ async upsert(input) {
1460
+ requireCapability(manifest, capabilitySet, "issue.documents.write");
1461
+ const parentIssue = issues.get(input.issueId);
1462
+ if (!isInCompany(parentIssue, input.companyId)) {
1463
+ throw new Error(`Issue not found: ${input.issueId}`);
1464
+ }
1465
+ const now = new Date();
1466
+ const existing = issueDocuments.get(`${input.issueId}|${input.key}`);
1467
+ const document = {
1468
+ id: existing?.id ?? randomUUID(),
1469
+ companyId: input.companyId,
1470
+ issueId: input.issueId,
1471
+ key: input.key,
1472
+ title: input.title ?? existing?.title ?? null,
1473
+ format: "markdown",
1474
+ latestRevisionId: randomUUID(),
1475
+ latestRevisionNumber: (existing?.latestRevisionNumber ?? 0) + 1,
1476
+ createdByAgentId: existing?.createdByAgentId ?? null,
1477
+ createdByUserId: existing?.createdByUserId ?? null,
1478
+ updatedByAgentId: null,
1479
+ updatedByUserId: null,
1480
+ lockedAt: existing?.lockedAt ?? null,
1481
+ lockedByAgentId: existing?.lockedByAgentId ?? null,
1482
+ lockedByUserId: existing?.lockedByUserId ?? null,
1483
+ createdAt: existing?.createdAt ?? now,
1484
+ updatedAt: now,
1485
+ body: input.body,
1486
+ };
1487
+ issueDocuments.set(`${input.issueId}|${input.key}`, document);
1488
+ return document;
1489
+ },
1490
+ async delete(issueId, _key, companyId) {
1491
+ requireCapability(manifest, capabilitySet, "issue.documents.write");
1492
+ const parentIssue = issues.get(issueId);
1493
+ if (!isInCompany(parentIssue, companyId)) {
1494
+ throw new Error(`Issue not found: ${issueId}`);
1495
+ }
1496
+ issueDocuments.delete(`${issueId}|${_key}`);
1497
+ },
1498
+ },
1499
+ relations: {
1500
+ async get(issueId, companyId) {
1501
+ requireCapability(manifest, capabilitySet, "issue.relations.read");
1502
+ if (!isInCompany(issues.get(issueId), companyId))
1503
+ throw new Error(`Issue not found: ${issueId}`);
1504
+ return issueRelationSummary(issueId);
1505
+ },
1506
+ async setBlockedBy(issueId, nextBlockedByIssueIds, companyId) {
1507
+ requireCapability(manifest, capabilitySet, "issue.relations.write");
1508
+ if (!isInCompany(issues.get(issueId), companyId))
1509
+ throw new Error(`Issue not found: ${issueId}`);
1510
+ blockedByIssueIds.set(issueId, [...new Set(nextBlockedByIssueIds)]);
1511
+ return issueRelationSummary(issueId);
1512
+ },
1513
+ async addBlockers(issueId, blockerIssueIds, companyId) {
1514
+ requireCapability(manifest, capabilitySet, "issue.relations.write");
1515
+ if (!isInCompany(issues.get(issueId), companyId))
1516
+ throw new Error(`Issue not found: ${issueId}`);
1517
+ const next = new Set(blockedByIssueIds.get(issueId) ?? []);
1518
+ for (const blockerIssueId of blockerIssueIds)
1519
+ next.add(blockerIssueId);
1520
+ blockedByIssueIds.set(issueId, [...next]);
1521
+ return issueRelationSummary(issueId);
1522
+ },
1523
+ async removeBlockers(issueId, blockerIssueIds, companyId) {
1524
+ requireCapability(manifest, capabilitySet, "issue.relations.write");
1525
+ if (!isInCompany(issues.get(issueId), companyId))
1526
+ throw new Error(`Issue not found: ${issueId}`);
1527
+ const removals = new Set(blockerIssueIds);
1528
+ blockedByIssueIds.set(issueId, (blockedByIssueIds.get(issueId) ?? []).filter((blockerIssueId) => !removals.has(blockerIssueId)));
1529
+ return issueRelationSummary(issueId);
1530
+ },
1531
+ },
1532
+ async getSubtree(issueId, companyId, options) {
1533
+ requireCapability(manifest, capabilitySet, "issue.subtree.read");
1534
+ const root = issues.get(issueId);
1535
+ if (!isInCompany(root, companyId))
1536
+ throw new Error(`Issue not found: ${issueId}`);
1537
+ const includeRoot = options?.includeRoot !== false;
1538
+ const allIds = [root.id];
1539
+ let frontier = [root.id];
1540
+ while (frontier.length > 0) {
1541
+ const children = [...issues.values()]
1542
+ .filter((issue) => issue.companyId === companyId && frontier.includes(issue.parentId ?? ""))
1543
+ .map((issue) => issue.id)
1544
+ .filter((id) => !allIds.includes(id));
1545
+ allIds.push(...children);
1546
+ frontier = children;
1547
+ }
1548
+ const issueIds = includeRoot ? allIds : allIds.filter((id) => id !== root.id);
1549
+ const subtreeIssues = issueIds.map((id) => issues.get(id)).filter((candidate) => Boolean(candidate));
1550
+ return {
1551
+ rootIssueId: root.id,
1552
+ companyId,
1553
+ issueIds,
1554
+ issues: subtreeIssues,
1555
+ ...(options?.includeRelations
1556
+ ? { relations: Object.fromEntries(issueIds.map((id) => [id, issueRelationSummary(id)])) }
1557
+ : {}),
1558
+ ...(options?.includeDocuments ? { documents: Object.fromEntries(issueIds.map((id) => [id, []])) } : {}),
1559
+ ...(options?.includeActiveRuns ? { activeRuns: Object.fromEntries(issueIds.map((id) => [id, []])) } : {}),
1560
+ ...(options?.includeAssignees ? { assignees: {} } : {}),
1561
+ };
1562
+ },
1563
+ summaries: {
1564
+ async getOrchestration(input) {
1565
+ requireCapability(manifest, capabilitySet, "issues.orchestration.read");
1566
+ const root = issues.get(input.issueId);
1567
+ if (!isInCompany(root, input.companyId))
1568
+ throw new Error(`Issue not found: ${input.issueId}`);
1569
+ const subtreeIssueIds = [root.id];
1570
+ if (input.includeSubtree) {
1571
+ let frontier = [root.id];
1572
+ while (frontier.length > 0) {
1573
+ const children = [...issues.values()]
1574
+ .filter((issue) => issue.companyId === input.companyId && frontier.includes(issue.parentId ?? ""))
1575
+ .map((issue) => issue.id)
1576
+ .filter((id) => !subtreeIssueIds.includes(id));
1577
+ subtreeIssueIds.push(...children);
1578
+ frontier = children;
1579
+ }
1580
+ }
1581
+ return {
1582
+ issueId: root.id,
1583
+ companyId: input.companyId,
1584
+ subtreeIssueIds,
1585
+ relations: Object.fromEntries(subtreeIssueIds.map((id) => [id, issueRelationSummary(id)])),
1586
+ approvals: [],
1587
+ runs: [],
1588
+ costs: {
1589
+ costCents: 0,
1590
+ inputTokens: 0,
1591
+ cachedInputTokens: 0,
1592
+ outputTokens: 0,
1593
+ billingCode: input.billingCode ?? null,
1594
+ },
1595
+ openBudgetIncidents: [],
1596
+ invocationBlocks: [],
1597
+ };
1598
+ },
1599
+ },
1600
+ },
1601
+ agents: {
1602
+ async list(input) {
1603
+ requireCapability(manifest, capabilitySet, "agents.read");
1604
+ const companyId = requireCompanyId(input?.companyId);
1605
+ let out = [...agents.values()];
1606
+ out = out.filter((agent) => agent.companyId === companyId);
1607
+ if (input?.status)
1608
+ out = out.filter((agent) => agent.status === input.status);
1609
+ if (input?.offset)
1610
+ out = out.slice(input.offset);
1611
+ if (input?.limit)
1612
+ out = out.slice(0, input.limit);
1613
+ return out;
1614
+ },
1615
+ async get(agentId, companyId) {
1616
+ requireCapability(manifest, capabilitySet, "agents.read");
1617
+ const agent = agents.get(agentId);
1618
+ return isInCompany(agent, companyId) ? agent : null;
1619
+ },
1620
+ async pause(agentId, companyId) {
1621
+ requireCapability(manifest, capabilitySet, "agents.pause");
1622
+ const cid = requireCompanyId(companyId);
1623
+ const agent = agents.get(agentId);
1624
+ if (!isInCompany(agent, cid))
1625
+ throw new Error(`Agent not found: ${agentId}`);
1626
+ if (agent.status === "terminated")
1627
+ throw new Error("Cannot pause terminated agent");
1628
+ const updated = { ...agent, status: "paused", updatedAt: new Date() };
1629
+ agents.set(agentId, updated);
1630
+ return updated;
1631
+ },
1632
+ async resume(agentId, companyId) {
1633
+ requireCapability(manifest, capabilitySet, "agents.resume");
1634
+ const cid = requireCompanyId(companyId);
1635
+ const agent = agents.get(agentId);
1636
+ if (!isInCompany(agent, cid))
1637
+ throw new Error(`Agent not found: ${agentId}`);
1638
+ if (agent.status === "terminated")
1639
+ throw new Error("Cannot resume terminated agent");
1640
+ if (agent.status === "pending_approval")
1641
+ throw new Error("Pending approval agents cannot be resumed");
1642
+ const updated = { ...agent, status: "idle", updatedAt: new Date() };
1643
+ agents.set(agentId, updated);
1644
+ return updated;
1645
+ },
1646
+ async invoke(agentId, companyId, opts) {
1647
+ requireCapability(manifest, capabilitySet, "agents.invoke");
1648
+ const cid = requireCompanyId(companyId);
1649
+ const agent = agents.get(agentId);
1650
+ if (!isInCompany(agent, cid))
1651
+ throw new Error(`Agent not found: ${agentId}`);
1652
+ if (agent.status === "paused" ||
1653
+ agent.status === "terminated" ||
1654
+ agent.status === "pending_approval") {
1655
+ throw new Error(`Agent is not invokable in its current state: ${agent.status}`);
1656
+ }
1657
+ return { runId: randomUUID() };
1658
+ },
1659
+ managed: {
1660
+ async get(agentKey, companyId) {
1661
+ requireCapability(manifest, capabilitySet, "agents.managed");
1662
+ const cid = requireCompanyId(companyId);
1663
+ managedAgentDeclaration(agentKey);
1664
+ const agent = [...agents.values()].find((candidate) => candidate.companyId === cid &&
1665
+ candidate.status !== "terminated" &&
1666
+ isManagedAgent(candidate, agentKey)) ?? null;
1667
+ return managedResolution(agentKey, cid, agent, agent ? "resolved" : "missing");
1668
+ },
1669
+ async reconcile(agentKey, companyId) {
1670
+ requireCapability(manifest, capabilitySet, "agents.managed");
1671
+ const cid = requireCompanyId(companyId);
1672
+ const declaration = managedAgentDeclaration(agentKey);
1673
+ const existingAgent = [...agents.values()].find((candidate) => candidate.companyId === cid &&
1674
+ candidate.status !== "terminated" &&
1675
+ isManagedAgent(candidate, agentKey)) ?? null;
1676
+ const existing = managedResolution(agentKey, cid, existingAgent, existingAgent ? "resolved" : "missing");
1677
+ if (existing.agent)
1678
+ return existing;
1679
+ const now = new Date();
1680
+ const created = {
1681
+ id: randomUUID(),
1682
+ companyId: cid,
1683
+ name: declaration.displayName,
1684
+ urlKey: declaration.displayName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""),
1685
+ role: (declaration.role ?? "general"),
1686
+ title: declaration.title ?? null,
1687
+ icon: declaration.icon ?? null,
1688
+ status: declaration.status ?? "idle",
1689
+ reportsTo: null,
1690
+ capabilities: declaration.capabilities ?? null,
1691
+ adapterType: (declaration.adapterType ?? "process"),
1692
+ adapterConfig: declaration.adapterConfig ?? {},
1693
+ runtimeConfig: declaration.runtimeConfig ?? {},
1694
+ budgetMonthlyCents: declaration.budgetMonthlyCents ?? 0,
1695
+ spentMonthlyCents: 0,
1696
+ pauseReason: null,
1697
+ pausedAt: null,
1698
+ permissions: { canCreateAgents: Boolean(declaration.permissions?.canCreateAgents) },
1699
+ lastHeartbeatAt: null,
1700
+ metadata: managedAgentMetadata(agentKey),
1701
+ createdAt: now,
1702
+ updatedAt: now,
1703
+ };
1704
+ agents.set(created.id, created);
1705
+ return managedResolution(agentKey, cid, created, "created");
1706
+ },
1707
+ async reset(agentKey, companyId) {
1708
+ requireCapability(manifest, capabilitySet, "agents.managed");
1709
+ const cid = requireCompanyId(companyId);
1710
+ const declaration = managedAgentDeclaration(agentKey);
1711
+ let agent = [...agents.values()].find((candidate) => candidate.companyId === cid &&
1712
+ candidate.status !== "terminated" &&
1713
+ isManagedAgent(candidate, agentKey)) ?? null;
1714
+ if (!agent) {
1715
+ const now = new Date();
1716
+ agent = {
1717
+ id: randomUUID(),
1718
+ companyId: cid,
1719
+ name: declaration.displayName,
1720
+ urlKey: declaration.displayName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""),
1721
+ role: (declaration.role ?? "general"),
1722
+ title: declaration.title ?? null,
1723
+ icon: declaration.icon ?? null,
1724
+ status: declaration.status ?? "idle",
1725
+ reportsTo: null,
1726
+ capabilities: declaration.capabilities ?? null,
1727
+ adapterType: (declaration.adapterType ?? "process"),
1728
+ adapterConfig: declaration.adapterConfig ?? {},
1729
+ runtimeConfig: declaration.runtimeConfig ?? {},
1730
+ budgetMonthlyCents: declaration.budgetMonthlyCents ?? 0,
1731
+ spentMonthlyCents: 0,
1732
+ pauseReason: null,
1733
+ pausedAt: null,
1734
+ permissions: { canCreateAgents: Boolean(declaration.permissions?.canCreateAgents) },
1735
+ lastHeartbeatAt: null,
1736
+ metadata: managedAgentMetadata(agentKey),
1737
+ createdAt: now,
1738
+ updatedAt: now,
1739
+ };
1740
+ agents.set(agent.id, agent);
1741
+ }
1742
+ const resolved = managedResolution(agentKey, cid, agent, "resolved");
1743
+ if (!resolved.agent)
1744
+ return resolved;
1745
+ const updated = {
1746
+ ...resolved.agent,
1747
+ name: declaration.displayName,
1748
+ role: (declaration.role ?? "general"),
1749
+ title: declaration.title ?? null,
1750
+ icon: declaration.icon ?? null,
1751
+ capabilities: declaration.capabilities ?? null,
1752
+ adapterType: (declaration.adapterType ?? "process"),
1753
+ adapterConfig: declaration.adapterConfig ?? {},
1754
+ runtimeConfig: declaration.runtimeConfig ?? {},
1755
+ budgetMonthlyCents: declaration.budgetMonthlyCents ?? 0,
1756
+ permissions: { canCreateAgents: Boolean(declaration.permissions?.canCreateAgents) },
1757
+ metadata: managedAgentMetadata(agentKey, resolved.agent.metadata),
1758
+ updatedAt: new Date(),
1759
+ };
1760
+ agents.set(updated.id, updated);
1761
+ return managedResolution(agentKey, cid, updated, "reset");
1762
+ },
1763
+ },
1764
+ sessions: {
1765
+ async create(agentId, companyId, opts) {
1766
+ requireCapability(manifest, capabilitySet, "agent.sessions.create");
1767
+ const cid = requireCompanyId(companyId);
1768
+ const agent = agents.get(agentId);
1769
+ if (!isInCompany(agent, cid))
1770
+ throw new Error(`Agent not found: ${agentId}`);
1771
+ const session = {
1772
+ sessionId: randomUUID(),
1773
+ agentId,
1774
+ companyId: cid,
1775
+ status: "active",
1776
+ createdAt: new Date().toISOString(),
1777
+ };
1778
+ sessions.set(session.sessionId, session);
1779
+ return session;
1780
+ },
1781
+ async list(agentId, companyId) {
1782
+ requireCapability(manifest, capabilitySet, "agent.sessions.list");
1783
+ const cid = requireCompanyId(companyId);
1784
+ return [...sessions.values()].filter((s) => s.agentId === agentId && s.companyId === cid && s.status === "active");
1785
+ },
1786
+ async sendMessage(sessionId, companyId, opts) {
1787
+ requireCapability(manifest, capabilitySet, "agent.sessions.send");
1788
+ const session = sessions.get(sessionId);
1789
+ if (!session || session.status !== "active")
1790
+ throw new Error(`Session not found or closed: ${sessionId}`);
1791
+ if (session.companyId !== companyId)
1792
+ throw new Error(`Session not found: ${sessionId}`);
1793
+ if (opts.onEvent) {
1794
+ sessionEventCallbacks.set(sessionId, opts.onEvent);
1795
+ }
1796
+ return { runId: randomUUID() };
1797
+ },
1798
+ async close(sessionId, companyId) {
1799
+ requireCapability(manifest, capabilitySet, "agent.sessions.close");
1800
+ const session = sessions.get(sessionId);
1801
+ if (!session)
1802
+ throw new Error(`Session not found: ${sessionId}`);
1803
+ if (session.companyId !== companyId)
1804
+ throw new Error(`Session not found: ${sessionId}`);
1805
+ session.status = "closed";
1806
+ sessionEventCallbacks.delete(sessionId);
1807
+ },
1808
+ },
1809
+ },
1810
+ goals: {
1811
+ async list(input) {
1812
+ requireCapability(manifest, capabilitySet, "goals.read");
1813
+ const companyId = requireCompanyId(input?.companyId);
1814
+ let out = [...goals.values()];
1815
+ out = out.filter((goal) => goal.companyId === companyId);
1816
+ if (input?.level)
1817
+ out = out.filter((goal) => goal.level === input.level);
1818
+ if (input?.status)
1819
+ out = out.filter((goal) => goal.status === input.status);
1820
+ if (input?.offset)
1821
+ out = out.slice(input.offset);
1822
+ if (input?.limit)
1823
+ out = out.slice(0, input.limit);
1824
+ return out;
1825
+ },
1826
+ async get(goalId, companyId) {
1827
+ requireCapability(manifest, capabilitySet, "goals.read");
1828
+ const goal = goals.get(goalId);
1829
+ return isInCompany(goal, companyId) ? goal : null;
1830
+ },
1831
+ async create(input) {
1832
+ requireCapability(manifest, capabilitySet, "goals.create");
1833
+ const now = new Date();
1834
+ const record = {
1835
+ id: randomUUID(),
1836
+ companyId: input.companyId,
1837
+ title: input.title,
1838
+ description: input.description ?? null,
1839
+ level: input.level ?? "task",
1840
+ status: input.status ?? "planned",
1841
+ parentId: input.parentId ?? null,
1842
+ ownerAgentId: input.ownerAgentId ?? null,
1843
+ createdAt: now,
1844
+ updatedAt: now,
1845
+ };
1846
+ goals.set(record.id, record);
1847
+ return record;
1848
+ },
1849
+ async update(goalId, patch, companyId) {
1850
+ requireCapability(manifest, capabilitySet, "goals.update");
1851
+ const record = goals.get(goalId);
1852
+ if (!isInCompany(record, companyId))
1853
+ throw new Error(`Goal not found: ${goalId}`);
1854
+ const updated = {
1855
+ ...record,
1856
+ ...patch,
1857
+ updatedAt: new Date(),
1858
+ };
1859
+ goals.set(goalId, updated);
1860
+ return updated;
1861
+ },
1862
+ },
1863
+ access: {
1864
+ members: {
1865
+ async list(input) {
1866
+ requireCapability(manifest, capabilitySet, "access.members.read");
1867
+ const cid = requireCompanyId(input.companyId);
1868
+ const includeArchived = input.includeArchived === true;
1869
+ return [...accessMembers.values()]
1870
+ .filter((member) => member.companyId === cid)
1871
+ .filter((member) => includeArchived || member.status !== "archived")
1872
+ .map((member) => ({
1873
+ ...member,
1874
+ grants: getPrincipalGrants(cid, member.principalType, member.principalId),
1875
+ }));
1876
+ },
1877
+ async get(memberId, companyId) {
1878
+ requireCapability(manifest, capabilitySet, "access.members.read");
1879
+ const cid = requireCompanyId(companyId);
1880
+ const member = accessMembers.get(memberId);
1881
+ if (!member || member.companyId !== cid)
1882
+ return null;
1883
+ return {
1884
+ ...member,
1885
+ grants: getPrincipalGrants(cid, member.principalType, member.principalId),
1886
+ };
1887
+ },
1888
+ async update(memberId, patch, companyId) {
1889
+ requireCapability(manifest, capabilitySet, "access.members.write");
1890
+ const cid = requireCompanyId(companyId);
1891
+ const member = accessMembers.get(memberId);
1892
+ if (!member || member.companyId !== cid) {
1893
+ throw new Error(`Membership not found: ${memberId}`);
1894
+ }
1895
+ const updated = {
1896
+ ...member,
1897
+ membershipRole: patch.membershipRole === undefined ? member.membershipRole : patch.membershipRole,
1898
+ status: patch.status === undefined ? member.status : patch.status,
1899
+ updatedAt: new Date().toISOString(),
1900
+ };
1901
+ accessMembers.set(memberId, updated);
1902
+ return {
1903
+ ...updated,
1904
+ grants: getPrincipalGrants(cid, updated.principalType, updated.principalId),
1905
+ };
1906
+ },
1907
+ },
1908
+ invites: {
1909
+ async list(input) {
1910
+ requireCapability(manifest, capabilitySet, "access.invites.read");
1911
+ requireCompanyId(input.companyId);
1912
+ return { invites: [], nextOffset: null };
1913
+ },
1914
+ async create(input) {
1915
+ requireCapability(manifest, capabilitySet, "access.invites.write");
1916
+ requireCompanyId(input.companyId);
1917
+ throw new Error("Invite creation is not implemented in the plugin test harness");
1918
+ },
1919
+ async revoke(inviteId, companyId) {
1920
+ requireCapability(manifest, capabilitySet, "access.invites.write");
1921
+ requireCompanyId(companyId);
1922
+ throw new Error(`Invite not found: ${inviteId}`);
1923
+ },
1924
+ },
1925
+ },
1926
+ authorization: {
1927
+ grants: {
1928
+ async list(input) {
1929
+ requireCapability(manifest, capabilitySet, "authorization.grants.read");
1930
+ const cid = requireCompanyId(input.companyId);
1931
+ if (input.principalType && input.principalId) {
1932
+ return getPrincipalGrants(cid, input.principalType, input.principalId);
1933
+ }
1934
+ const out = [];
1935
+ for (const [key, grants] of principalGrants.entries()) {
1936
+ if (!key.startsWith(`${cid}:`))
1937
+ continue;
1938
+ for (const grant of grants) {
1939
+ if (input.principalType && grant.principalType !== input.principalType)
1940
+ continue;
1941
+ if (input.principalId && grant.principalId !== input.principalId)
1942
+ continue;
1943
+ out.push(grant);
1944
+ }
1945
+ }
1946
+ return out;
1947
+ },
1948
+ async set(input) {
1949
+ requireCapability(manifest, capabilitySet, "authorization.grants.write");
1950
+ const cid = requireCompanyId(input.companyId);
1951
+ return setPrincipalGrants(cid, input.principalType, input.principalId, input.grants);
1952
+ },
1953
+ },
1954
+ policies: {
1955
+ async summary(companyId) {
1956
+ requireCapability(manifest, capabilitySet, "authorization.policies.read");
1957
+ const cid = requireCompanyId(companyId);
1958
+ const members = [...accessMembers.values()].filter((member) => member.companyId === cid);
1959
+ let grantCount = 0;
1960
+ for (const [key, grants] of principalGrants.entries()) {
1961
+ if (key.startsWith(`${cid}:`))
1962
+ grantCount += grants.length;
1963
+ }
1964
+ return {
1965
+ companyId: cid,
1966
+ permissionsMode: "simple",
1967
+ memberCount: members.length,
1968
+ activeMemberCount: members.filter((member) => member.status === "active").length,
1969
+ grantCount,
1970
+ advancedPolicyAvailable: false,
1971
+ };
1972
+ },
1973
+ async get(input) {
1974
+ requireCapability(manifest, capabilitySet, "authorization.policies.read");
1975
+ requireCompanyId(input.companyId);
1976
+ return null;
1977
+ },
1978
+ async update(input) {
1979
+ requireCapability(manifest, capabilitySet, "authorization.policies.write");
1980
+ const cid = requireCompanyId(input.companyId);
1981
+ return {
1982
+ companyId: cid,
1983
+ resourceType: input.resourceType,
1984
+ resourceId: input.resourceId,
1985
+ policy: input.policy,
1986
+ updatedAt: new Date().toISOString(),
1987
+ };
1988
+ },
1989
+ async previewAssignment(input) {
1990
+ requireCapability(manifest, capabilitySet, "authorization.policies.read");
1991
+ requireCompanyId(input.companyId);
1992
+ return {
1993
+ allowed: true,
1994
+ action: "issue.assign",
1995
+ explanation: "Allowed by simple company-wide defaults in the plugin test harness.",
1996
+ reason: "simple_mode",
1997
+ };
1998
+ },
1999
+ async explainAssignment(input) {
2000
+ requireCapability(manifest, capabilitySet, "authorization.policies.read");
2001
+ requireCompanyId(input.companyId);
2002
+ return {
2003
+ allowed: true,
2004
+ action: "issue.assign",
2005
+ explanation: "Allowed by simple company-wide defaults in the plugin test harness.",
2006
+ reason: "simple_mode",
2007
+ };
2008
+ },
2009
+ },
2010
+ audit: {
2011
+ async search(input) {
2012
+ requireCapability(manifest, capabilitySet, "authorization.audit.read");
2013
+ requireCompanyId(input.companyId);
2014
+ return [];
2015
+ },
2016
+ },
2017
+ },
2018
+ data: {
2019
+ register(key, handler) {
2020
+ dataHandlers.set(key, handler);
2021
+ },
2022
+ },
2023
+ actions: {
2024
+ register(key, handler) {
2025
+ actionHandlers.set(key, handler);
2026
+ },
2027
+ },
2028
+ streams: (() => {
2029
+ const channelCompanyMap = new Map();
2030
+ return {
2031
+ open(channel, companyId) {
2032
+ channelCompanyMap.set(channel, companyId);
2033
+ },
2034
+ emit(_channel, _event) {
2035
+ // No-op in test harness — events are not forwarded
2036
+ },
2037
+ close(channel) {
2038
+ channelCompanyMap.delete(channel);
2039
+ },
2040
+ };
2041
+ })(),
2042
+ tools: {
2043
+ register(name, _decl, fn) {
2044
+ requireCapability(manifest, capabilitySet, "agent.tools.register");
2045
+ toolHandlers.set(name, fn);
2046
+ },
2047
+ },
2048
+ metrics: {
2049
+ async write(name, value, tags) {
2050
+ requireCapability(manifest, capabilitySet, "metrics.write");
2051
+ metrics.push({ name, value, tags });
2052
+ },
2053
+ },
2054
+ telemetry: {
2055
+ async track(eventName, dimensions) {
2056
+ requireCapability(manifest, capabilitySet, "telemetry.track");
2057
+ telemetry.push({ eventName, dimensions });
2058
+ },
2059
+ },
2060
+ logger: {
2061
+ info(message, meta) {
2062
+ logs.push({ level: "info", message, meta });
2063
+ },
2064
+ warn(message, meta) {
2065
+ logs.push({ level: "warn", message, meta });
2066
+ },
2067
+ error(message, meta) {
2068
+ logs.push({ level: "error", message, meta });
2069
+ },
2070
+ debug(message, meta) {
2071
+ logs.push({ level: "debug", message, meta });
2072
+ },
2073
+ },
2074
+ };
2075
+ const harness = {
2076
+ ctx,
2077
+ seed(input) {
2078
+ for (const row of input.companies ?? [])
2079
+ companies.set(row.id, row);
2080
+ for (const row of input.projects ?? [])
2081
+ projects.set(row.id, row);
2082
+ for (const row of input.issues ?? []) {
2083
+ issues.set(row.id, row);
2084
+ if (row.blockedBy) {
2085
+ blockedByIssueIds.set(row.id, row.blockedBy.map((blocker) => blocker.id));
2086
+ }
2087
+ }
2088
+ for (const row of input.issueComments ?? []) {
2089
+ const list = issueComments.get(row.issueId) ?? [];
2090
+ list.push(row);
2091
+ issueComments.set(row.issueId, list);
2092
+ }
2093
+ for (const row of input.agents ?? [])
2094
+ agents.set(row.id, row);
2095
+ for (const row of input.goals ?? [])
2096
+ goals.set(row.id, row);
2097
+ for (const row of input.projectWorkspaces ?? []) {
2098
+ const list = projectWorkspaces.get(row.projectId) ?? [];
2099
+ list.push(row);
2100
+ projectWorkspaces.set(row.projectId, list);
2101
+ }
2102
+ for (const row of input.executionWorkspaces ?? [])
2103
+ executionWorkspaces.set(row.id, row);
2104
+ for (const row of input.accessMembers ?? [])
2105
+ accessMembers.set(row.id, row);
2106
+ for (const row of input.principalGrants ?? []) {
2107
+ const list = principalGrants.get(principalGrantsKey(row.companyId, row.principalType, row.principalId)) ?? [];
2108
+ list.push(row);
2109
+ principalGrants.set(principalGrantsKey(row.companyId, row.principalType, row.principalId), list);
2110
+ }
2111
+ },
2112
+ setConfig(config) {
2113
+ currentConfig = { ...config };
2114
+ },
2115
+ async emit(eventType, payload, base) {
2116
+ const event = {
2117
+ eventId: base?.eventId ?? randomUUID(),
2118
+ eventType,
2119
+ companyId: base?.companyId ?? "test-company",
2120
+ occurredAt: base?.occurredAt ?? new Date().toISOString(),
2121
+ actorId: base?.actorId,
2122
+ actorType: base?.actorType,
2123
+ entityId: base?.entityId,
2124
+ entityType: base?.entityType,
2125
+ payload,
2126
+ };
2127
+ for (const handler of events) {
2128
+ const exactMatch = handler.name === event.eventType;
2129
+ const wildcardPluginAll = handler.name === "plugin.*" && String(event.eventType).startsWith("plugin.");
2130
+ const wildcardPluginOne = String(handler.name).endsWith(".*")
2131
+ && String(event.eventType).startsWith(String(handler.name).slice(0, -1));
2132
+ if (!exactMatch && !wildcardPluginAll && !wildcardPluginOne)
2133
+ continue;
2134
+ if (!allowsEvent(handler.filter, event))
2135
+ continue;
2136
+ await handler.fn(event);
2137
+ }
2138
+ },
2139
+ async runJob(jobKey, partial = {}) {
2140
+ const handler = jobs.get(jobKey);
2141
+ if (!handler)
2142
+ throw new Error(`No job handler registered for '${jobKey}'`);
2143
+ await handler({
2144
+ jobKey,
2145
+ runId: partial.runId ?? randomUUID(),
2146
+ trigger: partial.trigger ?? "manual",
2147
+ scheduledAt: partial.scheduledAt ?? new Date().toISOString(),
2148
+ });
2149
+ },
2150
+ async getData(key, params = {}) {
2151
+ const handler = dataHandlers.get(key);
2152
+ if (!handler)
2153
+ throw new Error(`No data handler registered for '${key}'`);
2154
+ return await handler(params);
2155
+ },
2156
+ async performAction(key, params = {}, options) {
2157
+ const handler = actionHandlers.get(key);
2158
+ if (!handler)
2159
+ throw new Error(`No action handler registered for '${key}'`);
2160
+ const context = actionContextFor(params, options);
2161
+ return await handler(paramsWithHostCompanyScope(params, context, options), context);
2162
+ },
2163
+ async executeTool(name, params, runCtx = {}) {
2164
+ const handler = toolHandlers.get(name);
2165
+ if (!handler)
2166
+ throw new Error(`No tool handler registered for '${name}'`);
2167
+ const ctxToPass = {
2168
+ agentId: runCtx.agentId ?? "agent-test",
2169
+ runId: runCtx.runId ?? randomUUID(),
2170
+ companyId: runCtx.companyId ?? "company-test",
2171
+ projectId: runCtx.projectId ?? "project-test",
2172
+ };
2173
+ return await handler(params, ctxToPass);
2174
+ },
2175
+ getState(input) {
2176
+ return state.get(stateMapKey(input));
2177
+ },
2178
+ simulateSessionEvent(sessionId, event) {
2179
+ const cb = sessionEventCallbacks.get(sessionId);
2180
+ if (!cb)
2181
+ throw new Error(`No active session event callback for session: ${sessionId}`);
2182
+ cb({ ...event, sessionId });
2183
+ },
2184
+ logs,
2185
+ activity,
2186
+ metrics,
2187
+ telemetry,
2188
+ dbQueries,
2189
+ dbExecutes,
2190
+ };
2191
+ return harness;
2192
+ }
2193
+ /**
2194
+ * Create an environment-aware test harness that wraps the base harness with
2195
+ * environment driver simulation and lifecycle event recording.
2196
+ *
2197
+ * Use this to test environment plugins through the full host contract:
2198
+ * validateConfig → probe → acquireLease → realizeWorkspace → execute → releaseLease.
2199
+ */
2200
+ export function createEnvironmentTestHarness(options) {
2201
+ const base = createTestHarness(options);
2202
+ const environmentEvents = [];
2203
+ const driver = options.environmentDriver;
2204
+ function record(type, params, result, error) {
2205
+ const event = {
2206
+ type,
2207
+ driverKey: params.driverKey ?? driver.driverKey,
2208
+ environmentId: params.environmentId ?? "unknown",
2209
+ timestamp: new Date().toISOString(),
2210
+ params,
2211
+ result,
2212
+ error,
2213
+ };
2214
+ environmentEvents.push(event);
2215
+ return event;
2216
+ }
2217
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2218
+ async function callHook(type, hook, params, hookName) {
2219
+ if (!hook) {
2220
+ const err = `Environment driver '${driver.driverKey}' does not implement ${hookName}`;
2221
+ record(type, params, undefined, err);
2222
+ throw new Error(err);
2223
+ }
2224
+ try {
2225
+ const result = await hook(params);
2226
+ record(type, params, result);
2227
+ return result;
2228
+ }
2229
+ catch (e) {
2230
+ const msg = e instanceof Error ? e.message : String(e);
2231
+ record(type, params, undefined, msg);
2232
+ throw e;
2233
+ }
2234
+ }
2235
+ const envHarness = {
2236
+ ...base,
2237
+ environmentEvents,
2238
+ async validateConfig(params) {
2239
+ return callHook("validateConfig", driver.onValidateConfig, params, "onValidateConfig");
2240
+ },
2241
+ async probe(params) {
2242
+ return callHook("probe", driver.onProbe, params, "onProbe");
2243
+ },
2244
+ async acquireLease(params) {
2245
+ return callHook("acquireLease", driver.onAcquireLease, params, "onAcquireLease");
2246
+ },
2247
+ async resumeLease(params) {
2248
+ return callHook("resumeLease", driver.onResumeLease, params, "onResumeLease");
2249
+ },
2250
+ async releaseLease(params) {
2251
+ return callHook("releaseLease", driver.onReleaseLease, params, "onReleaseLease");
2252
+ },
2253
+ async destroyLease(params) {
2254
+ return callHook("destroyLease", driver.onDestroyLease, params, "onDestroyLease");
2255
+ },
2256
+ async realizeWorkspace(params) {
2257
+ return callHook("realizeWorkspace", driver.onRealizeWorkspace, params, "onRealizeWorkspace");
2258
+ },
2259
+ async execute(params) {
2260
+ return callHook("execute", driver.onExecute, params, "onExecute");
2261
+ },
2262
+ };
2263
+ return envHarness;
2264
+ }
2265
+ //# sourceMappingURL=testing.js.map