passcontrol 1.5.0 → 1.6.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.
@@ -15,6 +15,7 @@
15
15
  import fs from "node:fs";
16
16
  import os from "node:os";
17
17
  import path from "node:path";
18
+ import { GATE_HOOK_TIMEOUT_S } from "./subscription-gate.mjs";
18
19
 
19
20
  /** Not a secret: the sidecar discards whatever arrives in this header. */
20
21
  export const CLAUDE_CODE_AUTH_PLACEHOLDER = "passcontrol-sidecar";
@@ -65,11 +66,37 @@ function save(target, value, exists) {
65
66
  return backupPath;
66
67
  }
67
68
 
69
+ /**
70
+ * `hooks` with API mode's note-only prompt hook for `port`, or without it when `port`
71
+ * is null. Every other hook, subscription mode's included, is left as it is.
72
+ */
73
+ function withNoteOnlyHook(hooks, port) {
74
+ const isNoteOnly = (h) => isObject(h) && h.type === "http" && typeof h.url === "string" && OUR_NOTE_ONLY_URL.test(h.url);
75
+ const base = isObject(hooks) ? hooks : null;
76
+ const groups = Array.isArray(base?.UserPromptSubmit) ? base.UserPromptSubmit : [];
77
+ const kept = [];
78
+ for (const group of groups) {
79
+ if (!isObject(group) || !Array.isArray(group.hooks) || !group.hooks.some(isNoteOnly)) kept.push(group);
80
+ else {
81
+ const rest = group.hooks.filter((h) => !isNoteOnly(h));
82
+ if (rest.length) kept.push({ ...group, hooks: rest });
83
+ }
84
+ }
85
+ const ours = { hooks: [{ type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?note=only`, timeout: GATE_HOOK_TIMEOUT_S }] };
86
+ if (port !== null && groups.length === kept.length + 1 && groups.some((g) => same(g, ours))) return hooks;
87
+ if (port !== null) kept.push(ours);
88
+ if (!base && !kept.length) return hooks;
89
+ const next = { ...(base ?? {}) };
90
+ if (kept.length) next.UserPromptSubmit = kept;
91
+ else delete next.UserPromptSubmit;
92
+ return next;
93
+ }
94
+
68
95
  /**
69
96
  * The env keys, and with `statusLineCommand` the status line too, in ONE save:
70
97
  * two saves would back up the first save's output and lose the user's original.
71
98
  */
72
- export function writeClaudeCodeSettings({ target, baseUrl, force = false, statusLineCommand = null }) {
99
+ export function writeClaudeCodeSettings({ target, baseUrl, force = false, statusLineCommand = null, noteHookPort = null }) {
73
100
  const { exists, value } = readSettings(target);
74
101
  const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : {};
75
102
  const rawKeyFound = typeof env.ANTHROPIC_API_KEY === "string" && env.ANTHROPIC_API_KEY.length > 0;
@@ -87,7 +114,14 @@ export function writeClaudeCodeSettings({ target, baseUrl, force = false, status
87
114
  next = line.value;
88
115
  statusLine = line.existing !== undefined ? { changed: false, existing: line.existing } : { changed: line.changed };
89
116
  }
90
- const changed = !envDone || Boolean(statusLine?.changed);
117
+ const hooks = withNoteOnlyHook(value.hooks, noteHookPort);
118
+ const hooksChanged = !same(hooks ?? null, value.hooks ?? null);
119
+ if (hooksChanged) {
120
+ next = { ...next };
121
+ if (hooks && Object.keys(hooks).length) next.hooks = hooks;
122
+ else delete next.hooks;
123
+ }
124
+ const changed = !envDone || Boolean(statusLine?.changed) || hooksChanged;
91
125
  const backupPath = changed ? save(target, next, exists) : null;
92
126
  return { changed, backupPath, rawKeyFound, ...(statusLine ? { statusLine } : {}) };
93
127
  }
@@ -110,6 +144,14 @@ export function removeClaudeCodeSettings({ target }) {
110
144
  const { statusLine: _ours, ...rest } = next;
111
145
  next = rest;
112
146
  }
147
+ if (isObject(next.hooks)) {
148
+ const hooks = withNoteOnlyHook(next.hooks, null);
149
+ if (!same(hooks, next.hooks)) {
150
+ next = { ...next };
151
+ if (Object.keys(hooks).length) next.hooks = hooks;
152
+ else delete next.hooks;
153
+ }
154
+ }
113
155
  if (next === value) return { changed: false };
114
156
  save(target, next, true);
115
157
  return { changed: true };
@@ -158,3 +200,185 @@ export function removeClaudeCodeStatusLine({ target }) {
158
200
  save(target, rest, true);
159
201
  return { changed: true };
160
202
  }
203
+
204
+ // ── Subscription mode ─────────────────────────────────────────────────────────
205
+ //
206
+ // A Pro/Max login talks to Anthropic directly, and Anthropic's terms forbid
207
+ // intermediating it, so nothing here touches ANTHROPIC_BASE_URL. Instead Claude
208
+ // Code is told to report to the sidecar and to ask it before acting:
209
+ // * its OpenTelemetry LOG export (http/json) goes to the sidecar's receiver
210
+ // (cli/otlp-logs.mjs). Only the logs-specific variables are written, so a
211
+ // metrics or traces export the user runs is left alone;
212
+ // * three http hooks go to the sidecar's stop gate (cli/subscription-gate.mjs),
213
+ // each with a 5 s timeout: a hook that cannot connect or times out lets the
214
+ // action go ahead, which is the fail-open the owner chose;
215
+ // * the status line carries the usage window (cli/usage-window.mjs);
216
+ // * PASSCONTROL_SIDECAR_URL tells `/passcontrol` which sidecar to ask.
217
+ // Only the user settings: Claude Code ignores telemetry settings in a project's file.
218
+
219
+ const LOOPBACK_BASE = "http://127.0.0.1:";
220
+ const OUR_LOGS_ENDPOINT = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/otlp\/v1\/logs$/;
221
+ const OUR_HOOK_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook(\?(t=\d{1,4}|note=1))?$/;
222
+ // API mode's own prompt hook, for the agent's note only (1.6.0): never a stop.
223
+ const OUR_NOTE_ONLY_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook\?note=only$/;
224
+ const OUR_SIDECAR_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}$/;
225
+ const GATED_EVENTS = ["UserPromptSubmit", "PreToolUse", "PostToolBatch"];
226
+ // The log-export settings this mode owns, with the value it writes.
227
+ const LOGS_ENV = {
228
+ OTEL_LOGS_EXPORTER: "otlp",
229
+ OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: "http/json",
230
+ // The 5 s default would make the board's rows lag the session.
231
+ OTEL_LOGS_EXPORT_INTERVAL: "1000",
232
+ };
233
+
234
+ export function subscriptionEnv(port) {
235
+ return {
236
+ CLAUDE_CODE_ENABLE_TELEMETRY: "1",
237
+ ...LOGS_ENV,
238
+ OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: `${LOOPBACK_BASE}${port}/_passcontrol/otlp/v1/logs`,
239
+ PASSCONTROL_SIDECAR_URL: `${LOOPBACK_BASE}${port}`,
240
+ };
241
+ }
242
+
243
+ function gateHook(port, note = false) {
244
+ return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook${note ? "?note=1" : ""}`, timeout: GATE_HOOK_TIMEOUT_S };
245
+ }
246
+
247
+ // PreToolUse may hold a tool while the owner is asked (Phase 2), and Claude Code lets
248
+ // a tool RUN when its http hook times out. So this one gets Claude Code's own 600 s
249
+ // default, and says so in its URL: the sidecar always answers inside the time it is
250
+ // told, and a Phase 1 hook (no `t`, 5 s) refuses a tool that would need the owner
251
+ // instead of letting it through on the timeout.
252
+ export const TOOL_HOOK_TIMEOUT_S = 600;
253
+ function toolHook(port) {
254
+ return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?t=${TOOL_HOOK_TIMEOUT_S}`, timeout: TOOL_HOOK_TIMEOUT_S };
255
+ }
256
+
257
+ /** `note`: the agent's opt-in note rides on the prompt hook (`--agent-note`). */
258
+ export function subscriptionHooks(port, { note = false } = {}) {
259
+ const hook = gateHook(port);
260
+ return {
261
+ UserPromptSubmit: [{ hooks: [gateHook(port, note)] }],
262
+ PreToolUse: [{ matcher: "*", hooks: [toolHook(port)] }],
263
+ PostToolBatch: [{ hooks: [hook] }],
264
+ };
265
+ }
266
+
267
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
268
+ const isOurHook = (h) => isObject(h) && h.type === "http" && typeof h.url === "string" && OUR_HOOK_URL.test(h.url);
269
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
270
+
271
+ /** `hooks` with every hook this mode wrote taken out, and groups left empty dropped. */
272
+ function withoutOurHooks(hooks) {
273
+ if (!isObject(hooks)) return hooks;
274
+ const next = {};
275
+ for (const [event, groups] of Object.entries(hooks)) {
276
+ if (!Array.isArray(groups)) {
277
+ next[event] = groups;
278
+ continue;
279
+ }
280
+ const kept = [];
281
+ for (const group of groups) {
282
+ if (!isObject(group) || !Array.isArray(group.hooks) || !group.hooks.some(isOurHook)) {
283
+ kept.push(group);
284
+ continue;
285
+ }
286
+ const rest = group.hooks.filter((h) => !isOurHook(h));
287
+ if (rest.length) kept.push({ ...group, hooks: rest });
288
+ }
289
+ if (kept.length) next[event] = kept;
290
+ }
291
+ return next;
292
+ }
293
+
294
+ /** `hooks` with exactly this port's gate hooks, leaving them where they are when already right. */
295
+ function withOurHooks(hooks, port, note = false) {
296
+ const ours = subscriptionHooks(port, { note });
297
+ const base = isObject(hooks) ? hooks : {};
298
+ const next = withoutOurHooks(base);
299
+ for (const event of GATED_EVENTS) {
300
+ const current = Array.isArray(base[event]) ? base[event] : [];
301
+ const already = current.filter((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isOurHook));
302
+ if (already.length === 1 && same(already[0], ours[event][0])) next[event] = current;
303
+ else next[event] = [...(next[event] ?? []), ...ours[event]];
304
+ }
305
+ return next;
306
+ }
307
+
308
+ // `allowedHttpHookUrls`, when set at any level, runs only the http hooks it matches.
309
+ function urlAllowed(patterns, url) {
310
+ return patterns.some((p) => {
311
+ if (typeof p !== "string") return false;
312
+ const re = new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
313
+ return re.test(url);
314
+ });
315
+ }
316
+
317
+ /**
318
+ * Subscription mode's settings, in one save. Throws, writing nothing, when the
319
+ * user already exports Claude Code's logs somewhere else and `force` is not set.
320
+ */
321
+ export function writeClaudeCodeSubscription({ target, port, statusLineCommand, force = false, note = false }) {
322
+ const { exists, value } = readSettings(target);
323
+ const env = isObject(value.env) ? value.env : {};
324
+ const endpoint = env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
325
+ const ourEndpoint = typeof endpoint === "string" && OUR_LOGS_ENDPOINT.test(endpoint);
326
+ const theirs = [];
327
+ if (endpoint !== undefined && !ourEndpoint) theirs.push("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT");
328
+ if (env.OTEL_LOGS_EXPORTER !== undefined && !ourEndpoint) theirs.push("OTEL_LOGS_EXPORTER");
329
+ if (theirs.length && !force) {
330
+ throw new Error(
331
+ `${target} already exports Claude Code's logs (${theirs.join(", ")}). Subscription mode would send them to the sidecar instead. Re-run with --force to do that; nothing was written.`
332
+ );
333
+ }
334
+ let next = { ...value, env: { ...env, ...subscriptionEnv(port) }, hooks: withOurHooks(value.hooks, port, note) };
335
+ let statusLine;
336
+ if (statusLineCommand) {
337
+ const line = withStatusLine(next, statusLineCommand);
338
+ next = line.value;
339
+ statusLine = line.existing !== undefined ? { changed: false, existing: line.existing } : { changed: line.changed };
340
+ }
341
+ const changed = !same(next, value);
342
+ const backupPath = changed ? save(target, next, exists) : null;
343
+ const allowlist = Array.isArray(value.allowedHttpHookUrls) ? value.allowedHttpHookUrls : null;
344
+ return {
345
+ changed,
346
+ backupPath,
347
+ ...(statusLine ? { statusLine } : {}),
348
+ hookUrlsBlocked: Boolean(allowlist && [gateHook(port), gateHook(port, note), toolHook(port)].some((h) => !urlAllowed(allowlist, h.url))),
349
+ routed: env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER && typeof env.ANTHROPIC_BASE_URL === "string",
350
+ };
351
+ }
352
+
353
+ /**
354
+ * Takes out what `writeClaudeCodeSubscription` wrote: its hooks, its status line, its
355
+ * sidecar address, and the logs export only when it points at a sidecar. The
356
+ * telemetry switch stays while any other OTEL_ setting still needs it.
357
+ */
358
+ export function removeClaudeCodeSubscription({ target }) {
359
+ if (!fs.existsSync(target)) return { changed: false };
360
+ const { value } = readSettings(target);
361
+ let next = { ...value };
362
+ if (isObject(value.env)) {
363
+ const env = { ...value.env };
364
+ if (typeof env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT === "string" && OUR_LOGS_ENDPOINT.test(env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)) {
365
+ delete env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
366
+ for (const [key, ours] of Object.entries(LOGS_ENV)) if (env[key] === ours) delete env[key];
367
+ if (env.CLAUDE_CODE_ENABLE_TELEMETRY === "1" && !Object.keys(env).some((k) => k.startsWith("OTEL_"))) {
368
+ delete env.CLAUDE_CODE_ENABLE_TELEMETRY;
369
+ }
370
+ }
371
+ if (typeof env.PASSCONTROL_SIDECAR_URL === "string" && OUR_SIDECAR_URL.test(env.PASSCONTROL_SIDECAR_URL)) delete env.PASSCONTROL_SIDECAR_URL;
372
+ if (Object.keys(env).length) next.env = env;
373
+ else delete next.env;
374
+ }
375
+ if (isObject(value.hooks)) {
376
+ const hooks = withoutOurHooks(value.hooks);
377
+ if (Object.keys(hooks).length) next.hooks = hooks;
378
+ else delete next.hooks;
379
+ }
380
+ if (isOurStatusLine(next.statusLine)) delete next.statusLine;
381
+ if (same(next, value)) return { changed: false };
382
+ save(target, next, true);
383
+ return { changed: true };
384
+ }
@@ -0,0 +1,212 @@
1
+ // Subscription mode, Phase 1b: the model calls Claude Code REPORTS to the sidecar
2
+ // (cli/otlp-logs.mjs) are uploaded to the gateway's POST /api/v1/client-events, so
3
+ // they reach the agent's dashboard page and not only this machine's `watch`.
4
+ //
5
+ // The OTLP answer never waits for this: `add` only queues, and a timer flushes in
6
+ // batches. Each event gets its key once, when it is queued, and every retry sends the
7
+ // same key, so the gateway (0084, unique per agent and key) stores it once however
8
+ // often it is sent. The queue is bounded and drops the oldest.
9
+ //
10
+ // What each answer means:
11
+ // 200 sent; the gateway counted what it took
12
+ // 403 the agent is stopped: what it reports is not recorded, so drop
13
+ // 400, 413 the batch will never be accepted as it is, so drop it
14
+ // 503 `client_events_unavailable`: the gateway's database predates 0084
15
+ // 404, 405 the gateway predates the endpoint (npm, the Cloud deploy and
16
+ // `passcontrol update` ship at different times)
17
+ // → for both: drop everything and stop for a while
18
+ // 429 wait as long as the gateway asks
19
+ // anything else, or no answer: keep the events, back off, retry, and give a batch
20
+ // up after `maxAttempts`, so one that always fails cannot pin the queue
21
+ //
22
+ // Phase 2 queues the tool rules' decisions here too (cli/tool-gate.mjs): the tool's
23
+ // name and the decision, never the command, path or URL it was about.
24
+ //
25
+ // Only the fields the gateway stores are sent. The reported cost is what the call
26
+ // would have cost on the API, never money spent: the gateway keeps it apart from
27
+ // every budget.
28
+
29
+ import { randomBytes } from "node:crypto";
30
+
31
+ export const CLIENT_EVENTS_PATH = "/api/v1/client-events";
32
+ export const CLIENT_EVENTS_SOURCE = "claude_code_otel";
33
+
34
+ const UNAVAILABLE_PAUSE_MS = 10 * 60_000;
35
+ const BACKOFF_FIRST_MS = 2_000;
36
+ const BACKOFF_MAX_MS = 60_000;
37
+
38
+ const newKey = () => `evt_${randomBytes(16).toString("base64url")}`;
39
+
40
+ /** One event from readClaudeCodeEvents, as the gateway takes it. Absent fields are left out. */
41
+ function toWire(event, key) {
42
+ if (event.kind === "tool_decision") return toolDecisionWire(event, key);
43
+ const wire = {
44
+ key,
45
+ kind: event.kind === "api_error" ? "model_error" : "model_call",
46
+ session: event.session,
47
+ agent: event.agent,
48
+ at: event.at,
49
+ model: event.model,
50
+ cost_usd_micros: event.kind === "api_error" ? null : event.costMicros,
51
+ input_tokens: event.inputTokens,
52
+ output_tokens: event.outputTokens,
53
+ cache_read_tokens: event.cacheReadTokens,
54
+ cache_creation_tokens: event.cacheCreationTokens,
55
+ duration_ms: event.durationMs,
56
+ status: event.kind === "api_error" ? event.status : null,
57
+ };
58
+ for (const name of Object.keys(wire)) if (wire[name] === null || wire[name] === undefined) delete wire[name];
59
+ return wire;
60
+ }
61
+
62
+ function toolDecisionWire(event, key) {
63
+ const wire = {
64
+ key,
65
+ kind: "tool_decision",
66
+ session: event.session,
67
+ agent: event.agent,
68
+ at: event.at,
69
+ tool: event.tool,
70
+ decision: event.decision,
71
+ rule_index: event.ruleIndex,
72
+ duration_ms: event.waitMs,
73
+ };
74
+ for (const name of Object.keys(wire)) if (wire[name] === null || wire[name] === undefined) delete wire[name];
75
+ return wire;
76
+ }
77
+
78
+ /**
79
+ * @param {{
80
+ * send: (events: object[]) => Promise<{ status: number, error?: string, retryAfterS?: number }>,
81
+ * now?: () => number,
82
+ * setTimer?: (fn: () => unknown, ms: number) => unknown,
83
+ * clearTimer?: (timer: unknown) => void,
84
+ * maxQueue?: number,
85
+ * batchSize?: number,
86
+ * flushMs?: number,
87
+ * maxAttempts?: number,
88
+ * }} options
89
+ */
90
+ export function createCallUploader({
91
+ send,
92
+ now = () => Date.now(),
93
+ setTimer = (fn, ms) => {
94
+ const timer = setTimeout(fn, ms);
95
+ timer.unref?.();
96
+ return timer;
97
+ },
98
+ clearTimer = (timer) => clearTimeout(timer),
99
+ maxQueue = 1_000,
100
+ batchSize = 50,
101
+ // Every 10 s: the gateway allows 30 uploads a minute per agent, and two sidecars on
102
+ // one agent should still fit.
103
+ flushMs = 10_000,
104
+ maxAttempts = 8,
105
+ }) {
106
+ let queue = [];
107
+ let sent = 0;
108
+ let dropped = 0;
109
+ let timer = null;
110
+ let inflight = null;
111
+ let waitUntil = 0;
112
+ let unavailableUntil = 0;
113
+ let backoffMs = 0;
114
+ let closed = false;
115
+ // Failed sends per queued event (transient failures only).
116
+ const attempts = new WeakMap();
117
+
118
+ function schedule(delayMs) {
119
+ if (closed || queue.length === 0) return;
120
+ if (timer) clearTimer(timer);
121
+ const ms = Math.max(delayMs, waitUntil - now(), 0);
122
+ timer = setTimer(() => {
123
+ timer = null;
124
+ return flush();
125
+ }, ms);
126
+ }
127
+
128
+ function add(event) {
129
+ if (closed) return;
130
+ if (unavailableUntil > now()) {
131
+ dropped += 1;
132
+ return;
133
+ }
134
+ queue.push(toWire(event, newKey()));
135
+ if (queue.length > maxQueue) {
136
+ queue.shift();
137
+ dropped += 1;
138
+ }
139
+ if (inflight) return;
140
+ if (queue.length >= batchSize) schedule(0);
141
+ else if (!timer) schedule(flushMs);
142
+ }
143
+
144
+ async function flushOnce() {
145
+ const batch = queue.slice(0, batchSize);
146
+ if (batch.length === 0) return;
147
+ let answer;
148
+ try {
149
+ answer = await send(batch);
150
+ } catch {
151
+ answer = { status: 0 };
152
+ }
153
+ const taken = new Set(batch);
154
+ const status = answer?.status ?? 0;
155
+ if (status === 200) {
156
+ queue = queue.filter((e) => !taken.has(e));
157
+ sent += batch.length;
158
+ backoffMs = 0;
159
+ return;
160
+ }
161
+ if ((status === 503 && answer.error === "client_events_unavailable") || status === 404 || status === 405) {
162
+ dropped += queue.length;
163
+ queue = [];
164
+ unavailableUntil = now() + UNAVAILABLE_PAUSE_MS;
165
+ return;
166
+ }
167
+ if (status === 403 || status === 400 || status === 413) {
168
+ queue = queue.filter((e) => !taken.has(e));
169
+ dropped += batch.length;
170
+ return;
171
+ }
172
+ if (status === 429) {
173
+ const seconds = Number(answer.retryAfterS);
174
+ waitUntil = now() + (Number.isFinite(seconds) && seconds > 0 ? seconds * 1_000 : BACKOFF_MAX_MS);
175
+ return;
176
+ }
177
+ for (const e of batch) attempts.set(e, (attempts.get(e) ?? 0) + 1);
178
+ const spent = batch.filter((e) => attempts.get(e) >= maxAttempts);
179
+ if (spent.length > 0) {
180
+ const gone = new Set(spent);
181
+ queue = queue.filter((e) => !gone.has(e));
182
+ dropped += spent.length;
183
+ }
184
+ backoffMs = backoffMs ? Math.min(backoffMs * 2, BACKOFF_MAX_MS) : BACKOFF_FIRST_MS;
185
+ waitUntil = now() + backoffMs;
186
+ }
187
+
188
+ /** Sends one batch now (one at a time), then schedules whatever is left. */
189
+ function flush() {
190
+ if (inflight) return inflight;
191
+ inflight = (async () => {
192
+ try {
193
+ await flushOnce();
194
+ } finally {
195
+ inflight = null;
196
+ if (queue.length >= batchSize && waitUntil <= now()) schedule(0);
197
+ else schedule(flushMs);
198
+ }
199
+ })();
200
+ return inflight;
201
+ }
202
+
203
+ function close() {
204
+ closed = true;
205
+ if (timer) clearTimer(timer);
206
+ timer = null;
207
+ }
208
+
209
+ const stats = () => ({ queued: queue.length, sent, dropped });
210
+
211
+ return { add, flush, close, stats };
212
+ }