Open History to see the last commit
1import { ResourceScope, disposeAll } from './resources'
2import type { Logger } from '@tanstack/ai'
3import type { AnyHarness } from './define'
4import type {
5 HostPluginContext,
6 HostPluginContributions,
7 HostPluginDefinition,
8} from './plugins'
9
10/** One shared setup of a host plugin, and how to give it back. */
11export interface SharedHostPlugin {
12 contributions: HostPluginContributions<any> | void
13 /** Give the setup back. The last release disposes it. Safe to call twice. */
14 release: () => Promise<void>
15}
16
17interface Entry {
18 /** The sessions that hold the setup, and the ones that wait for it. */
19 refs: number
20 scope: ResourceScope
21 ready: Promise<HostPluginContributions<any> | void>
22}
23
24/**
25 * The context of a host plugin setup whose resources live in `scope`.
26 * `logger` is the logger of the host, safe to call.
27 */
28export function hostPluginContext(
29 harness: string,
30 scope: ResourceScope,
31 logger: Logger,
32) {
33 return {
34 harness,
35 resources: {
36 acquire: (open, close) => scope.acquire(open, close),
37 signal: scope.signal,
38 },
39 logger,
40 } satisfies HostPluginContext
41}
42
43/**
44 * @internal The plugins with `lifetime: 'host'` of one host. Each plugin
45 * object is set up once for each harness definition, and shared by a
46 * reference count. The last release disposes it, and so does `close()`.
47 *
48 * The keys are the objects, not their names. A `plugins` factory that
49 * builds a new plugin for each session (`() => [mcp({...})]`) gets a setup
50 * for each session, with its own options. To share one setup, create the
51 * plugin once, outside the factory.
52 */
53export class HostPlugins {
54 private readonly entries = new Map<
55 AnyHarness,
56 Map<HostPluginDefinition<any>, Entry>
57 >()
58 private closed = false
59
60 /** `logger` is the logger of the host, safe to call. Each setup gets it. */
61 constructor(private readonly logger: Logger) {}
62
63 /** The shared setup of `plugin` for `harness`. */
64 async acquire(
65 harness: AnyHarness,
66 plugin: HostPluginDefinition<any>,
67 ): Promise<SharedHostPlugin> {
68 if (this.closed) {
69 throw new Error('The host is closed. Create a new host to open sessions.')
70 }
71 const plugins =
72 this.entries.get(harness) ?? new Map<HostPluginDefinition<any>, Entry>()
73 this.entries.set(harness, plugins)
74 const key = plugin
75 /** Drop `entry` when it is still the one of `key`. */
76 const forget = (entry: Entry) => {
77 if (plugins.get(key) !== entry) return false
78 plugins.delete(key)
79 if (plugins.size === 0) this.entries.delete(harness)
80 return true
81 }
82 let entry = plugins.get(key)
83 if (!entry) {
84 const scope = new ResourceScope()
85 const ready = Promise.resolve().then(() =>
86 plugin.setup(hostPluginContext(harness.name, scope, this.logger)),
87 )
88 const created: Entry = { refs: 0, scope, ready }
89 // A failed setup is not kept: the next session sets it up again.
90 ready.catch(() => {
91 forget(created)
92 void scope.dispose().catch(() => {})
93 })
94 plugins.set(key, created)
95 entry = created
96 }
97 const held = entry
98 held.refs += 1
99 let contributions: HostPluginContributions<any> | void
100 try {
101 contributions = await held.ready
102 } catch (error) {
103 held.refs -= 1
104 throw error
105 }
106 let released = false
107 return {
108 contributions,
109 release: () => {
110 if (released) return Promise.resolve()
111 released = true
112 held.refs -= 1
113 if (held.refs > 0 || !forget(held)) return Promise.resolve()
114 return held.scope.dispose()
115 },
116 }
117 }
118
119 /** Dispose every shared setup. Later `acquire` calls throw. */
120 close(): Promise<void> {
121 this.closed = true
122 const scopes = [...this.entries.values()].flatMap((plugins) =>
123 [...plugins.values()].map((entry) => entry.scope),
124 )
125 this.entries.clear()
126 return disposeAll(scopes)
127 }
128}