@soffits/dsh-plugin-sdk 0.0.0-stage → 0.2.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.
@@ -0,0 +1,372 @@
1
+ /**
2
+ * The DSH side of a chat: finding, creating and prompting sessions through
3
+ * the Host services the Web UI uses (`sessionController`), with the raw agent
4
+ * registry as the headless fallback, and reading what a session said.
5
+ */
6
+ import { randomUUID } from 'node:crypto'
7
+
8
+ /** @returns the Web session controller, when this deployment mounts it. */
9
+ export function controllerOf(ctx) {
10
+ const controller = ctx.get('sessionController')
11
+ return typeof controller?.create === 'function' && typeof controller?.resolveAgent === 'function' ? controller : undefined
12
+ }
13
+
14
+ /**
15
+ * The live agent of a session, resuming it when needed.
16
+ * @param ctx - Host context.
17
+ * @param sessionId - session id.
18
+ * @param resumeOptions - extra options for the agent registry's `resume`
19
+ * (`agentOptions`, `setup`), used only without a session controller.
20
+ * @returns the agent; throws when the session cannot be resumed.
21
+ */
22
+ export async function resolveAgent(ctx, sessionId, resumeOptions = {}) {
23
+ const agents = ctx.get('agents')
24
+ const live = agents?.get(sessionId)
25
+ if (live !== undefined) return live
26
+ const controller = controllerOf(ctx)
27
+ if (controller !== undefined) {
28
+ const found = await controller.resolveAgent(sessionId)
29
+ if (found?.error !== undefined) throw found.error
30
+ const agent = found?.agent ?? agents?.get(sessionId)
31
+ if (agent === undefined) throw new Error(`session ${sessionId} has no live agent`)
32
+ return agent
33
+ }
34
+ if (agents === undefined) throw new Error('dsh-agent is not mounted in this profile')
35
+ const resumed = await agents.resume({ resumeSessionId: sessionId, ...resumeOptions })
36
+ if (resumed?.agent === undefined) throw new Error(`session ${sessionId} could not be resumed`)
37
+ return resumed.agent
38
+ }
39
+
40
+ /**
41
+ * Create a session the way the Web UI composes one (preset, default model,
42
+ * model-switch notices), falling back to the agent registry.
43
+ * @param ctx - Host context.
44
+ * @param options - `{ cwd, preset, setup, agentOptions, warn }`; `setup` and
45
+ * `agentOptions` go to the registry's `create` on the fallback path only.
46
+ * @returns the new session's agent.
47
+ */
48
+ export async function createSession(ctx, { cwd, preset, setup, agentOptions, warn }) {
49
+ const controller = controllerOf(ctx)
50
+ if (controller !== undefined) {
51
+ try {
52
+ const created = await controller.create({ cwd, ...(preset ? { agentPreset: preset } : {}) })
53
+ return await resolveAgent(ctx, created.sessionId)
54
+ } catch (error) {
55
+ warn(`sessionController create failed, using the agent registry: ${error?.message ?? error}`)
56
+ }
57
+ }
58
+ const agents = ctx.get('agents')
59
+ if (agents === undefined) throw new Error('dsh-agent is not mounted in this profile')
60
+ const meta = { cwd, ...(preset && ctx.get('agentPresets') !== undefined ? { agentPreset: preset } : {}) }
61
+ const created = await agents.create({
62
+ sessionId: `session-${randomUUID()}`,
63
+ meta,
64
+ ...(agentOptions === undefined ? {} : { agentOptions }),
65
+ ...(setup === undefined ? {} : { setup }),
66
+ })
67
+ return created.agent
68
+ }
69
+
70
+ /**
71
+ * End a new session's blank state with an empty turn that never reaches a
72
+ * model. DSH hands a blank session (one that never started a turn) to the
73
+ * next New conversation in the Web UI, and only `turn/start` ends that state.
74
+ * The marker message is rejected at `agent/pre-step`, the gate DSH uses for
75
+ * archived sessions, so the turn ends as blocked and the marker is never
76
+ * recorded. Call it before the session is bound to a chat, so no mirror shows
77
+ * this turn.
78
+ * @param agent - the new session's agent.
79
+ * @param marker - `{ text, rpcPrefix }`: the marker's text and request id prefix.
80
+ * @param waitMs - longest wait for the empty turn to end.
81
+ * @returns false when this agent cannot run the empty turn.
82
+ */
83
+ export async function claimSession(agent, { text, rpcPrefix }, waitMs = 10_000) {
84
+ if (typeof agent?.followup !== 'function' || typeof agent?.ctx?.on !== 'function') return false
85
+ const id = randomUUID()
86
+ const dispose = agent.ctx.on('agent/pre-step', (payload, next) => {
87
+ const messages = Array.isArray(payload?.messages) ? payload.messages : []
88
+ if (messages.length > 0 && messages.every((message) => message?.id === id)) return Promise.resolve({ kind: 'reject' })
89
+ return next()
90
+ })
91
+ agent.followup({ id, role: 'user', content: [{ type: 'text', text }], source: { kind: 'user', rpcId: `${rpcPrefix}:${id}` } })
92
+ // The gate stays until the turn is over, so the marker can never reach a model.
93
+ const idle = typeof agent.whenIdle === 'function' ? agent.whenIdle() : Promise.resolve()
94
+ void idle.catch(() => undefined).finally(() => { if (typeof dispose === 'function') dispose() })
95
+ let timer
96
+ await Promise.race([
97
+ idle.catch(() => undefined),
98
+ new Promise((resolveWait) => { timer = setTimeout(resolveWait, waitMs) }),
99
+ ])
100
+ clearTimeout(timer)
101
+ return true
102
+ }
103
+
104
+ /**
105
+ * Attach a session to the workspace of its directory, creating the workspace
106
+ * when needed, so it shows up in the Web UI sidebar.
107
+ * @param ctx - Host context.
108
+ * @param sessionId - session id.
109
+ * @param cwd - session directory.
110
+ * @param warn - logger.
111
+ */
112
+ export async function attachToWorkspace(ctx, sessionId, cwd, warn) {
113
+ const registry = ctx.get('workspaceRegistry')
114
+ if (registry === undefined) return
115
+ try {
116
+ let workspace = registry.list().find((entry) => entry.path === cwd)
117
+ if (workspace === undefined) workspace = await registry.create(cwd)
118
+ await workspace.attachSession(sessionId)
119
+ } catch (error) {
120
+ warn(`workspace attach failed for ${sessionId}: ${error?.message ?? error}`)
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Bring an archived session back before a chat message starts a turn in it:
126
+ * DSH admits prompts into archived sessions but rejects every model step.
127
+ * @param ctx - Host context.
128
+ * @param sessionId - session id.
129
+ * @returns `unarchived`, `unsupported` (archived, and this DSH cannot bring it
130
+ * back), or undefined when the session is not archived.
131
+ */
132
+ export async function unarchive(ctx, sessionId) {
133
+ const registry = ctx.get('workspaceRegistry')
134
+ if (registry?.archivedSessionIds?.includes(sessionId) !== true) return undefined
135
+ if (typeof registry.unarchiveSession !== 'function') return 'unsupported'
136
+ await registry.unarchiveSession(sessionId)
137
+ return 'unarchived'
138
+ }
139
+
140
+ const requestMatcher = (requestId) => (message) => message?.source?.kind === 'user' && message.source.rpcId === requestId
141
+
142
+ /** @returns whether a message the agent has not taken yet carries this request id. */
143
+ export function inInbox(agent, requestId) {
144
+ const matches = requestMatcher(requestId)
145
+ const inbox = agent?.inbox
146
+ return inbox?.nextTurn?.some?.(matches) === true || inbox?.nextStep?.some?.(matches) === true
147
+ }
148
+
149
+ /** @returns whether a pending or recorded message carries this request id. */
150
+ export function hasRequest(agent, requestId) {
151
+ if (inInbox(agent, requestId)) return true
152
+ const matches = requestMatcher(requestId)
153
+ const events = typeof agent?.session?.snapshotEvents === 'function' ? agent.session.snapshotEvents() : []
154
+ return events.some((event) => event?.type === 'user/message' && matches(event.data))
155
+ }
156
+
157
+ /**
158
+ * Hand one prompt to a session. Text goes through the session controller's
159
+ * `prompt`, the Web UI's own path; prompts with stored attachments go to the
160
+ * agent's `steer` (into the running turn) or `followup` (queued), the methods
161
+ * that path calls. A request id already admitted is skipped, so a message
162
+ * handled twice (a redelivery, a restart between admission and marking it
163
+ * seen) reaches the agent once. In steer mode DSH keeps a running turn going
164
+ * while its next-step inbox holds input and opens a new turn for input left
165
+ * after `turn/end`, so a steered prompt is never dropped.
166
+ * @param ctx - Host context.
167
+ * @param agent - the session's agent.
168
+ * @param prompt - `{ requestId, text, attachments, mode, principal, envelope,
169
+ * clientTimeZone }`; `mode` is `queue` or `steer`; `principal` and
170
+ * `envelope` go on the message's source (the controller builds its own
171
+ * message, so the tagger records them at its step); `clientTimeZone` is
172
+ * DSH's field for the zone of the person behind a prompt.
173
+ * @param signal - request lifetime.
174
+ * @param tagger - a `createPrincipalTagger` that records the metadata on the
175
+ * controller's message.
176
+ * @returns `admitted`, `known` (already admitted), `empty`, or `unsupported`
177
+ * when the agent offers no way in.
178
+ */
179
+ export async function admitPrompt(ctx, agent, { requestId, text, attachments = [], mode, principal, envelope, clientTimeZone }, signal, tagger) {
180
+ if (hasRequest(agent, requestId)) return 'known'
181
+ const content = [...(text.trim().length === 0 ? [] : [{ type: 'text', text }]), ...attachments]
182
+ if (content.length === 0) return 'empty'
183
+ const zone = clientTimeZone === undefined ? {} : { clientTimeZone }
184
+ const controller = ctx.get('sessionController')
185
+ if (attachments.length === 0 && typeof controller?.prompt === 'function') {
186
+ tagger?.remember(requestId, { principal, envelope })
187
+ await controller.prompt({ sessionId: agent.session?.id ?? agent.id, requestId, mode, content, ...zone }, signal)
188
+ return 'admitted'
189
+ }
190
+ const steer = mode === 'steer'
191
+ const enter = steer ? agent?.steer : agent?.followup
192
+ if (typeof enter !== 'function' && typeof agent?.send !== 'function') return 'unsupported'
193
+ tagger?.remember(requestId, { principal, envelope })
194
+ const message = {
195
+ id: randomUUID(),
196
+ role: 'user',
197
+ content,
198
+ source: { kind: 'user', rpcId: requestId, ...zone, ...(principal === undefined ? {} : { principal }), ...(envelope === undefined ? {} : { envelope }) },
199
+ }
200
+ if (typeof enter === 'function') enter.call(agent, message)
201
+ else agent.send(message, steer ? 'next-step' : 'next-turn', true)
202
+ return 'admitted'
203
+ }
204
+
205
+ /**
206
+ * Remove prompts the agent has not taken yet, from both inboxes.
207
+ * @param agent - the session's agent.
208
+ * @param ours - test on a prompt's request id, so only the chat's own go.
209
+ * @returns how many were removed.
210
+ */
211
+ export function removePending(agent, ours) {
212
+ const inbox = agent?.inbox
213
+ if (typeof inbox?.remove !== 'function') return 0
214
+ const matches = (message) => message?.source?.kind === 'user' && typeof message.source.rpcId === 'string' && ours(message.source.rpcId)
215
+ const pending = [...(inbox.nextStep ?? []), ...(inbox.nextTurn ?? [])].filter(matches)
216
+ for (const message of pending) inbox.remove(message.id)
217
+ return pending.length
218
+ }
219
+
220
+ /**
221
+ * Whether the agent still holds input it has not taken; DSH starts another
222
+ * turn for it right after the current one ends.
223
+ */
224
+ export function hasPendingInput(agent) {
225
+ const inbox = agent?.inbox
226
+ if (inbox === undefined) return false
227
+ if (typeof inbox.hasPending === 'boolean') return inbox.hasPending
228
+ return (inbox.nextStep?.length ?? 0) > 0 || (inbox.nextTurn?.length ?? 0) > 0
229
+ }
230
+
231
+ const SURFACE_TYPES = new Set(['system/message', 'user/message', 'developer/message', 'assistant/message', 'tool/result'])
232
+
233
+ /**
234
+ * Whether a session's first surface node is its system message. DSH's log
235
+ * format rejects a log whose first system message comes after another surface
236
+ * message, so only then may a message be appended outside a step.
237
+ * @param session - DSH session.
238
+ * @returns false when the head cannot be read, so callers queue instead.
239
+ */
240
+ export function hasSystemHead(session) {
241
+ try {
242
+ const nodes = session.surface?.nodes
243
+ if (nodes !== undefined) {
244
+ if (nodes.length === 0) return false
245
+ const event = typeof session.eventAt === 'function'
246
+ ? session.eventAt(nodes[0])
247
+ : session.snapshotEvents?.().find((item) => item.seq === nodes[0])
248
+ return event?.type === 'system/message'
249
+ }
250
+ const events = typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : session.events
251
+ if (!Array.isArray(events)) return false
252
+ return events.find((event) => SURFACE_TYPES.has(event.type))?.type === 'system/message'
253
+ } catch {
254
+ return false
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Put a message into a session without starting a turn: appended now to an
260
+ * idle session whose surface starts with its system message, otherwise queued
261
+ * for its next step. Either way the Web UI shows it and the model reads it at
262
+ * its next step.
263
+ * @param agent - the session's agent.
264
+ * @param message - a user-role message (`{ id, role, content, source }`).
265
+ */
266
+ export function recordMessage(agent, message) {
267
+ if (agent.status === 'idle' && typeof agent.session?.append === 'function' && hasSystemHead(agent.session)) {
268
+ agent.session.append('user/message', message, { surfaceOp: 'append' })
269
+ } else if (typeof agent.inject === 'function') {
270
+ agent.inject(message)
271
+ } else if (typeof agent.send === 'function') {
272
+ agent.send(message, 'next-step', false)
273
+ } else {
274
+ throw new Error('The session cannot record messages.')
275
+ }
276
+ }
277
+
278
+ /**
279
+ * A session's title as DSH stores it.
280
+ * @param ctx - Host context.
281
+ * @param sessionId - session id.
282
+ * @returns the title, or undefined while the session has none.
283
+ */
284
+ export async function storedTitle(ctx, sessionId) {
285
+ try {
286
+ const snapshot = await ctx.get('sessionQuery')?.readTitleSnapshot(sessionId)
287
+ const title = snapshot?.title?.title
288
+ return typeof title === 'string' && title.trim().length > 0 ? title.trim() : undefined
289
+ } catch {
290
+ return undefined
291
+ }
292
+ }
293
+
294
+ /**
295
+ * The latest assistant texts of a session, newest first.
296
+ * @param ctx - Host context.
297
+ * @param sessionId - session id.
298
+ * @param limit - most texts.
299
+ * @returns the texts; empty when the session cannot be read.
300
+ */
301
+ export async function recentAssistantTexts(ctx, sessionId, limit) {
302
+ const texts = []
303
+ try {
304
+ const surface = await ctx.get('sessionQuery')?.readSurface(sessionId)
305
+ const events = surface?.events ?? []
306
+ for (let index = events.length - 1; index >= 0 && texts.length < limit; index -= 1) {
307
+ const event = events[index]
308
+ if (event?.type !== 'assistant/message') continue
309
+ const message = event.data?.message ?? event.data
310
+ const content = Array.isArray(message?.content) ? message.content : []
311
+ const text = content.filter((block) => block?.type === 'text').map((block) => block.text).join('\n').trim()
312
+ if (text.length > 0) texts.push(text)
313
+ }
314
+ } catch {
315
+ // An empty result is reported by the caller.
316
+ }
317
+ return texts
318
+ }
319
+
320
+ /** @returns the registered workspaces, or an empty list. */
321
+ export function listWorkspaces(ctx) {
322
+ try {
323
+ return ctx.get('workspaceRegistry')?.list() ?? []
324
+ } catch {
325
+ return []
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Recent ordinary sessions (not archived, not subagents), newest first.
331
+ * @param ctx - Host context.
332
+ * @param workspace - workspace record, or undefined for every workspace.
333
+ * @param limit - most sessions.
334
+ * @param signal - request lifetime.
335
+ */
336
+ export async function sessionsInWorkspace(ctx, workspace, limit, signal) {
337
+ const query = ctx.get('sessionQuery')
338
+ if (query === undefined) return []
339
+ const archived = new Set(ctx.get('workspaceRegistry')?.archivedSessionIds ?? [])
340
+ const records = await query.listSessions(signal)
341
+ return records
342
+ .filter((record) => !archived.has(record.header.id))
343
+ .filter((record) => record.header?.origin !== 'subagent')
344
+ .filter((record) => workspace === undefined
345
+ || (workspace.sessionIds ?? []).includes(record.header.id)
346
+ || record.header.cwd === workspace.path)
347
+ .sort((left, right) => (right.header.createdAt ?? 0) - (left.header.createdAt ?? 0))
348
+ .slice(0, limit)
349
+ }
350
+
351
+ /** Sandbox mode and approval policy behind each built-in access mode. */
352
+ const ACCESS_MODES = {
353
+ 'workspace-write': ['workspace-write', 'ask'],
354
+ 'danger-full-access': ['danger-full-access', 'never'],
355
+ 'read-only': ['read-only', 'ask'],
356
+ }
357
+
358
+ /**
359
+ * Set a session's access mode by appending its knob events, for a DSH whose
360
+ * `permissionPresets` service cannot set it from a plugin.
361
+ * @param session - DSH session.
362
+ * @param value - a built-in access mode.
363
+ * @returns false for a mode this fallback does not know.
364
+ */
365
+ export function appendAccessMode(session, value) {
366
+ const spec = ACCESS_MODES[value]
367
+ if (spec === undefined) return false
368
+ session.append('permission/preset', { preset: value })
369
+ session.append('sandbox/mode', { mode: spec[0] })
370
+ session.append('approval/policy', { policy: spec[1] })
371
+ return true
372
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * File spool for requests from outside the Host process (a bridge's command
3
+ * line, a scheduled job): a sender writes one request file, the running
4
+ * plugin handles it and writes a result file next to it. Senders need no network access to the
5
+ * Host, only write access to the DSH home, and requests wait while the bot is
6
+ * stopped.
7
+ */
8
+ import { randomUUID } from 'node:crypto'
9
+ import { watch } from 'node:fs'
10
+ import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
11
+ import { join } from 'node:path'
12
+
13
+ /** Result files older than this are removed by the plugin. */
14
+ const RESULT_TTL_MS = 24 * 60 * 60 * 1000
15
+
16
+ /**
17
+ * Write one request atomically.
18
+ * @param request - `{ op, ... }`.
19
+ * @param dir - spool directory.
20
+ * @returns the request id.
21
+ */
22
+ export async function enqueue(request, dir) {
23
+ await mkdir(dir, { recursive: true, mode: 0o700 })
24
+ const id = `${Date.now()}-${randomUUID().slice(0, 8)}`
25
+ const temporary = join(dir, `${id}.tmp`)
26
+ await writeFile(temporary, JSON.stringify({ ...request, id, createdAt: Date.now() }) + '\n', { mode: 0o600 })
27
+ await rename(temporary, join(dir, `${id}.json`))
28
+ return id
29
+ }
30
+
31
+ /**
32
+ * Wait for the plugin's result for one request.
33
+ * @param id - request id from {@link enqueue}.
34
+ * @param timeoutMs - how long to wait.
35
+ * @param dir - spool directory.
36
+ * @returns the result document, or undefined after the timeout.
37
+ */
38
+ export async function waitForResult(id, timeoutMs, dir) {
39
+ const path = join(dir, `${id}.result.json`)
40
+ const deadline = Date.now() + timeoutMs
41
+ for (;;) {
42
+ try {
43
+ const result = JSON.parse(await readFile(path, 'utf8'))
44
+ await rm(path, { force: true })
45
+ return result
46
+ } catch {
47
+ // Not written yet.
48
+ }
49
+ if (Date.now() >= deadline) return undefined
50
+ await new Promise((resolve) => setTimeout(resolve, 200))
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Remove a request that was never picked up.
56
+ * @param id - request id.
57
+ * @param dir - spool directory.
58
+ * @returns true when it was still waiting and is gone now.
59
+ */
60
+ export async function withdraw(id, dir) {
61
+ try {
62
+ await rm(join(dir, `${id}.json`))
63
+ return true
64
+ } catch {
65
+ return false
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Plugin side: handle spooled requests one at a time.
71
+ * @param options - `{ dir, handle, ready, onError, intervalMs }`: `handle`
72
+ * resolves one request to its result; `ready` says whether requests can be
73
+ * handled now.
74
+ * @returns `{ start, stop, drain }`.
75
+ */
76
+ export function createSpool({ dir, handle, ready, onError, intervalMs = 1000 }) {
77
+ let timer
78
+ let watcher
79
+ let draining
80
+ let again = false
81
+ let running = false
82
+
83
+ async function recover() {
84
+ for (const name of await readdir(dir).catch(() => [])) {
85
+ if (name.endsWith('.processing')) {
86
+ await rename(join(dir, name), join(dir, name.replace(/\.processing$/u, '.json'))).catch(() => {})
87
+ }
88
+ }
89
+ }
90
+
91
+ async function sweep(names) {
92
+ for (const name of names) {
93
+ if (!name.endsWith('.result.json') && !name.endsWith('.tmp')) continue
94
+ const path = join(dir, name)
95
+ const info = await stat(path).catch(() => undefined)
96
+ if (info !== undefined && Date.now() - info.mtimeMs > RESULT_TTL_MS) await rm(path, { force: true })
97
+ }
98
+ }
99
+
100
+ async function drainOnce() {
101
+ if (!ready()) return
102
+ const names = (await readdir(dir).catch(() => [])).sort()
103
+ await sweep(names)
104
+ for (const name of names) {
105
+ if (!name.endsWith('.json') || name.endsWith('.result.json')) continue
106
+ if (!ready()) return
107
+ const id = name.slice(0, -'.json'.length)
108
+ const claimed = join(dir, `${id}.processing`)
109
+ try {
110
+ await rename(join(dir, name), claimed)
111
+ } catch {
112
+ continue
113
+ }
114
+ let outcome
115
+ try {
116
+ const request = JSON.parse(await readFile(claimed, 'utf8'))
117
+ outcome = { ok: true, result: await handle(request) }
118
+ } catch (error) {
119
+ outcome = { ok: false, error: typeof error?.message === 'string' ? error.message : String(error) }
120
+ }
121
+ try {
122
+ // The claim goes before the result shows: a stop in between loses
123
+ // only the confirmation, never sends the request twice.
124
+ const pending = join(dir, `${id}.result.tmp`)
125
+ await writeFile(pending, JSON.stringify(outcome) + '\n', { mode: 0o600 })
126
+ await rm(claimed, { force: true })
127
+ await rename(pending, join(dir, `${id}.result.json`))
128
+ } catch (error) {
129
+ onError(error)
130
+ }
131
+ }
132
+ }
133
+
134
+ function drain() {
135
+ if (draining !== undefined) {
136
+ again = true
137
+ return draining
138
+ }
139
+ draining = (async () => {
140
+ do {
141
+ again = false
142
+ await drainOnce()
143
+ } while (again)
144
+ })().catch(onError).finally(() => { draining = undefined })
145
+ return draining
146
+ }
147
+
148
+ async function start() {
149
+ if (running) return
150
+ running = true
151
+ await mkdir(dir, { recursive: true, mode: 0o700 })
152
+ await recover()
153
+ // Stopped while getting ready.
154
+ if (!running) return
155
+ try {
156
+ watcher = watch(dir, () => { void drain() })
157
+ watcher.on('error', () => {})
158
+ } catch {
159
+ // The interval still picks requests up.
160
+ }
161
+ timer = setInterval(() => { void drain() }, intervalMs)
162
+ timer.unref?.()
163
+ void drain()
164
+ }
165
+
166
+ function stop() {
167
+ running = false
168
+ if (timer !== undefined) clearInterval(timer)
169
+ timer = undefined
170
+ watcher?.close()
171
+ watcher = undefined
172
+ }
173
+
174
+ return { start, stop, drain }
175
+ }