fullcourtdefense 2.2.0 → 2.3.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.
@@ -1,56 +1,162 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RecordQueue = void 0;
3
+ exports.RecordQueue = exports.DEFAULT_CONCURRENCY = exports.DEFAULT_BATCH_BYTES = exports.DEFAULT_BATCH_RECORDS = exports.FLUSH_MAX_MS = void 0;
4
+ /**
5
+ * The records of locally decided tool calls (owner order 2026-11-01): queued in memory and sent in the
6
+ * background, in batches, to the backend (`POST /api/agent-security/runtime/tool-calls`, or one by one to
7
+ * `POST /api/agent-security/runtime/tool-call` against an older backend: see client.ts). Nothing here is ever
8
+ * awaited on a tool call's path, and a push does constant work.
9
+ *
10
+ * - bounded: past `max` the OLDEST record is dropped, never the agent's memory. A drop is never silent: it is
11
+ * counted (`lost`) AND kept as a GAP ({ dropped, from, to }) that rides on the next upload that the backend
12
+ * accepts, so the console says "N actions between 14:02 and 14:03 were not recorded"; `onDrop` tells the app;
13
+ * - batched: a push schedules one send `delayMs` later; each round takes up to `concurrency` batches of up to
14
+ * `batch` records (and `maxBytes` of JSON), sends them together, and then yields to the event loop before the
15
+ * next round, so a backlog never holds the agent's own work for more than one small round at a time;
16
+ * - outage: a record the API did not answer (no answer, timeout, 408, 429, 5xx) goes back to the FRONT of
17
+ * the queue and sending pauses (1 s doubling to 2 s, or until `resume()`: any answer of the API; the next round probes with a record, so
18
+ * the queue drains within one back-off of the API coming back); a gap that was not accepted stays pending;
19
+ * - a definite refusal (another 4xx) drops that record (resending it would be refused again) and counts it in
20
+ * the gap, like any other record that did not arrive;
21
+ * - exit: `flush()` is ONE bounded attempt (lifts a pause, at most 2 s whatever the caller asks), `drain()` hands what is left to the
22
+ * local spool (recordSpool.ts) so the next process sends it.
23
+ */
24
+ const crypto_1 = require("crypto");
4
25
  const BACKOFF_MIN_MS = 1000;
