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,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WEB_BATCH_URL_LIMIT = exports.HIGH_RISK_DESTINATION_CATEGORIES = exports.DESTINATION_CATEGORY_HOSTS = exports.GCLOUD_DELETE_VERB_RE = exports.GCLOUD_WRITE_VERB_RE = exports.GCLOUD_READ_VERB_RE = exports.isSegmentedIdentifierForTest = exports.DEFAULT_ACTION_POLICY_APPROVAL = exports.CONTENT_FACT_FIELDS = exports.WORKSTATION_ASK_APPROVAL = exports.MACHINE_KINDS = exports.ACTION_POLICY_GRANT_MAX_USES = exports.ACTION_POLICY_GRANT_MAX_DAYS = void 0;
3
+ exports.WEB_BATCH_URL_LIMIT = exports.ANONYMITY_NETWORK_TLDS = exports.HIGH_RISK_DESTINATION_CATEGORIES = exports.DESTINATION_CATEGORY_HOSTS = exports.NESTED_ARGS_MAX_LEAVES = exports.NESTED_ARGS_MAX_INDEX = exports.NESTED_ARGS_MAX_DEPTH = exports.GCLOUD_DELETE_VERB_RE = exports.GCLOUD_WRITE_VERB_RE = exports.GCLOUD_READ_VERB_RE = exports.isSegmentedIdentifierForTest = exports.DEFAULT_ACTION_POLICY_APPROVAL = exports.CONTENT_FACT_FIELDS = exports.WORKSTATION_ASK_APPROVAL = exports.MACHINE_KINDS = exports.ACTION_POLICY_GRANT_MAX_USES = exports.ACTION_POLICY_GRANT_MAX_DAYS = void 0;
4
4
  exports.approvalExceptionError = approvalExceptionError;
5
5
  exports.roleExceptionError = roleExceptionError;
6
6
  exports.normalizeMachineKind = normalizeMachineKind;
@@ -24,6 +24,7 @@ exports.setShellAstMode = setShellAstMode;
24
24
  exports.getShellAstMode = getShellAstMode;
25
25
  exports.takeShellAstOperationComparison = takeShellAstOperationComparison;
26
26
  exports.evaluateActionPolicies = evaluateActionPolicies;
27
+ exports.validateArgsFieldPath = validateArgsFieldPath;
27
28
  exports.inferToolContext = inferToolContext;
28
29
  exports.destinationCategory = destinationCategory;
29
30
  exports.classifyDestinationHost = classifyDestinationHost;
@@ -5866,6 +5867,61 @@ function evaluateActionPoliciesOnce(policies, toolName, operation, context, decl
5866
5867
  }
5867
5868
  return worstResult;
5868
5869
  }
