@agent-city/engine 0.0.0-stage → 0.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 (81) hide show
  1. package/LICENSE +21 -0
  2. package/dist/audit.d.ts +54 -0
  3. package/dist/audit.js +291 -0
  4. package/dist/audit.js.map +1 -0
  5. package/dist/budget.d.ts +24 -0
  6. package/dist/budget.js +65 -0
  7. package/dist/budget.js.map +1 -0
  8. package/dist/index.d.ts +17 -0
  9. package/dist/index.js +18 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/integrations/card.d.ts +19 -0
  12. package/dist/integrations/card.js +99 -0
  13. package/dist/integrations/card.js.map +1 -0
  14. package/dist/integrations/config.d.ts +13 -0
  15. package/dist/integrations/config.js +74 -0
  16. package/dist/integrations/config.js.map +1 -0
  17. package/dist/integrations/index.d.ts +29 -0
  18. package/dist/integrations/index.js +181 -0
  19. package/dist/integrations/index.js.map +1 -0
  20. package/dist/lan.d.ts +24 -0
  21. package/dist/lan.js +103 -0
  22. package/dist/lan.js.map +1 -0
  23. package/dist/learning.d.ts +73 -0
  24. package/dist/learning.js +261 -0
  25. package/dist/learning.js.map +1 -0
  26. package/dist/lessons.d.ts +17 -0
  27. package/dist/lessons.js +87 -0
  28. package/dist/lessons.js.map +1 -0
  29. package/dist/loops.d.ts +16 -0
  30. package/dist/loops.js +75 -0
  31. package/dist/loops.js.map +1 -0
  32. package/dist/mobile-page.d.ts +6 -0
  33. package/dist/mobile-page.js +146 -0
  34. package/dist/mobile-page.js.map +1 -0
  35. package/dist/mobile.d.ts +40 -0
  36. package/dist/mobile.js +67 -0
  37. package/dist/mobile.js.map +1 -0
  38. package/dist/packs.d.ts +47 -0
  39. package/dist/packs.js +103 -0
  40. package/dist/packs.js.map +1 -0
  41. package/dist/paths.d.ts +2 -0
  42. package/dist/paths.js +7 -0
  43. package/dist/paths.js.map +1 -0
  44. package/dist/policies.d.ts +21 -0
  45. package/dist/policies.js +126 -0
  46. package/dist/policies.js.map +1 -0
  47. package/dist/search.d.ts +8 -0
  48. package/dist/search.js +46 -0
  49. package/dist/search.js.map +1 -0
  50. package/dist/server.d.ts +47 -0
  51. package/dist/server.js +921 -0
  52. package/dist/server.js.map +1 -0
  53. package/dist/slack.d.ts +62 -0
  54. package/dist/slack.js +214 -0
  55. package/dist/slack.js.map +1 -0
  56. package/dist/snapshots.d.ts +39 -0
  57. package/dist/snapshots.js +265 -0
  58. package/dist/snapshots.js.map +1 -0
  59. package/dist/sqlite.d.ts +17 -0
  60. package/dist/sqlite.js +57 -0
  61. package/dist/sqlite.js.map +1 -0
  62. package/dist/store.d.ts +22 -0
  63. package/dist/store.js +114 -0
  64. package/dist/store.js.map +1 -0
  65. package/dist/sync.d.ts +38 -0
  66. package/dist/sync.js +173 -0
  67. package/dist/sync.js.map +1 -0
  68. package/dist/team.d.ts +62 -0
  69. package/dist/team.js +245 -0
  70. package/dist/team.js.map +1 -0
  71. package/dist/timetravel.d.ts +37 -0
  72. package/dist/timetravel.js +178 -0
  73. package/dist/timetravel.js.map +1 -0
  74. package/dist/usage.d.ts +28 -0
  75. package/dist/usage.js +114 -0
  76. package/dist/usage.js.map +1 -0
  77. package/dist/verify.d.ts +41 -0
  78. package/dist/verify.js +73 -0
  79. package/dist/verify.js.map +1 -0
  80. package/package.json +43 -3
  81. package/README.md +0 -3