5
- const BACKOFF_MAX_MS = 30000;
26
+ const BACKOFF_MAX_MS = 2000;
27
+ /** Longest one `flush()` waits: a serverless handler calls it at its end and must not hang. */
28
+ exports.FLUSH_MAX_MS = 2000;
29
+ exports.DEFAULT_BATCH_RECORDS = 100;
30
+ exports.DEFAULT_BATCH_BYTES = 256 * 1024;
31
+ exports.DEFAULT_CONCURRENCY = 3;
32
+ function sizeOf(item) {
33
+ if (item.bytes === undefined) {
34
+ try {
35
+ item.bytes = JSON.stringify(item.body)?.length ?? 0;
36
+ }
37
+ catch {
38
+ item.bytes = 0;
39
+ }
40
+ }
41
+ return item.bytes;
42
+ }
43
+ /** A gap report's id (the backend keys on it; 16 random bytes). */
44
+ function newGapId() {
45
+ return `gap-${(0, crypto_1.randomUUID)()}`;
46
+ }
47
+ function mergeGap(a, b) {
48
+ if (!a)
49
+ return b;
50
+ if (!b)
51
+ return a;
52
+ return { dropped: a.dropped + b.dropped, from: a.from < b.from ? a.from : b.from, to: a.to > b.to ? a.to : b.to };
53
+ }
6
54
  class RecordQueue {
7
55
  constructor(send, options = {}) {
8
56
  this.send = send;
9
57
  this.items = [];
58
+ this.lastNoticeAt = 0;
10
59
  this.pausedUntil = 0;
11
60
  this.backoffMs = BACKOFF_MIN_MS;
12
- /** Records dropped because the queue was full (oldest first). */
61
+ /** Records dropped since the start (observability, tests). */
13
62
  this.lost = 0;
14
63
  /** Records sent / refused since the start (observability, tests). */
15
64
  this.sent = 0;
16
65
  this.refused = 0;
66
+ /** Gaps the backend accepted, and the records they covered. */
67
+ this.gapsReported = 0;
68
+ this.gapRecordsReported = 0;
69
+ /** Requests made (observability: records per request is what batching buys). */
70
+ this.requests = 0;
17
71
  this.max = Math.max(1, options.max ?? 10000);
18
- this.batch = Math.max(1, options.batch ?? 100);
19
- this.concurrency = Math.max(1, options.concurrency ?? 4);
72
+ this.batch = Math.max(1, options.batch ?? exports.DEFAULT_BATCH_RECORDS);
73
+ this.maxBytes = Math.max(1, options.maxBytes ?? exports.DEFAULT_BATCH_BYTES);
74
+ this.concurrency = Math.max(1, options.concurrency ?? exports.DEFAULT_CONCURRENCY);
20
75
  this.delayMs = Math.max(0, options.delayMs ?? 100);
76
+ this.onDrop = options.onDrop;
77
+ this.dropNoticeMs = Math.max(0, options.dropNoticeMs ?? 30000);
21
78
  }
22
79
  get size() {
23
80
  return this.items.length;
24
81
  }
82
+ /** Records dropped that no accepted upload has reported yet (zero: nothing is missing, or the console already says so). */
83
+ get unreportedLoss() {
84
+ return (this.openGap?.dropped ?? 0) + (this.sentGap?.dropped ?? 0);
85
+ }
86
+ /** Everything dropped and not yet accepted, as one window (the app's notice, the spool at exit). */
87
+ owedGap() {
88
+ const all = mergeGap(this.sentGap, this.openGap);
89
+ return all ? { dropped: all.dropped, from: all.from, to: all.to } : undefined;
90
+ }
91
+ /**
92
+ * The record that gives way when the queue is full: the oldest one that was never sent. A record sent once stays (the
93
+ * API may already hold it; it is sent again and stored once, by its id), so every dropped record is one the API never
94
+ * saw and the gap is exact. Records sent once are at the front and are at most one round of batches.
95
+ */
96
+ dropOne() {
97
+ const at = this.items.findIndex((item) => !item.tried);
98
+ this.noteDrop(at <= 0 ? this.items.shift() : this.items.splice(at, 1)[0]);
99
+ }
25
100
  push(body) {
26
- if (this.items.length >= this.max) {
27
- this.items.shift();
28
- this.lost += 1;
29
- }
101
+ if (this.items.length >= this.max)
102
+ this.dropOne();
30
103
  this.items.push({ body, at: new Date().toISOString() });
31
104
  this.schedule(this.delayMs);
32
105
  }
106
+ /** Records that cannot be queued any more: counted, kept as a gap, and the app told (off this call's path). */
107
+ noteDrop(dropped) {
108
+ this.lost += 1;
109
+ const at = dropped?.at ?? new Date().toISOString();
110
+ this.openGap = mergeGap(this.openGap, { dropped: 1, from: at, to: at });
111
+ this.scheduleNotice();
112
+ }
113
+ scheduleNotice() {
114
+ if (!this.onDrop || this.noticeTimer)
115
+ return;
116
+ const wait = Math.max(0, this.lastNoticeAt + this.dropNoticeMs - Date.now());
117
+ const timer = setTimeout(() => {
118
+ this.noticeTimer = undefined;
119
+ this.lastNoticeAt = Date.now();
120
+ const gap = this.owedGap();
121
+ if (!gap)
122
+ return;
123
+ try {
124
+ this.onDrop?.({ ...gap });
125
+ }
126
+ catch { /* observability must never break the agent */ }
127
+ }, wait);
128
+ timer.unref?.();
129
+ this.noticeTimer = timer;
130
+ }
33
131
  /** The API answered again (a bundle refresh): send now instead of waiting out the backoff. */
34
132
  resume() {
35
133
  if (this.pausedUntil === 0)
36
134
  return;
37
135
  this.pausedUntil = 0;
38
136
  this.backoffMs = BACKOFF_MIN_MS;
39
- if (this.items.length > 0)
137
+ if (this.items.length > 0 || this.unreportedLoss > 0)
40
138
  this.schedule(0);
41
139
  }
42
- /** Send everything queued now (exit); resolves when every batch was tried once. Never rejects. */
43
- async flush() {
140
+ /** One bounded attempt to send everything queued (exit, end of a serverless handler); never rejects, never waits past FLUSH_MAX_MS. */
141
+ async flush(maxMs = exports.FLUSH_MAX_MS) {
44
142
  this.pausedUntil = 0;
45
- if (this.running)
46
- await this.running;
47
- let guard = Math.ceil(this.items.length / this.batch) + 1;
48
- while (this.items.length > 0 && guard-- > 0) {
49
- const before = this.items.length;
50
- await this.runOnce();
51
- if (this.items.length >= before)
52
- break; // the API does not answer: the caller spools the rest
53
- }
143
+ this.backoffMs = BACKOFF_MIN_MS;
144
+ const work = (async () => {
145
+ if (this.running)
146
+ await this.running;
147
+ let guard = Math.ceil(this.items.length / this.batch) + 2;
148
+ while ((this.items.length > 0 || this.unreportedLoss > 0) && guard-- > 0) {
149
+ const before = this.items.length;
150
+ const gapBefore = this.unreportedLoss;
151
+ await this.runOnce();
152
+ if (this.items.length >= before && this.unreportedLoss >= gapBefore)
153
+ break; // the API does not answer: the caller spools the rest
154
+ }
155
+ })().catch(() => undefined);
156
+ let timer;
157
+ await Promise.race([work, new Promise((resolve) => { timer = setTimeout(resolve, Math.max(0, Math.min(maxMs, exports.FLUSH_MAX_MS))); })]);
158
+ if (timer !== undefined)
159
+ clearTimeout(timer);
54
160
  }
55
161
  /** Everything still queued, removed from the queue (handed to the local spool at exit). */
56
162
  drain() {
@@ -59,6 +165,15 @@ class RecordQueue {
59
165
  this.timer = undefined;
60
166
  return this.items.splice(0, this.items.length);
61
167
  }
168
+ /** The gap not yet reported, removed (handed to the local spool at exit, so the next process reports it). */
169
+ takeGap() {
170
+ const owed = this.owedGap();
171
+ // One report with one id: the next process may send it more than once (the backend stores it once).
172
+ const gap = owed ? { ...owed, id: this.sentGap && !this.openGap ? this.sentGap.id : newGapId() } : undefined;
173
+ this.openGap = undefined;
174
+ this.sentGap = undefined;
175
+ return gap;
176
+ }
62
177
  schedule(delayMs) {
63
178
  if (this.timer || this.running)
64
179
  return;
@@ -66,57 +181,106 @@ class RecordQueue {
66
181
  const timer = setTimeout(() => {
67
182
  this.timer = undefined;
68
183
  void this.runOnce().then(() => {
69
- if (this.items.length > 0)
70
- this.schedule(this.pausedUntil > Date.now() ? 0 : this.delayMs);
184
+ // A backlog goes on at once (the timer turn is the yield between rounds); a pause waits its back-off out.
185
+ if (this.items.length > 0 || (this.unreportedLoss > 0 && this.pausedUntil > 0))
186
+ this.schedule(0);
71
187
  });
72
188
  }, wait);
73
189
  // A queue must never keep a process alive on its own; the exit hooks flush or spool what is left.
74
190
  timer.unref?.();
75
191
  this.timer = timer;
76
192
  }
193
+ /** The next batch: up to `batch` records and `maxBytes` of JSON, at least one record. */
194
+ cut() {
195
+ let count = 0;
196
+ let bytes = 0;
197
+ while (count < this.items.length && count < this.batch) {
198
+ const size = sizeOf(this.items[count]);
199
+ if (count > 0 && bytes + size > this.maxBytes)
200
+ break;
201
+ bytes += size;
202
+ count += 1;
203
+ }
204
+ return this.items.splice(0, count);
205
+ }
77
206
  runOnce() {
78
207
  if (this.running)
79
208
  return this.running;
80
209
  const run = (async () => {
81
- const take = this.items.splice(0, this.batch);
82
- if (take.length === 0)
83
- return;
84
- const back = [];
85
- let index = 0;
210
+ const batches = [];
211
+ for (let i = 0; i < this.concurrency && this.items.length > 0; i++)
212
+ batches.push(this.cut());
213
+ // The gap rides on the first request (alone, if there is no record to carry it). A report sent before goes again
214
+ // exactly as it was (same id); only when none is owed do the new drops become the next report.
215
+ if (!this.sentGap && this.openGap) {
216
+ this.sentGap = { ...this.openGap, id: newGapId() };
217
+ this.openGap = undefined;
218
+ }
219
+ const gap = this.sentGap;
220
+ for (const batch of batches)
221
+ for (const item of batch)
222
+ item.tried = true;
223
+ if (batches.length === 0) {
224
+ if (!gap)
225
+ return;
226
+ batches.push([]);
227
+ }
228
+ const back = batches.map(() => []);
86
229
  let outage = false;
87
- const worker = async () => {
88
- while (index < take.length) {
89
- const item = take[index++];
90
- if (outage) {
91
- back.push(item);
92
- continue;
93
- }
94
- let result;
95
- try {
96
- result = await this.send(item.body);
97
- }
98
- catch {
99
- result = 'outage';
100
- }
101
- if (result === 'sent')
230
+ await Promise.all(batches.map(async (take, index) => {
231
+ const carry = index === 0 ? gap : undefined;
232
+ let answer;
233
+ this.requests += 1;
234
+ try {
235
+ answer = await this.send(take.map((item) => item.body), carry);
236
+ }
237
+ catch {
238
+ answer = 'outage';
239
+ }
240
+ const results = typeof answer === 'string' ? take.map(() => answer) : answer.results;
241
+ const whole = typeof answer === 'string' ? answer : undefined;
242
+ take.forEach((item, at) => {
243
+ const result = results[at] ?? whole ?? 'outage';
244
+ if (result === 'sent') {
102
245
  this.sent += 1;
103
- else if (result === 'refused')
246
+ this.pausedUntil = 0;
247
+ }
248
+ else if (result === 'refused') {
249
+ // Refused for good (a rotated or expired key, a record the API will not take): never sent again, and never
250
+ // silent: it joins the gap the next accepted upload reports ("N actions were not recorded").
104
251
  this.refused += 1;
252
+ this.openGap = mergeGap(this.openGap, { dropped: 1, from: item.at, to: item.at });
253
+ this.scheduleNotice();
254
+ }
105
255
  else {
106
256
  outage = true;
107
- back.push(item);
257
+ back[index].push(item);
258
+ }
259
+ });
260
+ if (carry) {
261
+ const accepted = typeof answer !== 'string' && answer.gapAccepted === true;
262
+ if (accepted) {
263
+ this.gapsReported += 1;
264
+ this.gapRecordsReported += carry.dropped;
265
+ this.pausedUntil = 0;
266
+ this.sentGap = undefined;
267
+ }
268
+ else {
269
+ // Not accepted (outage, an older backend): it stays owed and goes again with the same id.
270
+ if (whole === 'outage' || (typeof answer !== 'string' && answer.results.some((r) => r === 'outage')))
271
+ outage = true;
108
272
  }
109
273
  }
110
- };
111
- await Promise.all(Array.from({ length: Math.min(this.concurrency, take.length) }, worker));
112
- if (back.length > 0) {
274
+ }));
275
+ const requeue = back.flat();
276
+ if (requeue.length > 0 || outage) {
113
277
  // Keep the order: what could not be sent goes back to the front.
114
- back.sort((a, b) => take.indexOf(a) - take.indexOf(b));
115
- this.items.unshift(...back);
116
- while (this.items.length > this.max) {
117
- this.items.shift();
118
- this.lost += 1;
119
- }
278
+ const order = new Map();
279
+ batches.flat().forEach((item, at) => order.set(item, at));
280
+ requeue.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
281
+ this.items.unshift(...requeue);
282
+ while (this.items.length > this.max)
283
+ this.dropOne();
120
284
  this.pausedUntil = Date.now() + this.backoffMs;
121
285
  this.backoffMs = Math.min(BACKOFF_MAX_MS, this.backoffMs * 2);
122
286
  }
package/dist/types.d.ts CHANGED
@@ -246,7 +246,7 @@ export interface CircuitBreakerOptions {
246
246
  }
247
247
  export interface DegradeInfo {
248
248
  /** Which guard call degraded. */
249
- call: 'scan' | 'scanToolResponse' | 'scanChunks' | 'checkContext' | 'checkToolCall';
249
+ call: 'scan' | 'scanToolResponse' | 'scanChunks' | 'checkContext' | 'checkToolCall' | 'recordUpload';
250
250
  /** Why it degraded. */
251
251
  reason: string;
252
252
  /** Circuit-breaker state at the time of the degrade. */
@@ -267,6 +267,15 @@ export interface DegradeInfo {
267
267
  outcome?: 'never_allowed' | 'closed' | 'per_call' | 'would_need_manager' | 'allowed' | 'unconfirmed_monitor' | 'monitor_config_error';
268
268
  /** The never-allowed rule that blocked it (`<policyId>#<rule>`). */
269
269
  ruleId?: string;
270
+ /**
271
+ * `call: 'recordUpload'` only (`reason` starts with `records_dropped`): records of tool calls that were dropped because
272
+ * the background upload could not keep up (the queue is bounded). The calls themselves were checked and ran as usual;
273
+ * only their records are missing. `droppedRecords` and the window say how many and when; the SDK reports the same gap to
274
+ * FullCourtDefense with its next upload, and the console shows it.
275
+ */
276
+ droppedRecords?: number;
277
+ droppedFrom?: string;
278
+ droppedTo?: string;
270
279
  }
271
280
  export interface ScanMetadata {
272
281
  /** Merchant / customer identifier in the vendor's system (sent as `X-Merchant-Id`). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fullcourtdefense",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "description": "Control what your AI agents do: check every tool call against your company's FullCourtDefense policy (Monitor or Enforce).",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",