5870
+ /**
5871
+ * Nested tool arguments as constraint fields (`args.customer.tier`, `args.items.0.sku`). A constraint field is a dotted
5872
+ * path into the call's arguments: object keys and array indexes, joined by `.`. A path that is not there (a missing key, an
5873
+ * index past the end, a value that is not a string / number / boolean) is a missing fact, exactly as a missing top-level
5874
+ * field: no match. Limits, identical in every engine that decides tool calls (backend, Node SDK, Python SDK, Rust CLI;
5875
+ * sdks/shared/policy-parity/nested-args.json): at most NESTED_ARGS_MAX_DEPTH segments after `args.`, array indexes below
5876
+ * NESTED_ARGS_MAX_INDEX, NESTED_ARGS_MAX_LEAVES values per call, and a key containing `.` is not addressable.
5877
+ * `validateArgsFieldPath` is the save-time check of the same rules.
5878
+ */
5879
+ exports.NESTED_ARGS_MAX_DEPTH = 6;
5880
+ exports.NESTED_ARGS_MAX_INDEX = 100;
5881
+ exports.NESTED_ARGS_MAX_LEAVES = 256;
5882
+ /** Why a constraint field naming tool arguments cannot be evaluated by every engine, or undefined when it can. */
5883
+ function validateArgsFieldPath(field) {
5884
+ if (!field.startsWith('args.'))
5885
+ return undefined;
5886
+ const segments = field.slice(5).split('.');
5887
+ if (segments.some(segment => !/^[A-Za-z0-9_-]+$/.test(segment))) {
5888
+ return `The condition "${field}" is not a valid argument path: use letters, digits, "_" and "-" between dots, for example args.customer.tier or args.items.0.sku.`;
5889
+ }
5890
+ if (segments.length > exports.NESTED_ARGS_MAX_DEPTH) {
5891
+ return `The condition "${field}" goes ${segments.length} levels into the arguments; at most ${exports.NESTED_ARGS_MAX_DEPTH} levels can be checked.`;
5892
+ }
5893
+ if (segments.slice(1).some(segment => /^[0-9]+$/.test(segment) && Number(segment) >= exports.NESTED_ARGS_MAX_INDEX)) {
5894
+ return `The condition "${field}" names a list position of ${exports.NESTED_ARGS_MAX_INDEX} or more; only positions 0 to ${exports.NESTED_ARGS_MAX_INDEX - 1} can be checked.`;
5895
+ }
5896
+ return undefined;
5897
+ }
5898
+ /** Add `args.<path>` facts for the string / number / boolean values nested in objects and arrays of the arguments. */
5899
+ function addNestedArgFacts(context, args) {
5900
+ let leaves = 0;
5901
+ const walk = (prefix, value, depth) => {
5902
+ if (leaves >= exports.NESTED_ARGS_MAX_LEAVES || depth > exports.NESTED_ARGS_MAX_DEPTH || value === null || typeof value !== 'object')
5903
+ return;
5904
+ const entries = Array.isArray(value)
5905
+ ? value.slice(0, exports.NESTED_ARGS_MAX_INDEX).map((item, index) => [String(index), item])
5906
+ : Object.entries(value).filter(([key]) => key !== '' && !key.includes('.'));
5907
+ for (const [key, item] of entries) {
5908
+ if (leaves >= exports.NESTED_ARGS_MAX_LEAVES)
5909
+ return;
5910
+ const path = `${prefix}.${key}`;
5911
+ if (['string', 'number', 'boolean'].includes(typeof item)) {
5912
+ if (!Object.hasOwn(context, path))
5913
+ context[path] = String(item);
5914
+ leaves += 1;
5915
+ }
5916
+ else
5917
+ walk(path, item, depth + 1);
5918
+ }
5919
+ };
5920
+ for (const [key, value] of Object.entries(args)) {
5921
+ if (key !== '' && !key.includes('.'))
5922
+ walk(`args.${key}`, value, 2);
5923
+ }
5924
+ }
5869
5925
  /**
5870
5926
  * Infer operation and context from a tool call.
5871
5927
  * Handles common patterns: SQL operations, file paths, HTTP methods, etc.
@@ -5924,6 +5980,7 @@ function inferToolContext(toolName, args) {
5924
5980
  if (!reservedInputFact(key) && (LEGACY_TRUST_LABEL_ARGS.has(key) || (0, detectorRuntime_1.detectorRejectsFactName)(key)) && !Object.hasOwn(context, key))
5925
5981
  context[key] = String(value);
5926
5982
  }
5983
+ addNestedArgFacts(context, args);
5927
5984
  if (!Object.hasOwn(context, 'request.containsSecret')
5928
5985
  && recordHttpRequestFacts(context, args, extractUrl(args, argsText))) {
5929
5986
  context['destination.type'] = context['request.destination.type'];
@@ -5938,19 +5995,35 @@ exports.DESTINATION_CATEGORY_HOSTS = {
5938
5995
  paste: [
5939
5996
  'pastebin.com', 'paste.ee', 'hastebin.com', 'rentry.co', 'rentry.org', 'dpaste.org', 'dpaste.com', 'paste.rs',
5940
5997
  'termbin.com', 'controlc.com', 'justpaste.it', 'privatebin.net', 'ix.io', 'sprunge.us', 'pastes.io', 'paste.mozilla.org',
5998
+ 'clbin.com', 'paste.c-net.org', 'p.ip.fi', 'vpaste.net', 'paste.sh', 'hastebin.skyra.pw', 'ghostbin.com', 'ghostbin.co',
5999
+ '0bin.net', 'paste.gg', 'pastie.io', 'paste2.org', 'pastelink.net', 'snippet.host', 'katb.in', 'bpa.st', 'bpaste.net',
6000
+ 'paste.debian.net',
5941
6001
  ],
5942
6002
  file_drop: [
5943
6003
  'transfer.sh', 'file.io', '0x0.st', 'temp.sh', 'bashupload.com', 'gofile.io', 'catbox.moe', 'uguu.se', 'tmpfiles.org',
5944
6004
  'filebin.net', 'wetransfer.com', 'we.tl', 'sendspace.com', 'mediafire.com', 'mega.nz', 'anonfiles.com', 'oshi.at',
5945
6005
  'pixeldrain.com', 'ufile.io', 'keep.sh', 'filetransfer.io',
6006
+ 'krakenfiles.com', 'x0.at', 'qu.ax', 'tmp.ninja', 'easyupload.io', 'tempsend.com', 'send.vis.ee', 'upload.ee',
6007
+ 'fileditch.com', 'anonymfile.com', 'bayfiles.com', 'buzzheavier.com',
5946
6008
  ],
5947
6009
  request_capture: [
5948
6010
  'webhook.site', 'pipedream.net', 'beeceptor.com', 'hookbin.com', 'requestcatcher.com', 'interact.sh', 'oast.fun',
5949
6011
  'oast.pro', 'oast.live', 'oast.site', 'oast.online', 'oast.me', 'oastify.com', 'burpcollaborator.net', 'dnslog.cn', 'ceye.io',
6012
+ 'requestbin.net', 'postb.in', 'ptsv2.com', 'ptsv3.com', 'webhook.cool', 'typedwebhook.tools', 'webhook-test.com',
6013
+ 'putsreq.com', 'requestinspector.com', 'mockbin.org', 'smee.io', 'requestrepo.com',
5950
6014
  ],
5951
6015
  tunnel: [
5952
6016
  'ngrok.io', 'ngrok.app', 'ngrok.dev', 'ngrok-free.app', 'ngrok-free.dev', 'trycloudflare.com', 'loca.lt', 'localtunnel.me',
5953
6017
  'serveo.net', 'localhost.run', 'lhr.life', 'pinggy.io', 'pinggy.link', 'bore.pub',
6018
+ 'ngrok.pizza', 'ngrok-agent.com', 'argotunnel.com', 'cfargotunnel.com', 'serveousercontent.com', 'lhr.rocks',
6019
+ 'pinggy.online', 'tunnelmole.net', 'tunnelmole.com', 'zrok.io', 'pagekite.net', 'pagekite.me', 'sharedwithexpose.com',
6020
+ 'loclx.io', 'localtonet.com', 'localto.net', 'devtunnels.ms', 'gradio.live', 'pktriot.net', 'portmap.io', 'portmap.host',
6021
+ 'playit.gg', 'srv.us', 'loophole.site', 'jprq.io',
6022
+ ],
6023
+ anonymizer: [
6024
+ 'onion.ws', 'onion.pet', 'onion.ly', 'onion.to', 'onion.link', 'onion.sh', 'onion.city', 'tor2web.org', 'tor2web.io',
6025
+ 'torproject.org', 'hidester.com', 'proxysite.com', 'croxyproxy.com', 'croxyproxy.rocks', 'kproxy.com', '4everproxy.com',
6026
+ 'proxyium.com', 'blockaway.net', 'hide.me', 'anonymouse.org', 'proxyscrape.com', 'free-proxy-list.net', 'spys.one',
5954
6027
  ],
5955
6028
  messaging: ['discord.com', 'discordapp.com', 'api.telegram.org', 'hooks.slack.com'],
5956
6029
  news: [
@@ -5961,13 +6034,18 @@ exports.DESTINATION_CATEGORY_HOSTS = {
5961
6034
  'aljazeera.com',
5962
6035
  ],
5963
6036
  };
5964
- /** Categories whose purpose is to receive data from strangers: a first upload there is high risk. */
5965
- exports.HIGH_RISK_DESTINATION_CATEGORIES = new Set(['paste', 'file_drop', 'request_capture', 'tunnel']);
6037
+ /** Categories whose purpose is to receive data from strangers, or to hide where it goes: a first upload there is high risk. */
6038
+ exports.HIGH_RISK_DESTINATION_CATEGORIES = new Set(['paste', 'file_drop', 'request_capture', 'tunnel', 'anonymizer']);
6039
+ /** Top-level names that resolve only through an anonymity network (Tor onion services, I2P, Tor exit notation). */
6040
+ exports.ANONYMITY_NETWORK_TLDS = ['onion', 'i2p', 'exit'];
5966
6041
  const DESTINATION_CATEGORY_BY_HOST = new Map(Object.entries(exports.DESTINATION_CATEGORY_HOSTS)
5967
6042
  .flatMap(([category, hosts]) => hosts.map(host => [host, category])));