package/dist/server.js ADDED
@@ -0,0 +1,921 @@
1
+ import fs from 'node:fs';
2
+ import http from 'node:http';
3
+ import path from 'node:path';
4
+ import { WebSocketServer, WebSocket } from 'ws';
5
+ import { APPROVAL_TIMEOUT_MS, DEFAULT_HOST, PROTOCOL_VERSION, DEFAULT_PORT, SPEC_VERSION, createEvent, newId, parseEvent, redactDeep, } from '@agent-city/spec';
6
+ import { agentcityHome } from './paths.js';
7
+ import { createPolicyEngine, isPolicyArray, loadPolicies, savePolicies } from './policies.js';
8
+ import { loadPacks } from './packs.js';
9
+ import { createStore } from './store.js';
10
+ import { createSnapshotter } from './snapshots.js';
11
+ import { createTimeTravelRoutes } from './timetravel.js';
12
+ import { auditRoute, createAuditLog } from './audit.js';
13
+ import { createLessonRoutes } from './lessons.js';
14
+ import { sealEvidence, verifyFromEvents } from './verify.js';
15
+ import { ARCHIVED, createLearner } from './learning.js';
16
+ import { createUsageReader, safeTranscriptPath } from './usage.js';
17
+ import { createLoopGuard } from './loops.js';
18
+ import { budgetDenial, createBudgetMeter, readBudgetConfig } from './budget.js';
19
+ import { createIntegrations } from './integrations/index.js';
20
+ import { startMobileApprovals } from './mobile.js';
21
+ import { startSlackApprovals, validateSlackOptions } from './slack.js';
22
+ import { startSync } from './sync.js';
23
+ import { followPeer, startTeamShare } from './team.js';
24
+ export const ENGINE_VERSION = '0.1.0';
25
+ const MAX_BODY = 5 * 1024 * 1024;
26
+ const RECENT = 200;
27
+ const MAX_PEER_SESSIONS = 200;
28
+ const MAX_PEER_AGENTS = 50;
29
+ const MAX_PEER_HANDLES = 100;
30
+ const MAX_PEER_SESSIONS_TOTAL = 1_000;
31
+ class HttpError extends Error {
32
+ status;
33
+ constructor(status, message) {
34
+ super(message);
35
+ this.status = status;
36
+ }
37
+ }
38
+ export const LOCK_FILE = 'engine.lock';
39
+ /** Another live engine already owns this home directory. */
40
+ export class EngineLockedError extends Error {
41
+ pid;
42
+ lockPort;
43
+ home;
44
+ code = 'ENGINE_LOCKED';
45
+ constructor(pid, lockPort, home) {
46
+ super(`otro engine ya usa este directorio (pid ${pid}, puerto ${lockPort ?? '?'}): ${home}`);
47
+ this.pid = pid;
48
+ this.lockPort = lockPort;
49
+ this.home = home;
50
+ }
51
+ }
52
+ const pidAlive = (pid) => {
53
+ if (!Number.isInteger(pid) || pid <= 0)
54
+ return false;
55
+ try {
56
+ process.kill(pid, 0);
57
+ return true;
58
+ }
59
+ catch (e) {
60
+ return e.code === 'EPERM'; // exists but not ours
61
+ }
62
+ };
63
+ /** Creates ~/.agentcity/engine.lock with 'wx'; replaces it if its pid is dead. Returns an updater and a releaser. */
64
+ function acquireLock(home, port) {
65
+ const file = path.join(home, LOCK_FILE);
66
+ fs.mkdirSync(home, { recursive: true });
67
+ const body = (p) => JSON.stringify({ pid: process.pid, port: p, startedAt: new Date().toISOString() });
68
+ for (let attempt = 0;; attempt++) {
69
+ try {
70
+ fs.writeFileSync(file, body(port), { flag: 'wx' });
71
+ break;
72
+ }
73
+ catch (e) {
74
+ if (e.code !== 'EEXIST' || attempt > 2)
75
+ throw e;
76
+ let cur = {};
77
+ try {
78
+ cur = JSON.parse(fs.readFileSync(file, 'utf8'));
79
+ }
80
+ catch {
81
+ // unreadable lock: treat as stale
82
+ }
83
+ if (typeof cur.pid === 'number' && cur.pid !== process.pid && pidAlive(cur.pid))
84
+ throw new EngineLockedError(cur.pid, cur.port, home);
85
+ if (cur.pid === process.pid)
86
+ throw new EngineLockedError(cur.pid, cur.port, home);
87
+ try {
88
+ fs.unlinkSync(file); // stale lock
89
+ }
90
+ catch {
91
+ // raced with another remover
92
+ }
93
+ }
94
+ }
95
+ let released = false;
96
+ return {
97
+ setPort(p) {
98
+ try {
99
+ fs.writeFileSync(file, body(p));
100
+ }
101
+ catch {
102
+ // best effort
103
+ }
104
+ },
105
+ release() {
106
+ if (released)
107
+ return;
108
+ released = true;
109
+ try {
110
+ const cur = JSON.parse(fs.readFileSync(file, 'utf8'));
111
+ if (cur.pid === process.pid)
112
+ fs.unlinkSync(file);
113
+ }
114
+ catch {
115
+ // already gone
116
+ }
117
+ },
118
+ };
119
+ }
120
+ const LOCAL_HOSTS = ['localhost', '127.0.0.1', '[::1]'];
121
+ const DEV_ORIGINS = ['http://localhost:3000', 'http://127.0.0.1:3000'];
122
+ /** Origins allowed for CORS/WS: the engine's own port, AGENTCITY_ALLOWED_ORIGINS and, outside production, Next dev. */
123
+ function allowedOrigins(port) {
124
+ const set = new Set();
125
+ for (const h of LOCAL_HOSTS)
126
+ for (const proto of ['http', 'https'])
127
+ set.add(`${proto}://${h}:${port}`);
128
+ if (process.env.NODE_ENV !== 'production')
129
+ for (const o of DEV_ORIGINS)
130
+ set.add(o);
131
+ for (const o of (process.env.AGENTCITY_ALLOWED_ORIGINS ?? '').split(',')) {
132
+ const t = o.trim().replace(/\/+$/, '').toLowerCase();
133
+ if (t)
134
+ set.add(t);
135
+ }
136
+ return set;
137
+ }
138
+ const escapeRe = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
139
+ const MIN_LABEL_MATCH = 8;
140
+ const MIME = {
141
+ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
142
+ '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml',
143
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp',
144
+ '.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8',
145
+ '.glb': 'model/gltf-binary', '.wasm': 'application/wasm', '.map': 'application/json',
146
+ };
147
+ const CLIENT_GONE = 'client disconnected';
148
+ const EXPLICIT_REASON = 'the agent explicitly requested human approval';
149
+ export async function startEngine(opts = {}) {
150
+ const home = agentcityHome(opts.home);
151
+ const timeoutMs = opts.approvalTimeoutMs ?? APPROVAL_TIMEOUT_MS;
152
+ const port = opts.port ?? (Number(process.env.AGENTCITY_PORT) || DEFAULT_PORT);
153
+ const lock = acquireLock(home, port);
154
+ try {
155
+ return await startLocked(opts, home, timeoutMs, port, lock);
156
+ }
157
+ catch (err) {
158
+ lock.release();
159
+ throw err;
160
+ }
161
+ }
162
+ async function startLocked(opts, home, timeoutMs, port, lock) {
163
+ const store = createStore(home, { forceMemory: opts.forceMemoryStore });
164
+ const snapshots = createSnapshotter(home, { forceMemory: opts.forceMemoryStore });
165
+ const audit = createAuditLog(home, () => store.allEvents()); // append-only, hash-chained (~/.agentcity/audit.jsonl)
166
+ const policies = createPolicyEngine(loadPolicies(home));
167
+ // Marketplace packs can only tighten. The user's policies decide first, except a catch-all `allow` (no action,
168
+ // category or target, like the default `default-allow`): that one is "no opinion", so packs get their say before it.
169
+ let packs = loadPacks(home);
170
+ const packPolicies = createPolicyEngine(packs.policies);
171
+ const isCatchAllAllow = (id) => {
172
+ const p = id ? policies.list().find((x) => x.id === id) : undefined;
173
+ return !!p && p.decision === 'allow' && !p.action && !p.category && !p.target;
174
+ };
175
+ const evaluatePolicies = (ev) => {
176
+ const own = policies.evaluate(ev);
177
+ if (own.policyId && !isCatchAllAllow(own.policyId))
178
+ return own;
179
+ const fromPack = packPolicies.evaluate(ev);
180
+ return fromPack.policyId ? fromPack : own;
181
+ };
182
+ let boundPort = 0;
183
+ const integrations = createIntegrations({ home, port: () => boundPort, sessionEvents: (id) => store.sessionEvents(id) }, opts.integrations);
184
+ const health = { ok: true, name: 'agentcity-engine', version: ENGINE_VERSION, specVersion: SPEC_VERSION, protocolVersion: PROTOCOL_VERSION };
185
+ const sessions = new Map(store.sessions().map((s) => [s.id, { ...s, paused: false }]));
186
+ const recent = store.recent(RECENT);
187
+ // Team city: teammates' sessions and events live only in memory (never stored, audited or policy-checked).
188
+ let teamShare;
189
+ let slack;
190
+ let sync;
191
+ const followers = [];
192
+ const peerSessions = new Map();
193
+ const peerRecent = [];
194
+ const pending = new Map();
195
+ const paused = new Set();
196
+ const pauseWaiters = new Map();
197
+ const pruned = new Map();
198
+ const clients = new Set();
199
+ let origins = new Set();
200
+ const originOk = (o) => !o || origins.has(o.toLowerCase());
201
+ const broadcast = (msg) => {
202
+ const data = JSON.stringify(msg);
203
+ for (const c of clients)
204
+ if (c.readyState === WebSocket.OPEN)
205
+ c.send(data);
206
+ };
207
+ const publishSession = (s) => {
208
+ s.paused = paused.has(s.id);
209
+ store.upsertSession(s);
210
+ broadcast({ type: 'session.update', session: { ...s, agents: [...s.agents] } });
211
+ };
212
+ // Live token usage per agent/model (protocol 0.6): recomputed at most every USAGE_THROTTLE_MS per session.
213
+ const usageReader = createUsageReader();
214
+ const budgetMeter = createBudgetMeter();
215
+ const transcriptOf = new Map();
216
+ const usageTimers = new Map();
217
+ const USAGE_THROTTLE_MS = 1500;
218
+ const refreshUsage = (sessionId) => {
219
+ usageTimers.delete(sessionId);
220
+ const tp = transcriptOf.get(sessionId);
221
+ const s = sessions.get(sessionId);
222
+ if (!tp || !s)
223
+ return;
224
+ const usage = usageReader.session(tp);
225
+ const b = readBudgetConfig(home);
226
+ if (usage && b) {
227
+ usage.budget = b.sessionTokens;
228
+ usage.budgetUsed = budgetMeter.used(s.id, s.startedAt, usage.total, b);
229
+ }
230
+ if (!usage || (usage.total === s.usage?.total && usage.budget === s.usage?.budget && usage.budgetUsed === s.usage?.budgetUsed))
231
+ return;
232
+ s.usage = usage;
233
+ publishSession(s);
234
+ };
235
+ const scheduleUsage = (ev) => {
236
+ const tp = safeTranscriptPath(ev.transcriptPath);
237
+ if (tp)
238
+ transcriptOf.set(ev.session.id, tp);
239
+ if (!transcriptOf.has(ev.session.id) || usageTimers.has(ev.session.id))
240
+ return;
241
+ const t = setTimeout(() => { try {
242
+ refreshUsage(ev.session.id);
243
+ }
244
+ catch { /* never break ingest */ } }, USAGE_THROTTLE_MS);
245
+ t.unref?.();
246
+ usageTimers.set(ev.session.id, t);
247
+ };
248
+ const updateSession = (ev) => {
249
+ let s = sessions.get(ev.session.id);
250
+ if (!s) {
251
+ s = { id: ev.session.id, tool: ev.source.tool, startedAt: ev.ts, lastEventAt: ev.ts, eventCount: 0, agents: [] };
252
+ sessions.set(s.id, s);
253
+ }
254
+ s.eventCount += 1;
255
+ if (ev.ts > s.lastEventAt)
256
+ s.lastEventAt = ev.ts;
257
+ if (ev.ts < s.startedAt)
258
+ s.startedAt = ev.ts;
259
+ if (ev.session.project)
260
+ s.project = ev.session.project;
261
+ if (ev.session.cwd)
262
+ s.cwd = ev.session.cwd;
263
+ if (!s.agents.includes(ev.agent.id))
264
+ s.agents.push(ev.agent.id);
265
+ if (ev.kind === 'session.end')
266
+ s.endedAt = ev.ts;
267
+ publishSession(s);
268
+ scheduleUsage(ev);
269
+ };
270
+ /** Validates, redacts, stores and broadcasts. Returns the event or null if invalid. Never throws. */
271
+ const ingest = (raw) => {
272
+ const r = parseEvent(raw);
273
+ if (!r.ok)
274
+ return null;
275
+ // `peer` and the peer: id namespace belong to events received from teammates only (team.ts), never to local ones.
276
+ if (r.event.session.id.startsWith('peer:') || r.event.agent.id.startsWith('peer:'))
277
+ return null;
278
+ const local = { ...r.event };
279
+ delete local.peer;
280
+ const ev = redactDeep(local);
281
+ try {
282
+ if (!store.addEvent(ev))
283
+ return ev; // duplicate id: already known
284
+ learner.onEvent(ev); // scoring, proposals, transcripts (never throws)
285
+ loopGuard.onEvent(ev);
286
+ audit.append(ev);
287
+ recent.push(ev);
288
+ if (recent.length > RECENT)
289
+ recent.splice(0, recent.length - RECENT);
290
+ updateSession(ev);
291
+ snapshots.onEvent(ev, sessions.get(ev.session.id)?.cwd); // before/after file snapshots (never throws)
292
+ broadcast({ type: 'event', event: ev });
293
+ teamShare?.publish(ev);
294
+ sync?.publish(ev);
295
+ }
296
+ catch {
297
+ return null;
298
+ }
299
+ return ev;
300
+ };
301
+ /** A teammate's event (already reduced, namespaced and tagged by team.ts): show it, keep nothing. */
302
+ const ingestPeer = (ev) => {
303
+ let s = peerSessions.get(ev.session.id);
304
+ if (!s) {
305
+ // Global bounds (whatever the source): at most MAX_PEER_HANDLES teammates and MAX_PEER_SESSIONS_TOTAL sessions.
306
+ const handles = new Set([...peerSessions.values()].map((x) => x.peer));
307
+ if (!handles.has(ev.peer.handle) && handles.size >= MAX_PEER_HANDLES)
308
+ return;
309
+ if (peerSessions.size >= MAX_PEER_SESSIONS_TOTAL) {
310
+ const oldest = [...peerSessions.values()].reduce((a, b) => (a.lastEventAt <= b.lastEventAt ? a : b));
311
+ peerSessions.delete(oldest.id);
312
+ }
313
+ // Bounded per teammate: drop their least recently active session first.
314
+ const mine = [...peerSessions.values()].filter((x) => x.peer === ev.peer.handle);
315
+ if (mine.length >= MAX_PEER_SESSIONS) {
316
+ const oldest = mine.reduce((a, b) => (a.lastEventAt <= b.lastEventAt ? a : b));
317
+ peerSessions.delete(oldest.id);
318
+ }
319
+ s = { id: ev.session.id, tool: ev.source.tool, startedAt: ev.ts, lastEventAt: ev.ts, eventCount: 0, agents: [], peer: ev.peer.handle };
320
+ peerSessions.set(s.id, s);
321
+ }
322
+ s.eventCount += 1;
323
+ if (ev.ts > s.lastEventAt)
324
+ s.lastEventAt = ev.ts;
325
+ if (ev.session.project)
326
+ s.project = ev.session.project;
327
+ if (!s.agents.includes(ev.agent.id)) {
328
+ if (s.agents.length >= MAX_PEER_AGENTS)
329
+ return; // a session with this many agents is not a real one
330
+ s.agents.push(ev.agent.id);
331
+ }
332
+ if (ev.kind === 'session.end')
333
+ s.endedAt = ev.ts;
334
+ peerRecent.push(ev);
335
+ if (peerRecent.length > RECENT)
336
+ peerRecent.splice(0, peerRecent.length - RECENT);
337
+ broadcast({ type: 'session.update', session: { ...s, agents: [...s.agents] } });
338
+ broadcast({ type: 'event', event: ev });
339
+ };
340
+ const engineEvent = (base, kind, extra) => ingest(createEvent({ source: { tool: 'agentcity' }, session: base.session, agent: base.agent, kind, ...extra }));
341
+ const decide = (requestId, d) => {
342
+ const p = pending.get(requestId);
343
+ if (!p || !d || (d.decision !== 'allow' && d.decision !== 'deny'))
344
+ return false;
345
+ pending.delete(requestId);
346
+ clearTimeout(p.timer);
347
+ p.resolve(d);
348
+ return true;
349
+ };
350
+ const waitForResume = (sessionId, ms, signal) => new Promise((resolve) => {
351
+ if (ms <= 0 || signal?.aborted)
352
+ return resolve(false);
353
+ let set = pauseWaiters.get(sessionId);
354
+ if (!set) {
355
+ set = new Set();
356
+ pauseWaiters.set(sessionId, set);
357
+ }
358
+ const owner = set;
359
+ const w = {
360
+ resolve: (ok) => {
361
+ owner.delete(w);
362
+ clearTimeout(w.timer);
363
+ signal?.removeEventListener('abort', onAbort);
364
+ resolve(ok);
365
+ },
366
+ };
367
+ const onAbort = () => w.resolve(false);
368
+ w.timer = setTimeout(() => w.resolve(false), ms);
369
+ signal?.addEventListener('abort', onAbort, { once: true });
370
+ owner.add(w);
371
+ });
372
+ const control = (sessionId, cmd) => {
373
+ if (cmd.type === 'pause')
374
+ paused.add(sessionId);
375
+ else if (cmd.type === 'resume') {
376
+ paused.delete(sessionId);
377
+ for (const w of [...(pauseWaiters.get(sessionId) ?? [])])
378
+ w.resolve(true);
379
+ }
380
+ else if (cmd.type === 'prune') {
381
+ if (typeof cmd.nodeId !== 'string')
382
+ throw new HttpError(400, 'nodeId required');
383
+ const last = [...store.sessionEvents(sessionId)].reverse().find((e) => e.kind === 'plan.update' && e.plan);
384
+ if (!last?.plan)
385
+ throw new HttpError(404, 'no plan for session');
386
+ if (!last.plan.nodes.some((n) => n.id === cmd.nodeId))
387
+ throw new HttpError(404, 'node not found');
388
+ const ids = new Set([cmd.nodeId]);
389
+ let grew = true;
390
+ while (grew) {
391
+ grew = false;
392
+ for (const n of last.plan.nodes) {
393
+ if (n.parentId && ids.has(n.parentId) && !ids.has(n.id)) {
394
+ ids.add(n.id);
395
+ grew = true;
396
+ }
397
+ }
398
+ }
399
+ const nodes = last.plan.nodes.map((n) => (ids.has(n.id) ? { ...n, state: 'pruned' } : n));
400
+ const prev = (pruned.get(sessionId) ?? []).filter((n) => !ids.has(n.id));
401
+ pruned.set(sessionId, [...prev, ...nodes.filter((n) => ids.has(n.id))]);
402
+ engineEvent(last, 'plan.update', { plan: { nodes } });
403
+ }
404
+ else
405
+ throw new HttpError(400, 'unknown command');
406
+ const s = sessions.get(sessionId);
407
+ if (s)
408
+ publishSession(s);
409
+ };
410
+ const prunedMatch = (ev) => {
411
+ const nodes = pruned.get(ev.session.id);
412
+ if (!nodes?.length || !ev.step)
413
+ return undefined;
414
+ const hay = `${ev.step.target ?? ''} ${ev.step.summary ?? ''}`;
415
+ const planNodeId = ev.step.planNodeId;
416
+ return nodes.find((n) => {
417
+ if (typeof planNodeId === 'string' && n.id === planNodeId)
418
+ return true;
419
+ const label = n.label.trim();
420
+ if (label.length < MIN_LABEL_MATCH)
421
+ return false;
422
+ return new RegExp(`(^|[^\\p{L}\\p{N}_])${escapeRe(label)}($|[^\\p{L}\\p{N}_])`, 'iu').test(hay);
423
+ });
424
+ };
425
+ const preTool = async (body, signal) => {
426
+ const deadline = Date.now() + timeoutMs; // single deadline for pause + approval
427
+ const wrapped = body && typeof body === 'object' && 'event' in body;
428
+ const raw = wrapped ? body.event : body;
429
+ const requireHuman = wrapped && body.requireHuman === true;
430
+ const ev = ingest(raw);
431
+ if (!ev)
432
+ throw new HttpError(400, 'invalid event');
433
+ const finish = (decision, requestId, reason, by, policyId) => {
434
+ if (decision === 'deny')
435
+ snapshots.discard(ev.id); // the write never happened
436
+ engineEvent(ev, 'approval.result', { approval: { requestId, decision, ...(by ? { by } : {}), ...(reason ? { reason } : {}) } });
437
+ return { decision, requestId, ...(reason ? { reason } : {}), ...(policyId ? { policyId } : {}) };
438
+ };
439
+ if (paused.has(ev.session.id)) {
440
+ const resumed = await waitForResume(ev.session.id, deadline - Date.now(), signal);
441
+ if (!resumed)
442
+ return finish('deny', newId(), signal?.aborted ? CLIENT_GONE : 'timeout', 'agentcity');
443
+ }
444
+ const node = prunedMatch(ev);
445
+ if (node)
446
+ return finish('deny', newId(), `pruned: ${node.label}`, 'agentcity');
447
+ const b = readBudgetConfig(home);
448
+ const sess = sessions.get(ev.session.id);
449
+ const used = b && sess?.usage ? budgetMeter.used(sess.id, sess.startedAt, sess.usage.total, b) : 0;
450
+ if (b && used >= b.sessionTokens)
451
+ return finish('deny', newId(), budgetDenial(used, b.sessionTokens), 'agentcity', 'budget');
452
+ const loop = loopGuard.check(ev);
453
+ if (loop)
454
+ return finish('deny', newId(), loop, 'agentcity', 'loop-guard');
455
+ const evaluated = evaluatePolicies(ev);
456
+ const policyId = evaluated.policyId;
457
+ // Protocol 0.4: an explicit approval request turns a policy 'allow' into 'ask'; 'deny' still denies.
458
+ const decision = requireHuman && evaluated.decision === 'allow' ? 'ask' : evaluated.decision;
459
+ if (decision === 'allow')
460
+ return { decision: 'allow', ...(policyId ? { policyId } : {}) };
461
+ if (decision === 'deny')
462
+ return finish('deny', newId(), `policy: ${policyId ?? 'deny'}`, 'policy', policyId);
463
+ if (signal?.aborted)
464
+ return finish('deny', newId(), CLIENT_GONE, 'agentcity', policyId);
465
+ const remaining = deadline - Date.now();
466
+ if (remaining <= 0)
467
+ return finish('deny', newId(), 'timeout', 'agentcity', policyId);
468
+ const requestId = newId();
469
+ const onAbort = () => void decide(requestId, { decision: 'deny', by: 'agentcity', reason: CLIENT_GONE });
470
+ const approval = {
471
+ requestId, event: ev, createdAt: new Date().toISOString(), ...(policyId ? { policyId } : {}),
472
+ ...(requireHuman ? { reason: EXPLICIT_REASON } : {}),
473
+ };
474
+ const d = await new Promise((resolve) => {
475
+ pending.set(requestId, {
476
+ approval,
477
+ resolve,
478
+ timer: setTimeout(() => decide(requestId, { decision: 'deny', by: 'agentcity', reason: 'timeout' }), remaining),
479
+ });
480
+ signal?.addEventListener('abort', onAbort, { once: true });
481
+ engineEvent(ev, 'approval.request', { approval: { requestId, ...(requireHuman ? { reason: EXPLICIT_REASON } : {}) } });
482
+ broadcast({ type: 'approval.pending', approval });
483
+ integrations.onApprovalPending(approval);
484
+ slack?.notifyPending(approval);
485
+ });
486
+ signal?.removeEventListener('abort', onAbort);
487
+ broadcast({ type: 'approval.resolved', requestId, decision: d.decision, ...(d.by ? { by: d.by } : {}) });
488
+ slack?.notifyResolved(requestId, d);
489
+ return finish(d.decision, requestId, d.reason, d.by, policyId);
490
+ };
491
+ const addLesson = (body) => {
492
+ const i = (body ?? {});
493
+ if (i.verified !== true)
494
+ throw new HttpError(400, 'lesson must be verified (principle 5)');
495
+ if (typeof i.evidence !== 'string' || !i.evidence.trim())
496
+ throw new HttpError(400, 'evidence required');
497
+ if (typeof i.text !== 'string' || !i.text.trim())
498
+ throw new HttpError(400, 'text required');
499
+ if (!i.source || typeof i.source.tool !== 'string')
500
+ throw new HttpError(400, 'source.tool required');
501
+ if (i.tags !== undefined && !(Array.isArray(i.tags) && i.tags.every((t) => typeof t === 'string'))) {
502
+ throw new HttpError(400, 'tags must be strings');
503
+ }
504
+ const src = i.source;
505
+ // Lessons written by an agent (they carry a session) need proof the engine recorded itself: a passing test run of
506
+ // the same project or session in the last hour, not followed by a failing one. People (CLI, team imports) vouch.
507
+ let evidence = i.evidence;
508
+ if (src.sessionId) {
509
+ const v = verifyFromEvents(store.recent(5000), { sessionId: src.sessionId, ...(i.project ? { project: i.project } : {}) });
510
+ if (!v.ok) {
511
+ throw new HttpError(422, v.reason === 'last-test-failed'
512
+ ? 'not verified: the latest test run failed; fix it and run the tests again (principle 5)'
513
+ : 'not verified: AgentCity saw no passing test run in this project in the last hour; run the tests first (principle 5)');
514
+ }
515
+ evidence = sealEvidence(i.evidence, v.proof);
516
+ }
517
+ const now = new Date().toISOString();
518
+ const lesson = redactDeep({
519
+ id: newId(),
520
+ text: i.text,
521
+ ...(i.project ? { project: i.project } : {}),
522
+ tags: i.tags ?? [],
523
+ source: { tool: src.tool, ...(src.sessionId ? { sessionId: src.sessionId } : {}), ...(src.agentId ? { agentId: src.agentId } : {}) },
524
+ evidence,
525
+ verified: true,
526
+ score: 1,
527
+ uses: 0,
528
+ createdAt: now,
529
+ updatedAt: now,
530
+ });
531
+ store.addLesson(lesson);
532
+ ingest(createEvent({
533
+ source: { tool: lesson.source.tool },
534
+ session: { id: lesson.source.sessionId ?? 'agentcity', ...(lesson.project ? { project: lesson.project } : {}) },
535
+ agent: { id: lesson.source.agentId ?? 'agentcity' },
536
+ kind: 'lesson.write',
537
+ lesson: { id: lesson.id, text: lesson.text, evidence: lesson.evidence, score: lesson.score },
538
+ }));
539
+ return lesson;
540
+ };
541
+ const lessonFeedback = (id, body) => {
542
+ const l = store.getLesson(id);
543
+ if (!l)
544
+ throw new HttpError(404, 'lesson not found');
545
+ const helped = body?.helped;
546
+ if (typeof helped !== 'boolean')
547
+ throw new HttpError(400, 'helped:boolean required');
548
+ const next = { ...l, uses: l.uses + 1, score: Math.max(0, l.score + (helped ? 1 : -1)), updatedAt: new Date().toISOString() };
549
+ store.updateLesson(next);
550
+ return next;
551
+ };
552
+ /** An agent may accept a proposal only this soon after the engine observed the fix. */
553
+ const AGENT_ACCEPT_MS = 60 * 60 * 1000;
554
+ const lessonRoutes = createLessonRoutes({ store, emit: (ev) => void ingest(ev) });
555
+ // AGENTCITY_LOOP_GUARD=0 turns the loop guard off
556
+ const loopGuard = process.env.AGENTCITY_LOOP_GUARD === '0' ? { onEvent: () => { }, check: () => undefined } : createLoopGuard();
557
+ const learner = createLearner({ home, store, emit: (ev) => void ingest(ev) });
558
+ const runMaintenance = () => { try {
559
+ learner.maintain();
560
+ }
561
+ catch { /* best effort */ } };
562
+ runMaintenance();
563
+ const maintenanceTimer = setInterval(runMaintenance, 24 * 60 * 60 * 1000);
564
+ maintenanceTimer.unref?.();
565
+ const timeTravel = createTimeTravelRoutes({
566
+ snapshots,
567
+ sessionCwd: (id) => sessions.get(id)?.cwd,
568
+ isPaused: (id) => paused.has(id),
569
+ emit: (id, action, summary, timeTravel) => {
570
+ const s = sessions.get(id);
571
+ ingest(createEvent({ source: { tool: 'agentcity' }, session: { id, ...(s?.cwd ? { cwd: s.cwd } : {}) }, agent: { id: 'agentcity' }, kind: 'metric', step: { action, category: 'other', summary: summary.slice(0, 200) }, timeTravel }));
572
+ },
573
+ });
574
+ const readBody = (req) => new Promise((resolve, reject) => {
575
+ const chunks = [];
576
+ let size = 0;
577
+ req.on('data', (c) => {
578
+ size += c.length;
579
+ if (size > MAX_BODY) {
580
+ reject(new HttpError(413, 'body too large'));
581
+ req.destroy();
582
+ }
583
+ else
584
+ chunks.push(c);
585
+ });
586
+ req.on('end', () => {
587
+ const txt = Buffer.concat(chunks).toString('utf8');
588
+ if (!txt.trim())
589
+ return resolve(undefined);
590
+ try {
591
+ resolve(JSON.parse(txt));
592
+ }
593
+ catch {
594
+ reject(new HttpError(400, 'invalid JSON'));
595
+ }
596
+ });
597
+ req.on('error', reject);
598
+ });
599
+ const serveStatic = (urlPath, res) => {
600
+ if (!opts.staticDir)
601
+ return false;
602
+ const root = path.resolve(opts.staticDir);
603
+ let rel;
604
+ try {
605
+ rel = decodeURIComponent(urlPath);
606
+ }
607
+ catch {
608
+ return false;
609
+ }
610
+ const candidates = [path.join(root, rel), path.join(root, rel, 'index.html'), path.join(root, `${rel}.html`), path.join(root, 'index.html')];
611
+ for (const f of candidates) {
612
+ const abs = path.resolve(f);
613
+ if (abs !== root && !abs.startsWith(root + path.sep))
614
+ continue;
615
+ try {
616
+ if (!fs.statSync(abs).isFile())
617
+ continue;
618
+ }
619
+ catch {
620
+ continue;
621
+ }
622
+ res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' });
623
+ fs.createReadStream(abs).pipe(res);
624
+ return true;
625
+ }
626
+ return false;
627
+ };
628
+ const send = (res, status, data) => {
629
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
630
+ res.end(JSON.stringify(data));
631
+ };
632
+ const route = async (req, res) => {
633
+ const origin = req.headers.origin;
634
+ if (origin) {
635
+ if (!originOk(origin))
636
+ return send(res, 403, { error: 'origin not allowed' });
637
+ res.setHeader('access-control-allow-origin', origin);
638
+ res.setHeader('vary', 'origin');
639
+ res.setHeader('access-control-allow-methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
640
+ res.setHeader('access-control-allow-headers', 'content-type');
641
+ }
642
+ if (req.method === 'OPTIONS') {
643
+ res.writeHead(204);
644
+ res.end();
645
+ return;
646
+ }
647
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
648
+ const p = url.pathname.replace(/\/+$/, '') || '/';
649
+ const m = req.method ?? 'GET';
650
+ let mm;
651
+ const param = (x) => decodeURIComponent(x[1] ?? '');
652
+ if (m === 'GET' && p === '/health')
653
+ return send(res, 200, health);
654
+ if (m === 'POST' && p === '/events') {
655
+ const body = await readBody(req);
656
+ const list = Array.isArray(body) ? body : [body];
657
+ let accepted = 0;
658
+ for (const e of list)
659
+ if (ingest(e))
660
+ accepted++;
661
+ return send(res, 200, { accepted, rejected: list.length - accepted });
662
+ }
663
+ if (m === 'POST' && p === '/hooks/pre-tool') {
664
+ const ac = new AbortController();
665
+ res.on('close', () => {
666
+ if (!res.writableEnded)
667
+ ac.abort();
668
+ });
669
+ const body = await readBody(req);
670
+ const out = await preTool(body, ac.signal);
671
+ if (ac.signal.aborted)
672
+ return;
673
+ return send(res, 200, out);
674
+ }
675
+ if (m === 'GET' && p === '/approvals')
676
+ return send(res, 200, [...pending.values()].map((x) => x.approval));
677
+ if (m === 'POST' && (mm = p.match(/^\/approvals\/([^/]+)$/))) {
678
+ const body = (await readBody(req));
679
+ if (!body || !decide(param(mm), body))
680
+ return send(res, 404, { error: 'approval not found or invalid decision' });
681
+ return send(res, 200, { ok: true });
682
+ }
683
+ if (m === 'GET' && p === '/sessions') {
684
+ return send(res, 200, [...sessions.values(), ...peerSessions.values()].sort((a, b) => b.lastEventAt.localeCompare(a.lastEventAt)));
685
+ }
686
+ if (m === 'GET' && p === '/sync')
687
+ return send(res, 200, sync ? { enabled: true, ...sync.status() } : { enabled: false });
688
+ if (m === 'GET' && p === '/slack')
689
+ return send(res, 200, slack ? { enabled: true, ...slack.status() } : { enabled: false });
690
+ if (m === 'GET' && p === '/team') {
691
+ return send(res, 200, {
692
+ sharing: teamShare ? { handle: teamShare.handle, port: teamShare.port } : null,
693
+ peers: followers.map((f) => f.status()),
694
+ });
695
+ }
696
+ if (m === 'GET' && (mm = p.match(/^\/sessions\/([^/]+)\/events$/)))
697
+ return send(res, 200, store.sessionEvents(param(mm)));
698
+ if (m === 'POST' && (mm = p.match(/^\/sessions\/([^/]+)\/control$/))) {
699
+ const body = (await readBody(req));
700
+ if (!body || typeof body !== 'object')
701
+ throw new HttpError(400, 'command required');
702
+ control(param(mm), body);
703
+ return send(res, 200, { ok: true });
704
+ }
705
+ if (m === 'GET' && p === '/policies')
706
+ return send(res, 200, policies.list());
707
+ if (m === 'GET' && p === '/packs')
708
+ return send(res, 200, { packs: packs.packs, invalid: packs.invalid, policies: packPolicies.list() });
709
+ if (m === 'POST' && p === '/packs/reload') {
710
+ packs = loadPacks(home);
711
+ packPolicies.set(packs.policies);
712
+ return send(res, 200, { packs: packs.packs, invalid: packs.invalid });
713
+ }
714
+ if (m === 'GET' && p === '/themes')
715
+ return send(res, 200, packs.themes);
716
+ if (m === 'PUT' && p === '/policies') {
717
+ const body = await readBody(req);
718
+ if (!isPolicyArray(body))
719
+ throw new HttpError(400, 'invalid policies');
720
+ policies.set(body);
721
+ savePolicies(home, body);
722
+ return send(res, 200, { ok: true });
723
+ }
724
+ if (m === 'GET' && p === '/lessons') {
725
+ const list = store.searchLessons(url.searchParams.get('q') || undefined, url.searchParams.get('project') || undefined);
726
+ // active=1 (agents): archived lessons (duplicates, low score, stale) are left out; people see them all
727
+ return send(res, 200, url.searchParams.get('active') === '1' ? list.filter((l) => !l.tags.includes(ARCHIVED)) : list);
728
+ }
729
+ if (m === 'POST' && p === '/lessons/brief') {
730
+ const b = ((await readBody(req)) ?? {});
731
+ if (typeof b.sessionId !== 'string' || !b.sessionId)
732
+ throw new HttpError(400, 'sessionId required');
733
+ return send(res, 200, learner.brief(typeof b.project === 'string' && b.project ? b.project : undefined, b.sessionId, typeof b.tool === 'string' ? b.tool : undefined));
734
+ }
735
+ if (m === 'GET' && p === '/lessons/proposals') {
736
+ const proj = url.searchParams.get('project') || undefined;
737
+ const recent = url.searchParams.get('recent') === '1';
738
+ return send(res, 200, learner.proposals().filter((x) => (!proj || x.project === proj) && (!recent || Date.now() - Date.parse(x.createdAt) <= AGENT_ACCEPT_MS)));
739
+ }
740
+ if (m === 'POST' && (mm = p.match(/^\/lessons\/proposals\/([^/]+)\/accept$/))) {
741
+ const prop = learner.proposals().find((x) => x.id === param(mm));
742
+ if (!prop)
743
+ throw new HttpError(404, 'proposal not found');
744
+ const b = ((await readBody(req)) ?? {});
745
+ const byAgent = b.by === 'agent';
746
+ const given = typeof b.text === 'string' ? b.text.trim() : '';
747
+ if (byAgent) {
748
+ // an agent accepts only what it just fixed in its own project, and must write the cause itself
749
+ if (Date.now() - Date.parse(prop.createdAt) > AGENT_ACCEPT_MS)
750
+ throw new HttpError(403, 'proposal too old for an agent: a person can accept it in the UI');
751
+ if (prop.project && b.project !== prop.project)
752
+ throw new HttpError(403, 'proposal belongs to another project');
753
+ if (given.length < 15 || given.includes('(Describe'))
754
+ throw new HttpError(422, 'write the cause in one sentence');
755
+ }
756
+ const text = given || prop.text;
757
+ // the proof is what the engine itself observed (failed run, edits, passing run); a person or the agent that fixed it accepts it
758
+ const lesson = addLesson({
759
+ text, verified: true, tags: ['propuesta', ...(byAgent ? ['agente'] : [])], ...(prop.project ? { project: prop.project } : {}),
760
+ evidence: `${prop.evidence}\n— propuesta por AgentCity a partir de eventos observados; aceptada por ${byAgent ? 'el agente' : 'una persona'}`,
761
+ source: { tool: 'agentcity' },
762
+ });
763
+ learner.takeProposal(prop.id);
764
+ return send(res, 200, lesson);
765
+ }
766
+ if (m === 'DELETE' && (mm = p.match(/^\/lessons\/proposals\/([^/]+)$/))) {
767
+ return send(res, learner.takeProposal(param(mm)) ? 200 : 404, { ok: true });
768
+ }
769
+ if (m === 'POST' && p === '/lessons/maintain')
770
+ return send(res, 200, learner.maintain());
771
+ if (m === 'GET' && p === '/memory/impact')
772
+ return send(res, 200, learner.impact());
773
+ if (m === 'POST' && p === '/lessons')
774
+ return send(res, 200, addLesson(await readBody(req)));
775
+ if (m === 'POST' && (mm = p.match(/^\/lessons\/([^/]+)\/feedback$/))) {
776
+ return send(res, 200, lessonFeedback(param(mm), await readBody(req)));
777
+ }
778
+ const lr = await lessonRoutes(m, p, () => readBody(req));
779
+ if (lr)
780
+ return send(res, lr.status, lr.data);
781
+ const ar = auditRoute(audit, m, p, url.searchParams);
782
+ if (ar) {
783
+ res.writeHead(ar.status, { 'content-type': ar.contentType });
784
+ res.end(ar.body);
785
+ return;
786
+ }
787
+ const tt = await timeTravel(m, p, () => readBody(req));
788
+ if (tt)
789
+ return send(res, tt.status, tt.data);
790
+ const ir = await integrations.route(m, p, () => readBody(req));
791
+ if (ir)
792
+ return send(res, ir.status, ir.data);
793
+ if (m === 'GET' && serveStatic(url.pathname, res))
794
+ return;
795
+ send(res, 404, { error: 'not found' });
796
+ };
797
+ const server = http.createServer((req, res) => {
798
+ route(req, res).catch((err) => {
799
+ if (res.headersSent) {
800
+ res.end();
801
+ return;
802
+ }
803
+ if (err instanceof HttpError)
804
+ send(res, err.status, { error: err.message });
805
+ else
806
+ send(res, 500, { error: 'internal error' });
807
+ });
808
+ });
809
+ server.requestTimeout = 0; // pre-tool may wait for a human decision
810
+ const wss = new WebSocketServer({
811
+ server,
812
+ path: '/ws',
813
+ verifyClient: (info) => originOk(info.origin),
814
+ });
815
+ wss.on('connection', (ws) => {
816
+ clients.add(ws);
817
+ const hello = {
818
+ type: 'hello',
819
+ health,
820
+ sessions: [...sessions.values(), ...peerSessions.values()],
821
+ approvals: [...pending.values()].map((x) => x.approval),
822
+ recent: [...recent, ...peerRecent],
823
+ };
824
+ ws.send(JSON.stringify(hello));
825
+ ws.on('message', (data) => {
826
+ try {
827
+ const msg = JSON.parse(String(data));
828
+ if (msg.type === 'approval.decide')
829
+ decide(msg.requestId, msg.decision);
830
+ else if (msg.type === 'control')
831
+ control(msg.sessionId, msg.command);
832
+ }
833
+ catch {
834
+ // malformed client messages are ignored
835
+ }
836
+ });
837
+ ws.on('close', () => clients.delete(ws));
838
+ ws.on('error', () => clients.delete(ws));
839
+ });
840
+ try {
841
+ await new Promise((resolve, reject) => {
842
+ server.once('error', reject);
843
+ server.listen(port, DEFAULT_HOST, () => {
844
+ server.off('error', reject);
845
+ resolve();
846
+ });
847
+ });
848
+ }
849
+ catch (err) {
850
+ store.close();
851
+ snapshots.close();
852
+ throw err;
853
+ }
854
+ const addr = server.address();
855
+ const actualPort = typeof addr === 'object' && addr ? addr.port : port;
856
+ origins = allowedOrigins(actualPort);
857
+ boundPort = actualPort;
858
+ lock.setPort(actualPort);
859
+ let mobile;
860
+ try {
861
+ if (opts.mobile) {
862
+ mobile = await startMobileApprovals({ list: () => [...pending.values()].map((x) => x.approval), decide }, opts.mobile === true ? {} : opts.mobile);
863
+ }
864
+ if (opts.team?.share)
865
+ teamShare = await startTeamShare(() => recent, opts.team.share === true ? {} : opts.team.share);
866
+ for (const peer of opts.team?.peers ?? [])
867
+ followers.push(followPeer(peer, ingestPeer));
868
+ if (opts.sync)
869
+ sync = startSync(opts.sync, ingestPeer, opts.syncDeps);
870
+ if (opts.slack) {
871
+ const bad = validateSlackOptions(opts.slack);
872
+ if (bad)
873
+ throw new Error(bad);
874
+ slack = startSlackApprovals(opts.slack, decide, opts.slackDeps);
875
+ }
876
+ }
877
+ catch (err) {
878
+ sync?.close();
879
+ slack?.close();
880
+ for (const f of followers)
881
+ f.close();
882
+ await teamShare?.close();
883
+ await mobile?.close();
884
+ await new Promise((r) => { server.closeAllConnections(); server.close(() => r()); });
885
+ store.close();
886
+ snapshots.close();
887
+ lock.release();
888
+ throw err;
889
+ }
890
+ return {
891
+ port: actualPort,
892
+ storeKind: store.kind,
893
+ ...(mobile ? { mobile } : {}),
894
+ ...(teamShare ? { team: teamShare } : {}),
895
+ async close() {
896
+ clearInterval(maintenanceTimer);
897
+ for (const t of usageTimers.values())
898
+ clearTimeout(t);
899
+ sync?.close();
900
+ slack?.close();
901
+ for (const f of followers)
902
+ f.close();
903
+ await teamShare?.close();
904
+ await mobile?.close();
905
+ for (const id of [...pending.keys()])
906
+ decide(id, { decision: 'deny', by: 'agentcity', reason: 'shutdown' });
907
+ for (const set of pauseWaiters.values())
908
+ for (const w of [...set])
909
+ w.resolve(false);
910
+ for (const c of clients)
911
+ c.terminate();
912
+ await new Promise((r) => wss.close(() => r()));
913
+ server.closeAllConnections();
914
+ await new Promise((r) => server.close(() => r()));
915
+ store.close();
916
+ snapshots.close();
917
+ lock.release();
918
+ },
919
+ };
920
+ }
921
+ //# sourceMappingURL=server.js.map