@deepseek-ai/dsh-cordis-host-runner 0.2.2-alpha.3 → 0.2.2-rc.2

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.
@@ -0,0 +1,292 @@
1
+ /** Host registry for model-visible, read-only Cordis capability queries. */
2
+
3
+ import { Service } from '@deepseek-ai/cordis'
4
+ import type { Context } from '@deepseek-ai/cordis'
5
+ import type { Agent } from '@deepseek-ai/dsh-agent'
6
+ import type {} from '@deepseek-ai/dsh-api-gateway'
7
+ import { snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values'
8
+ import { assertSupportedJsonSchema, validateJsonSchemaValue } from '@deepseek-ai/dsh-tools'
9
+ import type { JsonSchemaNode } from '@deepseek-ai/dsh-tools'
10
+ import type {
11
+ CordisInspectMethodManifest, CordisInspectPlatform, CordisInspectProviderManifest,
12
+ CordisInspectProviderView, CordisInspectQueryRequest, CordisInspectQueryResolution,
13
+ CordisInspectRequestId, CordisInspectResolveAck,
14
+ } from './types.ts'
15
+
16
+ /** Context supplied to a Host inspect query. */
17
+ export interface HostCordisInspectQueryContext {
18
+ /** Tool-call cancellation. */
19
+ signal: AbortSignal
20
+ /** Agent whose scoped runtime is being inspected. */
21
+ agent: Agent
22
+ }
23
+
24
+ /** Local registration paired with its serializable manifest. */
25
+ export interface HostCordisInspectProviderRegistration {
26
+ /** Provider and explicit method directory. */
27
+ manifest: CordisInspectProviderManifest
28
+ /** Execute one declared method. */
29
+ query(method: string, input: JsonValue | undefined, context: HostCordisInspectQueryContext): Promise<JsonValue>
30
+ }
31
+
32
+ interface PendingClientQuery {
33
+ request: CordisInspectQueryRequest
34
+ method: CordisInspectMethodManifest
35
+ failure?: string
36
+ settle(resolution: CordisInspectQueryResolution): void
37
+ }
38
+
39
+ declare module '@deepseek-ai/cordis' {
40
+ interface Context {
41
+ /** Host registry for Cordis inspect providers and Client manifest/query routing. */
42
+ cordisInspect: CordisInspectRegistryService
43
+ }
44
+ }
45
+
46
+ /** Registry and cross-page router behind the two model-facing inspect tools. */
47
+ export class CordisInspectRegistryService extends Service {
48
+ private readonly providers = new Map<string, HostCordisInspectProviderRegistration>()
49
+ private readonly pending = new Map<CordisInspectRequestId, PendingClientQuery>()
50
+ private clientManifest: readonly CordisInspectProviderManifest[] | undefined
51
+ private nextRequest = 1
52
+
53
+ /**
54
+ * Register the process-global Host registry.
55
+ * @param ctx - owning Host context.
56
+ * @param clientQueryTimeoutMs - maximum wait for a valid Client response, in milliseconds.
57
+ */
58
+ constructor(ctx: Context, private readonly clientQueryTimeoutMs: number) {
59
+ super(ctx, 'cordisInspect')
60
+ ctx.effect(() => () => {
61
+ for (const pending of this.pending.values()) {
62
+ pending.settle({ ok: false, reason: 'cancelled', message: 'Client inspect registry was disposed' })
63
+ }
64
+ }, 'cordis-inspect: pending queries')
65
+ }
66
+
67
+ /**
68
+ * Register one Host provider.
69
+ * @param registration - manifest and local query handler.
70
+ * @returns idempotent disposer.
71
+ */
72
+ register(registration: HostCordisInspectProviderRegistration): () => void {
73
+ const manifest = validateManifest(registration.manifest)
74
+ if (this.providers.has(manifest.id)) throw new Error(`Host Cordis inspect provider "${manifest.id}" is already registered`)
75
+ const stored = { ...registration, manifest }
76
+ this.providers.set(manifest.id, stored)
77
+ return () => {
78
+ if (this.providers.get(manifest.id) === stored) this.providers.delete(manifest.id)
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Replace the mirrored Client provider directory.
84
+ * @param providers - complete Client manifest snapshot.
85
+ */
86
+ syncClientManifest(providers: readonly CordisInspectProviderManifest[]): void {
87
+ const ids = new Set<string>()
88
+ const validated = providers.map((provider) => {
89
+ const manifest = validateManifest(provider)
90
+ if (ids.has(manifest.id)) throw new Error(`Client Cordis inspect manifest repeats provider "${manifest.id}"`)
91
+ ids.add(manifest.id)
92
+ return manifest
93
+ })
94
+ this.clientManifest = Object.freeze(validated)
95
+ }
96
+
97
+ /**
98
+ * Return the complete known Host and Client provider directory.
99
+ * @returns Host providers followed by the Client providers.
100
+ */
101
+ list(): CordisInspectProviderView[] {
102
+ return [
103
+ ...[...this.providers.values()].map(provider => view('host', provider.manifest)),
104
+ ...(this.clientManifest ?? []).map(provider => view('client', provider)),
105
+ ]
106
+ }
107
+
108
+ /**
109
+ * Execute one provider query on its owning platform.
110
+ * @param platform - Host or Client runtime.
111
+ * @param providerId - provider selected from {@link list}.
112
+ * @param methodName - declared method name.
113
+ * @param input - optional lossless JSON input.
114
+ * @param agent - requesting Agent and scope.
115
+ * @param signal - tool-call cancellation.
116
+ * @returns provider JSON data; Client queries fail fast when Gateway has no live Client
117
+ * and retain only the first observed failure diagnostic for timeout reporting.
118
+ */
119
+ async query(
120
+ platform: CordisInspectPlatform,
121
+ providerId: string,
122
+ methodName: string,
123
+ input: JsonValue | undefined,
124
+ agent: Agent,
125
+ signal: AbortSignal,
126
+ ): Promise<JsonValue> {
127
+ if (platform === 'host') {
128
+ const registration = this.providers.get(providerId)
129
+ if (registration === undefined) throw new Error(`Host Cordis inspect provider "${providerId}" is not registered`)
130
+ const method = findMethod(registration.manifest, methodName)
131
+ validateInput('Host', providerId, method, input)
132
+ signal.throwIfAborted()
133
+ const data = await registration.query(methodName, input, { agent, signal })
134
+ signal.throwIfAborted()
135
+ return validateOutput('Host', providerId, method, data)
136
+ }
137
+ return await this.queryClient(providerId, methodName, input, agent, signal)
138
+ }
139
+
140
+ /**
141
+ * Accept the first valid Client response for a pending query.
142
+ * @param agent - Agent whose Session owns the query.
143
+ * @param requestId - Pending Client query identity.
144
+ * @param resolution - Client provider result or failure.
145
+ * @returns acknowledgement with accepted true only for a success that settles the query; only the first failure diagnostic is retained.
146
+ */
147
+ resolveClientQuery(
148
+ agent: Agent,
149
+ requestId: CordisInspectRequestId,
150
+ resolution: CordisInspectQueryResolution,
151
+ ): CordisInspectResolveAck {
152
+ const pending = this.pending.get(requestId)
153
+ if (pending === undefined || pending.request.agentId !== agent.id) return { accepted: false }
154
+ // A failed page must not prevent another page from supplying a valid result.
155
+ if (!resolution.ok) {
156
+ pending.failure ??= `${resolution.reason}: ${resolution.message}`
157
+ return { accepted: false }
158
+ }
159
+ try {
160
+ resolution = {
161
+ ok: true,
162
+ data: validateOutput('Client', pending.request.provider, pending.method, resolution.data),
163
+ }
164
+ } catch (error) {
165
+ pending.failure ??= error instanceof Error ? error.message : String(error)
166
+ return { accepted: false }
167
+ }
168
+ pending.settle(resolution)
169
+ return { accepted: true }
170
+ }
171
+
172
+ private async queryClient(
173
+ providerId: string,
174
+ methodName: string,
175
+ input: JsonValue | undefined,
176
+ agent: Agent,
177
+ signal: AbortSignal,
178
+ ): Promise<JsonValue> {
179
+ const provider = this.clientManifest?.find(candidate => candidate.id === providerId)
180
+ if (provider === undefined) throw new Error(`Client Cordis inspect provider "${providerId}" is not registered`)
181
+ const method = findMethod(provider, methodName)
182
+ validateInput('Client', providerId, method, input)
183
+ signal.throwIfAborted()
184
+ const gateway = this.ctx.get('typertGateway')
185
+ if (gateway !== undefined && !gateway.hasLiveClient()) {
186
+ throw new Error(`Client inspect query ${providerId}.${methodName} has no connected Harness page. Open or reconnect the Harness page, then retry.`)
187
+ }
188
+ const requestId = `inspect-${this.nextRequest++}` as CordisInspectRequestId
189
+ const request: CordisInspectQueryRequest = {
190
+ requestId,
191
+ agentId: agent.id,
192
+ provider: providerId,
193
+ method: methodName,
194
+ ...input === undefined ? {} : { input },
195
+ }
196
+ const result = new Promise<CordisInspectQueryResolution>((resolve) => {
197
+ this.pending.set(requestId, {
198
+ request,
199
+ method,
200
+ settle: (resolution) => {
201
+ this.pending.delete(requestId)
202
+ resolve(resolution)
203
+ try {
204
+ this.ctx.emit('cordis/inspect-query-resolved', { requestId })
205
+ } catch (error) {
206
+ console.error('[cordis-host-runner] notifying Client inspect completion failed:', error)
207
+ }
208
+ },
209
+ })
210
+ })
211
+ const onAbort = (): void => {
212
+ this.pending.get(requestId)?.settle({
213
+ ok: false,
214
+ reason: 'cancelled',
215
+ message: `Client inspect query ${providerId}.${methodName} was cancelled`,
216
+ })
217
+ }
218
+ const timer = setTimeout(() => {
219
+ const pending = this.pending.get(requestId)
220
+ if (pending === undefined) return
221
+ const detail = pending.failure === undefined
222
+ ? 'Open or reconnect the Harness page, then retry.'
223
+ : `Client failure: ${pending.failure}`
224
+ pending.settle({
225
+ ok: false,
226
+ reason: 'provider-error',
227
+ message: `Client inspect query ${providerId}.${methodName} timed out after ${this.clientQueryTimeoutMs}ms. ${detail}`,
228
+ })
229
+ }, this.clientQueryTimeoutMs)
230
+ signal.addEventListener('abort', onAbort, { once: true })
231
+ try {
232
+ if (signal.aborted) onAbort()
233
+ else this.ctx.emit('cordis/inspect-query', request)
234
+ const resolution = await result
235
+ if (!resolution.ok) throw new Error(`${providerId}.${methodName}: ${resolution.message}`)
236
+ return resolution.data
237
+ } finally {
238
+ clearTimeout(timer)
239
+ signal.removeEventListener('abort', onAbort)
240
+ this.pending.delete(requestId)
241
+ }
242
+ }
243
+ }
244
+
245
+ function view(platform: CordisInspectPlatform, manifest: CordisInspectProviderManifest): CordisInspectProviderView {
246
+ return { platform, ...manifest, methods: [...manifest.methods] }
247
+ }
248
+
249
+ function validateManifest(manifest: CordisInspectProviderManifest): CordisInspectProviderManifest {
250
+ if (manifest.id.trim() === '') throw new Error('Cordis inspect provider id must not be empty')
251
+ if (manifest.description.trim() === '') throw new Error(`Cordis inspect provider "${manifest.id}" needs a description`)
252
+ const names = new Set<string>()
253
+ const methods = manifest.methods.map((method) => {
254
+ if (method.name.trim() === '') throw new Error(`Cordis inspect provider "${manifest.id}" has an empty method name`)
255
+ if (names.has(method.name)) throw new Error(`Cordis inspect provider "${manifest.id}" repeats method "${method.name}"`)
256
+ if (method.description.trim() === '') throw new Error(`Cordis inspect method ${manifest.id}.${method.name} needs a description`)
257
+ assertSupportedJsonSchema(method.inputSchema)
258
+ assertSupportedJsonSchema(method.outputSchema)
259
+ names.add(method.name)
260
+ return Object.freeze({ ...method })
261
+ })
262
+ return Object.freeze({ ...manifest, methods: Object.freeze(methods) })
263
+ }
264
+
265
+ function findMethod(manifest: CordisInspectProviderManifest, name: string): CordisInspectMethodManifest {
266
+ const method = manifest.methods.find(candidate => candidate.name === name)
267
+ if (method === undefined) throw new Error(`Cordis inspect provider "${manifest.id}" has no method "${name}"`)
268
+ return method
269
+ }
270
+
271
+ function validateInput(
272
+ platform: 'Host' | 'Client',
273
+ provider: string,
274
+ method: CordisInspectMethodManifest,
275
+ input: JsonValue | undefined,
276
+ ): void {
277
+ const violations = validateJsonSchemaValue(method.inputSchema as JsonSchemaNode, input ?? {}, 'input')
278
+ if (violations.length > 0) throw new Error(`${platform} Cordis inspect ${provider}.${method.name} rejected input: ${violations.join('; ')}`)
279
+ }
280
+
281
+ function validateOutput(
282
+ platform: 'Host' | 'Client',
283
+ provider: string,
284
+ method: CordisInspectMethodManifest,
285
+ data: JsonValue,
286
+ ): JsonValue {
287
+ const snapshot = snapshotJsonValue(data)
288
+ if (snapshot === undefined) throw new Error(`${platform} Cordis inspect ${provider}.${method.name} returned a non-JSON value`)
289
+ const violations = validateJsonSchemaValue(method.outputSchema as JsonSchemaNode, snapshot, 'output')
290
+ if (violations.length > 0) throw new Error(`${platform} Cordis inspect ${provider}.${method.name} returned invalid output: ${violations.join('; ')}`)
291
+ return snapshot
292
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Host-half fiber lifecycle over the `cordis-dynamic` group: settle a
3
+ * sandbox-produced plugin as a child fiber (never leaving a failed fiber
4
+ * mounted), and report the services a settled-but-pending fiber still waits
5
+ * for. Stopping needs no helper — a host half unwinds through an ordinary
6
+ * awaited `fiber.dispose()`, because everything the plugin registered is an
7
+ * effect on its fiber.
8
+ * @module @deepseek-ai/dsh-cordis-host-runner/lifecycle
9
+ */
10
+
11
+ import type { Context, Fiber, Plugin } from '@deepseek-ai/cordis'
12
+ import { guardedPlugin } from './guard.ts'
13
+
14
+ /**
15
+ * Await the group, start and settle one guarded child, and dispose it before rethrowing any
16
+ * startup failure so a failed run never lingers. A valid unresolved inject may remain pending.
17
+ * @param group - the `cordis-dynamic` group fiber every host half hangs under.
18
+ * @param plugin - the plugin the sandbox returned; wrapped with the registration guard before starting.
19
+ * @param reportGuardFailure - reports post-activation Host guard rejections to the owning Agent.
20
+ * @returns the settled child fiber (possibly pending on unsatisfied `inject`).
21
+ */
22
+ export async function startHostHalf(
23
+ group: Fiber,
24
+ plugin: Plugin,
25
+ reportGuardFailure: (error: Error) => void,
26
+ ): Promise<Fiber> {
27
+ await group.await()
28
+ const fiber = group.ctx.plugin(guardedPlugin(plugin, reportGuardFailure))
29
+ try {
30
+ await fiber.await()
31
+ } catch (error) {
32
+ await fiber.dispose()
33
+ const message = error instanceof Error ? error.message : String(error)
34
+ // The commonest startup collision is running a NEW version of a package
35
+ // while the old run still holds the name — teach the replace recipe.
36
+ if (message.includes('already registered')) {
37
+ throw new Error(
38
+ `${message} — to REPLACE something an earlier dynamic package registered, first stop that package through its runner or the Cordis panel `
39
+ + 'before running the new version.',
40
+ )
41
+ }
42
+ throw error instanceof Error ? error : new Error(message)
43
+ }
44
+ return fiber
45
+ }
46
+
47
+ /**
48
+ * The services a fiber declared in `inject` that do not exist yet — a settled
49
+ * fiber that is not active is waiting on exactly these (legal cordis
50
+ * semantics: it activates when the service appears).
51
+ * @param ctx - the context to resolve service existence against.
52
+ * @param fiber - the host-half fiber whose `inject` declarations are checked.
53
+ * @returns the missing service names, in declaration order.
54
+ */
55
+ export function missingServices(ctx: Context, fiber: Fiber): string[] {
56
+ return Object.keys(fiber.inject).filter(service => ctx.get(service) === undefined)
57
+ }
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Process-local dynamic Plugin registry and its opaque identity mints.
3
+ * @module @deepseek-ai/dsh-cordis-host-runner/registry
4
+ */
5
+
6
+ import type { Fiber } from '@deepseek-ai/cordis'
7
+ import type { SessionId } from '@deepseek-ai/dsh-session/types'
8
+ import type {
9
+ ApprovalRequestId, CordisDynamicPackageId, CordisDynamicPluginId, CordisDynamicPluginRunId,
10
+ CordisDynamicRunMode, DynamicCordisRenderFailure, DynamicCordisRunAttempt,
11
+ } from './types.ts'
12
+
13
+ /** One Host method exposed to this package's Client half. */
14
+ export type DynamicCordisHandler = (args: unknown) => Promise<unknown>
15
+
16
+ /** One live activation and everything its teardown owns. */
17
+ export interface DynamicCordisRun {
18
+ /** Exact activation identity. */
19
+ pluginRunId: CordisDynamicPluginRunId
20
+ /** Immutable package version being run. */
21
+ packageId: CordisDynamicPackageId
22
+ /** Host-half Fiber, absent for Client-only packages. */
23
+ fiber?: Fiber
24
+ /** Active Host methods. */
25
+ handlers: Map<string, DynamicCordisHandler>
26
+ /** Method registration cleanup. */
27
+ handlerDisposers: (() => void)[]
28
+ /** Runtime failures already sent to the owning Agent during this activation. */
29
+ reportedRuntimeErrors: Set<string>
30
+ /** Last render failure observed for this version's current run. */
31
+ renderFailure?: DynamicCordisRenderFailure
32
+ /** Approval whose transition started this run, when model-driven. */
33
+ startedForRequest?: ApprovalRequestId
34
+ }
35
+
36
+ /** One immutable package version. */
37
+ export interface DynamicCordisDefinition {
38
+ /** Package identity. */
39
+ packageId: CordisDynamicPackageId
40
+ /** Package label. */
41
+ name: string
42
+ /** User-facing purpose. */
43
+ purpose: string
44
+ /** Host source. */
45
+ hostCode?: string
46
+ /** Client source. */
47
+ clientCode?: string
48
+ }
49
+
50
+ /** Stable plugin instance containing immutable package versions. */
51
+ export interface DynamicCordisPlugin {
52
+ /** Stable identity. */
53
+ pluginId: CordisDynamicPluginId
54
+ /** Owning session. */
55
+ sessionId: SessionId
56
+ /** Versions in define order. */
57
+ packages: Map<CordisDynamicPackageId, DynamicCordisDefinition>
58
+ /** Client-bearing Packages individually authorized by the user. */
59
+ approvedClientPackages: Set<CordisDynamicPackageId>
60
+ /** Whether one user decision authorized future Package versions of this Plugin. */
61
+ clientVersionUpdatesApproved: boolean
62
+ /** Last successfully activated version. */
63
+ currentPackageId?: CordisDynamicPackageId
64
+ /** Failed or in-progress target version. */
65
+ nextPackageId?: CordisDynamicPackageId
66
+ /** Current activation. */
67
+ run?: DynamicCordisRun
68
+ /** Latest activation attempt, including approval and asynchronous failure state. */
69
+ latestRun?: DynamicCordisRunAttempt
70
+ }
71
+
72
+ /** One suspended model-driven activation. */
73
+ export interface DynamicCordisPendingRequest {
74
+ /** Session whose model requested this activation. */
75
+ agentId: SessionId
76
+ pluginId: CordisDynamicPluginId
77
+ packageId: CordisDynamicPackageId
78
+ pluginRunId: CordisDynamicPluginRunId
79
+ mode: CordisDynamicRunMode
80
+ /** Whether this request must wait for an explicit user decision. */
81
+ requiresApproval: boolean
82
+ }
83
+
84
+ /** Request accepted by `define`; it never crosses the Remote transport. */
85
+ export interface DynamicCordisDefineRequest {
86
+ /** Session that owns the plugin. */
87
+ sessionId: SessionId
88
+ /** Create a plugin or append to an existing one. */
89
+ plugin:
90
+ | { kind: 'new'; idPrefix: string }
91
+ | { kind: 'existing'; pluginId: CordisDynamicPluginId }
92
+ /** Package label. */
93
+ name: string
94
+ /** User-facing purpose. */
95
+ purpose: string
96
+ /** At least one source half. */
97
+ code: { host?: string; client?: string }
98
+ }
99
+
100
+ /** Successful `define` result. */
101
+ export interface DynamicCordisDefineReceipt {
102
+ pluginId: CordisDynamicPluginId
103
+ packageId: CordisDynamicPackageId
104
+ name: string
105
+ purpose: string
106
+ hasHostHalf: boolean
107
+ hasClientHalf: boolean
108
+ }
109
+
110
+ /** Source-free modification context for an explicit `@pluginId` reference. */
111
+ export interface DynamicCordisReference {
112
+ pluginId: CordisDynamicPluginId
113
+ packageId: CordisDynamicPackageId
114
+ name: string
115
+ purpose: string
116
+ currentPackageId?: CordisDynamicPackageId
117
+ nextPackageId?: CordisDynamicPackageId
118
+ activeRun?: { pluginRunId: CordisDynamicPluginRunId; packageId: CordisDynamicPackageId }
119
+ latestRun?: DynamicCordisRunAttempt
120
+ }
121
+
122
+ /** Source-free Plugin summary returned by layered self inspection. */
123
+ export interface DynamicCordisPluginInspection extends DynamicCordisReference {
124
+ /** Immutable Package summaries in define order. */
125
+ packages: Array<{
126
+ packageId: CordisDynamicPackageId
127
+ name: string
128
+ purpose: string
129
+ hasHostHalf: boolean
130
+ hasClientHalf: boolean
131
+ }>
132
+ }
133
+
134
+ /** Exact immutable Package metadata and source returned by explicit inspection. */
135
+ export interface DynamicCordisPackageInspection extends DynamicCordisReference {
136
+ /** Host and Client function bodies stored for this Package. */
137
+ code: { host?: string; client?: string }
138
+ }
139
+
140
+ /** Registry, identity mints, and pending approval index. */
141
+ export class DynamicCordisRegistry {
142
+ private readonly plugins = new Map<CordisDynamicPluginId, DynamicCordisPlugin>()
143
+ private readonly pendingRequests = new Map<ApprovalRequestId, DynamicCordisPendingRequest>()
144
+ private nextPlugin = 1
145
+ private nextPackage = 1
146
+ private nextRun = 1
147
+ private nextApproval = 1
148
+
149
+ /**
150
+ * Mint a semantic plugin ID without reusing a prior suffix.
151
+ * @param prefix - validated lowercase semantic prefix proposed by the model.
152
+ * @returns a process-unique Plugin ID.
153
+ */
154
+ mintPluginId(prefix: string): string {
155
+ let id: CordisDynamicPluginId
156
+ do id = `${prefix}-${this.nextPlugin++}` as CordisDynamicPluginId
157
+ while (this.plugins.has(id))
158
+ return id
159
+ }
160
+
161
+ /**
162
+ * Mint an immutable package ID.
163
+ * @returns a process-unique Package ID.
164
+ */
165
+ mintPackageId(): string {
166
+ return `pkg-${this.nextPackage++}`
167
+ }
168
+
169
+ /**
170
+ * Mint an activation ID.
171
+ * @returns a process-unique Plugin Run ID.
172
+ */
173
+ mintPluginRunId(): string {
174
+ return `run-${this.nextRun++}`
175
+ }
176
+
177
+ /**
178
+ * Mint an approval ID.
179
+ * @returns a process-unique approval request ID.
180
+ */
181
+ mintApprovalRequestId(): string {
182
+ return `approval-${this.nextApproval++}`
183
+ }
184
+
185
+ /**
186
+ * Add one stable plugin.
187
+ * @param plugin - Plugin record to retain under its stable ID.
188
+ */
189
+ add(plugin: DynamicCordisPlugin): void {
190
+ this.plugins.set(plugin.pluginId, plugin)
191
+ }
192
+
193
+ /**
194
+ * Read one plugin.
195
+ * @param id - stable Plugin ID.
196
+ * @returns the Plugin record, or `undefined` when absent.
197
+ */
198
+ get(id: CordisDynamicPluginId): DynamicCordisPlugin | undefined {
199
+ return this.plugins.get(id)
200
+ }
201
+
202
+ /**
203
+ * Delete one plugin and all package versions.
204
+ * @param id - stable Plugin ID to remove.
205
+ * @returns whether a Plugin record was removed.
206
+ */
207
+ delete(id: CordisDynamicPluginId): boolean {
208
+ return this.plugins.delete(id)
209
+ }
210
+
211
+ /**
212
+ * Read all plugins in creation order.
213
+ * @returns a snapshot of every Plugin record.
214
+ */
215
+ all(): DynamicCordisPlugin[] {
216
+ return [...this.plugins.values()]
217
+ }
218
+
219
+ /**
220
+ * Read one session's plugins in creation order.
221
+ * @param sessionId - owning session to filter by.
222
+ * @returns a snapshot of matching Plugin records.
223
+ */
224
+ ofSession(sessionId: SessionId): DynamicCordisPlugin[] {
225
+ return this.all().filter(plugin => plugin.sessionId === sessionId)
226
+ }
227
+
228
+ /**
229
+ * Publish one pending approval.
230
+ * @param id - approval request ID.
231
+ * @param pending - resolver and Plugin metadata retained until settlement.
232
+ */
233
+ armRequest(id: ApprovalRequestId, pending: DynamicCordisPendingRequest): void {
234
+ this.pendingRequests.set(id, pending)
235
+ }
236
+
237
+ /**
238
+ * Read one pending approval without claiming it.
239
+ * @param id - approval request ID.
240
+ * @returns the pending request, or `undefined` when absent.
241
+ */
242
+ peekRequest(id: ApprovalRequestId): DynamicCordisPendingRequest | undefined {
243
+ return this.pendingRequests.get(id)
244
+ }
245
+
246
+ /**
247
+ * Claim one pending approval; first answer wins.
248
+ * @param id - approval request ID.
249
+ * @returns the claimed request, or `undefined` when already settled.
250
+ */
251
+ claimRequest(id: ApprovalRequestId): DynamicCordisPendingRequest | undefined {
252
+ const pending = this.pendingRequests.get(id)
253
+ if (pending !== undefined) this.pendingRequests.delete(id)
254
+ return pending
255
+ }
256
+
257
+ /**
258
+ * Cancel one pending approval.
259
+ * @param id - approval request ID to remove.
260
+ */
261
+ disarmRequest(id: ApprovalRequestId): void {
262
+ this.pendingRequests.delete(id)
263
+ }
264
+
265
+ /**
266
+ * Find a pending approval for one Plugin.
267
+ * @param pluginId - stable Plugin ID.
268
+ * @returns its approval request ID, or `undefined` when none is pending.
269
+ */
270
+ pendingRequestFor(pluginId: CordisDynamicPluginId): ApprovalRequestId | undefined {
271
+ for (const [requestId, request] of this.pendingRequests) {
272
+ if (request.pluginId === pluginId) return requestId
273
+ }
274
+ return undefined
275
+ }
276
+ }