5968
6043
  /** The listed host itself or any subdomain of it (`www.pastebin.com`, `x.m.pipedream.net`); never a look-alike (`notpastebin.com`). */
5969
6044
  function destinationCategory(host) {
5970
6045
  let candidate = String(host || '').trim().toLowerCase().replace(/\.$/, '');
6046
+ const tld = candidate.slice(candidate.lastIndexOf('.') + 1);
6047
+ if (candidate.includes('.') && exports.ANONYMITY_NETWORK_TLDS.includes(tld))
6048
+ return 'anonymizer';
5971
6049
  while (candidate) {
5972
6050
  const category = DESTINATION_CATEGORY_BY_HOST.get(candidate);
5973
6051
  if (category)
@@ -6225,6 +6303,7 @@ function inferBundledToolContext(toolName, args) {
6225
6303
  if (!reservedInputFact(key))
6226
6304
  context[key] = String(val);
6227
6305
  }
6306
+ addNestedArgFacts(context, args);
6228
6307
  // Search-intent tools: their `query` is a text PATTERN to look for, not an action to run.
6229
6308
  // Searching a codebase for "DROP TABLE" is a read — classifying the pattern as SQL would
6230
6309
  // pause every code/document search that mentions a governed verb. The destructive-verb
@@ -94,6 +94,19 @@ const SECRET_PATTERNS = [
94
94
  { itemId: 'google_api_key', label: 'Google API key', re: /\bAIza[0-9A-Za-z_-]{35}\b/ },
95
95
  { itemId: 'huggingface_token_secret', label: 'HuggingFace token', re: /\bhf_[A-Za-z0-9]{30,}\b/ },
96
96
  { itemId: 'database_url_password', label: 'database URL with password', re: /\b(?:postgres(?:ql)?|mongodb(?:\+srv)?|mysql):\/\/[^/\s'":]+:[^@\s'"]+@/i },
97
+ // 2026-11 (DefenseClaw round 1): the formats of the backend redaction detectors (runtime/redaction-rules.json). Portions
98
+ // derived from DefenseClaw (Cisco, Apache-2.0), modified. jwt_token / bearer_token ship off (DEFAULT_DISABLED_BUILT_INS).
99
+ // Twin of fcd-guard families/secrets.rs SECRET_PATTERNS (same order).
100
+ { itemId: 'gitlab_token', label: 'GitLab token', re: /\bgl(?:pat|ptt|dt|rt|soat|cbt|imt|oas|ft|agent|ffct)-[A-Za-z0-9_-]{20,}/ },
101
+ { itemId: 'slack_webhook', label: 'Slack webhook URL', re: /\bhooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9+/_-]{20,}/ },
102
+ { itemId: 'discord_webhook', label: 'Discord webhook URL', re: /\bdiscord(?:app)?\.com\/api\/webhooks\/[0-9]{17,20}\/[A-Za-z0-9_-]{60,}/ },
103
+ { itemId: 'npm_token', label: 'npm token', re: /\bnpm_[A-Za-z0-9]{36}\b/ },
104
+ { itemId: 'pypi_token', label: 'PyPI token', re: /\bpypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,}/ },
105
+ { itemId: 'sendgrid_key', label: 'SendGrid API key', re: /\bSG\.[A-Za-z0-9_-]{16,32}\.[A-Za-z0-9_-]{16,64}/ },
106
+ { itemId: 'twilio_key', label: 'Twilio API key', re: /\bSK[0-9a-fA-F]{32}\b/ },
107
+ { itemId: 'aws_secret_key', label: 'AWS secret access key', re: /aws.{0,25}?(?:secret|private|key).{0,25}?[=:\s'"]{1,4}[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])/i },
108
+ { itemId: 'jwt_token', label: 'JSON Web Token', re: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/ },
109
+ { itemId: 'bearer_token', label: 'bearer token in an Authorization header', re: /\bauthorization["']?\s*[:=]\s*["']?bearer\s+[A-Za-z0-9._~+/-]{20,}=*/i },
97
110
  ];
98
111
  // Contextual secret detection: bare high-entropy strings (hex app secrets,
99
112
  // random tokens) have no recognizable prefix, so SECRET_PATTERNS misses them.
@@ -241,6 +254,9 @@ exports.DEFAULT_DISABLED_BUILT_INS = new Set([
241
254
  // IDE). Off by default — orgs opt in via the Local Safety console toggle,
242
255
  // which the runtime snapshot then applies on every machine.
243
256
  'contextual_secret',
257
+ // Test JWTs and bearer tokens go to a developer's own services all day: opt-in.
258
+ 'jwt_token',
259
+ 'bearer_token',
244
260
  ]);
245
261
  function evidence(value) {
246
262
  const compact = value.replace(/\s+/g, ' ').trim();
@@ -694,7 +710,169 @@ function findSecret(value) {
694
710
  }
695
711
  function containsMetadataEndpoint(value) {
696
712
  const normalized = decodeLoosely(value).toLowerCase();
697
- return METADATA_ENDPOINTS.find(endpoint => normalized.includes(endpoint.value));
713
+ return METADATA_ENDPOINTS.find(endpoint => normalized.includes(endpoint.value)) || encodedMetadataEndpoint(normalized);
714
+ }
715
+ // Portions derived from DefenseClaw (Cisco, Apache-2.0), modified: the encoded-address forms (decimal, hex, octal,
716
+ // partial dotted, IPv4-mapped IPv6 and the AWS IPv6 endpoint) follow DefenseClaw's metadata SSRF rules; the parser is
717
+ // written anew and is the twin of `encoded_metadata_endpoint` in sdks/cli/rust/crates/fcd-guard/src/families/metadata.rs.
718
+ const LINK_LOCAL_METADATA = 0xa9fea9fe;
719
+ const ALIBABA_METADATA = 0x646464c8;
720
+ const AWS_IPV6_METADATA = [0xfd00, 0xec2, 0, 0, 0, 0, 0, 0x254];
721
+ const METADATA_TOKEN_DELIMITERS = /[ \t\n\f\r"'`()<>,;|&=@\\{}]+/;
722
+ /**
723
+ * A host written as an encoded metadata address. A single number (`2852039166`, `0xa9fea9fe`) counts only in host
724
+ * position (after `scheme://`, or followed by a path or a port); dotted forms with octal / hex / fewer parts and IPv6
725
+ * forms count as tokens anywhere (they equal the metadata address exactly).
726
+ */
727
+ function encodedMetadataEndpoint(normalized) {
728
+ if (!/[0-9]/.test(normalized))
729
+ return undefined;
730
+ const linkLocal = METADATA_ENDPOINTS[0];
731
+ const alibaba = METADATA_ENDPOINTS[3];
732
+ const byIpv6 = (h) => {
733
+ if (!h)
734
+ return undefined;
735
+ if (h.every((v, i) => v === AWS_IPV6_METADATA[i]))
736
+ return linkLocal;
737
+ const mapped = h.slice(0, 5).every(v => v === 0) && h[5] === 0xffff ? h[6] * 65536 + h[7] : undefined;
738
+ return mapped === LINK_LOCAL_METADATA ? linkLocal : mapped === ALIBABA_METADATA ? alibaba : undefined;
739
+ };
740
+ for (const raw of normalized.split(METADATA_TOKEN_DELIMITERS)) {
741
+ if (!raw)
742
+ continue;
743
+ let token = raw;
744
+ let hostPosition = false;
745
+ const rest = stripUrlScheme(token);
746
+ if (rest !== undefined) {
747
+ token = rest;
748
+ hostPosition = true;
749
+ }
750
+ if (token.startsWith('[')) {
751
+ const end = token.indexOf(']', 1);
752
+ if (end < 0)
753
+ continue;
754
+ const hit = byIpv6(ipv6Hextets(token.slice(1, end)));
755
+ if (hit)
756
+ return hit;
757
+ continue;
758
+ }
759
+ const cut = token.search(/[/?#]/);
760
+ let host = token;
761
+ if (cut >= 0) {
762
+ hostPosition = true;
763
+ host = token.slice(0, cut);
764
+ }
765
+ if ((host.match(/:/g) || []).length >= 2) {
766
+ const hit = byIpv6(ipv6Hextets(host));
767
+ if (hit)
768
+ return hit;
769
+ continue;
770
+ }
771
+ const colon = host.indexOf(':');
772
+ if (colon >= 0) {
773
+ const port = host.slice(colon + 1);
774
+ if (!/^[0-9]{1,5}$/.test(port))
775
+ continue;
776
+ hostPosition = true;
777
+ host = host.slice(0, colon);
778
+ }
779
+ const value = inetAton(host);
780
+ if (value === undefined || (!host.includes('.') && !hostPosition))
781
+ continue;
782
+ if (value === LINK_LOCAL_METADATA)
783
+ return linkLocal;
784
+ if (value === ALIBABA_METADATA)
785
+ return alibaba;
786
+ }
787
+ return undefined;
788
+ }
789
+ /** `token` without a leading `scheme://` or `//` (undefined: there is none). */
790
+ function stripUrlScheme(token) {
791
+ if (token.startsWith('//'))
792
+ return token.slice(2);
793
+ const at = token.indexOf('://');
794
+ if (at < 0)
795
+ return undefined;
796
+ return /^[a-z][a-z0-9+.-]*$/.test(token.slice(0, at)) ? token.slice(at + 3) : undefined;
797
+ }
798
+ /** The BSD `inet_aton` value of a 1-4 part numeric host (decimal, `0x` hex or `0` octal parts; the last fills the rest). */
799
+ function inetAton(host) {
800
+ if (!host || !/^[0-9a-fx.]+$/.test(host))
801
+ return undefined;
802
+ const parts = host.split('.');
803
+ if (parts.length > 4)
804
+ return undefined;
805
+ const values = [];
806
+ for (const part of parts) {
807
+ if (!part || part.length > 12)
808
+ return undefined;
809
+ if (part.startsWith('0x')) {
810
+ if (!/^0x[0-9a-f]+$/.test(part))
811
+ return undefined;
812
+ values.push(parseInt(part.slice(2), 16));
813
+ }
814
+ else if (part.startsWith('0')) {
815
+ if (!/^[0-7]+$/.test(part))
816
+ return undefined;
817
+ values.push(parseInt(part, 8));
818
+ }
819
+ else {
820
+ if (!/^[0-9]+$/.test(part))
821
+ return undefined;
822
+ values.push(Number(part));
823
+ }
824
+ }
825
+ const last = values[values.length - 1];
826
+ const head = values.slice(0, -1);
827
+ let value = 0;
828
+ for (let i = 0; i < head.length; i++) {
829
+ if (head[i] > 255)
830
+ return undefined;
831
+ value += head[i] * Math.pow(256, 3 - i);
832
+ }
833
+ if (last >= Math.pow(2, 8 * (4 - head.length)))
834
+ return undefined;
835
+ return value + last;
836
+ }
837
+ /** The eight hextets of an IPv6 address (`::` once, an IPv4 tail allowed, a `%zone` dropped). */
838
+ function ipv6Hextets(input) {
839
+ const text = input.split('%')[0];
840
+ const at = text.indexOf('::');
841
+ const head = at >= 0 ? text.slice(0, at) : text;
842
+ const tail = at >= 0 ? text.slice(at + 2) : undefined;
843
+ const groups = (s) => {
844
+ if (!s)
845
+ return [];
846
+ const out = [];
847
+ const pieces = s.split(':');
848
+ for (let i = 0; i < pieces.length; i++) {
849
+ const p = pieces[i];
850
+ if (i + 1 === pieces.length && p.includes('.')) {
851
+ const m = /^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.exec(p);
852
+ if (!m || m.slice(1).some(o => Number(o) > 255))
853
+ return undefined;
854
+ out.push(Number(m[1]) * 256 + Number(m[2]), Number(m[3]) * 256 + Number(m[4]));
855
+ }
856
+ else {
857
+ if (!/^[0-9a-f]{1,4}$/.test(p))
858
+ return undefined;
859
+ out.push(parseInt(p, 16));
860
+ }
861
+ }
862
+ return out;
863
+ };
864
+ const left = groups(head);
865
+ if (!left)
866
+ return undefined;
867
+ if (tail !== undefined && tail.includes('::'))
868
+ return undefined;
869
+ const right = tail !== undefined ? groups(tail) : [];
870
+ if (!right)
871
+ return undefined;
872
+ const total = left.length + right.length;
873
+ if ((tail === undefined && total !== 8) || (tail !== undefined && total > 7))
874
+ return undefined;
875
+ return [...left, ...new Array(8 - total).fill(0), ...right];
698
876
  }
699
877
  function containsSensitiveCredentialPath(value) {
700
878
  const text = normalizeForPath(value);
@@ -1,53 +1,108 @@
1
- /**
2
- * The records of locally decided tool calls (owner order 2026-11-01): queued in memory and sent in the
3
- * background, in small batches, to the existing record endpoint (`POST /api/agent-security/runtime/tool-call`).
4
- * Nothing here is ever awaited on a tool call's path.
5
- *
6
- * - bounded: past `max` the OLDEST record is dropped and counted (`lost`), never the agent's memory;
7
- * - coalesced: a push schedules one send `delayMs` later, so a burst goes out as one batch of up to `batch`
8
- * records, `concurrency` requests at a time;
9
- * - outage: a record the API did not answer (no answer, timeout, 408, 429, 5xx) goes back to the FRONT of
10
- * the queue and sending pauses (1 s doubling to 30 s, or until `resume()`: the bundle refresh answered);
11
- * - a definite refusal (another 4xx) drops that record: resending it would be refused again;
12
- * - exit: `flush()` sends everything now (the caller bounds the wait), `drain()` hands what is left to the
13
- * local spool (recordSpool.ts) so the next process sends it.
14
- */
15
1
  export interface QueuedRecord {
16
2
  body: Record<string, unknown>;
17
3
  at: string;
4
+ /** JSON size of the body, measured once when a batch is cut. */
5
+ bytes?: number;
6
+ /** Sent at least once (the API may hold it even if its answer never came): never dropped before a record that was not. */
7
+ tried?: boolean;
18
8
  }
19
9
  export type SendOutcome = 'sent' | 'outage' | 'refused';
10
+ /** Records dropped before they could be sent: how many, and when the first and the last of them were made. */
11
+ export interface RecordGap {
12
+ dropped: number;
13
+ from: string;
14
+ to: string;
15
+ /**
16
+ * Set when the report is first sent, and kept on every resend: the backend stores one gap per id, so a report the API
17
+ * stored but answered too late for is not added a second time.
18
+ */
19
+ id?: string;
20
+ }
21
+ /** What a batch send answers: one outcome per record, and whether the backend took the gap that came with it. */
22
+ export interface BatchAnswer {
23
+ results: SendOutcome[];
24
+ gapAccepted?: boolean;
25
+ }
26
+ /** Sends one batch (and the gap riding on it, if any). A single outcome stands for every record of the batch. May reject: that is an outage. */
27
+ export type BatchSender = (bodies: Record<string, unknown>[], gap?: RecordGap) => Promise<BatchAnswer | SendOutcome>;
20
28
  export interface RecordQueueOptions {
21
29
  max?: number;
30
+ /** Most records in one request. */
22
31
  batch?: number;
32
+ /** Most JSON bytes in one request (a lone larger record still goes alone). */
33
+ maxBytes?: number;
34
+ /** Requests in flight at once. */
23
35
  concurrency?: number;
24
36
  delayMs?: number;
37
+ /** Called (off the caller's path, at most once per `dropNoticeMs`) while records are being dropped. */
38
+ onDrop?: (info: {
39
+ dropped: number;
40
+ from: string;
41
+ to: string;
42
+ }) => void;
43
+ dropNoticeMs?: number;
25
44
  }
45
+ /** Longest one `flush()` waits: a serverless handler calls it at its end and must not hang. */
46
+ export declare const FLUSH_MAX_MS = 2000;
47
+ export declare const DEFAULT_BATCH_RECORDS = 100;
48
+ export declare const DEFAULT_BATCH_BYTES: number;
49
+ export declare const DEFAULT_CONCURRENCY = 3;
26
50
  export declare class RecordQueue {
27
51
  private readonly send;
28
52
  private readonly items;
29
53
  private readonly max;
30
54
  private readonly batch;
55
+ private readonly maxBytes;
31
56
  private readonly concurrency;
32
57
  private readonly delayMs;
58
+ private readonly onDrop?;
59
+ private readonly dropNoticeMs;
33
60
  private timer?;
61
+ private noticeTimer?;
62
+ private lastNoticeAt;
34
63
  private running?;
35
64
  private pausedUntil;
36
65
  private backoffMs;
37
- /** Records dropped because the queue was full (oldest first). */
66
+ /** Dropped and not yet in a report (new drops add up here). */
67
+ private openGap?;
68
+ /** A report already sent once (it has its id) and not yet accepted: resent as it is, never merged with new drops. */
69
+ private sentGap?;
70
+ /** Records dropped since the start (observability, tests). */
38
71
  lost: number;
39
72
  /** Records sent / refused since the start (observability, tests). */
40
73
  sent: number;
41
74
  refused: number;
42
- constructor(send: (body: Record<string, unknown>) => Promise<SendOutcome>, options?: RecordQueueOptions);
75
+ /** Gaps the backend accepted, and the records they covered. */
76
+ gapsReported: number;
77
+ gapRecordsReported: number;
78
+ /** Requests made (observability: records per request is what batching buys). */
79
+ requests: number;
80
+ constructor(send: BatchSender, options?: RecordQueueOptions);
43
81
  get size(): number;
82
+ /** Records dropped that no accepted upload has reported yet (zero: nothing is missing, or the console already says so). */
83
+ get unreportedLoss(): number;
84
+ /** Everything dropped and not yet accepted, as one window (the app's notice, the spool at exit). */
85
+ private owedGap;
86
+ /**
87
+ * The record that gives way when the queue is full: the oldest one that was never sent. A record sent once stays (the
88
+ * API may already hold it; it is sent again and stored once, by its id), so every dropped record is one the API never
89
+ * saw and the gap is exact. Records sent once are at the front and are at most one round of batches.
90
+ */
91
+ private dropOne;
44
92
  push(body: Record<string, unknown>): void;
93
+ /** Records that cannot be queued any more: counted, kept as a gap, and the app told (off this call's path). */
94
+ private noteDrop;
95
+ private scheduleNotice;
45
96
  /** The API answered again (a bundle refresh): send now instead of waiting out the backoff. */
46
97
  resume(): void;
47
- /** Send everything queued now (exit); resolves when every batch was tried once. Never rejects. */
48
- flush(): Promise<void>;
98
+ /** One bounded attempt to send everything queued (exit, end of a serverless handler); never rejects, never waits past FLUSH_MAX_MS. */
99
+ flush(maxMs?: number): Promise<void>;
49
100
  /** Everything still queued, removed from the queue (handed to the local spool at exit). */
50
101
  drain(): QueuedRecord[];
102
+ /** The gap not yet reported, removed (handed to the local spool at exit, so the next process reports it). */
103
+ takeGap(): RecordGap | undefined;
51
104
  private schedule;
105
+ /** The next batch: up to `batch` records and `maxBytes` of JSON, at least one record. */
106
+ private cut;
52
107
  private runOnce;
53
108
  }