@pinta-ai/mcp-logger 0.4.1 → 0.4.2-dev.1010

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 (92) hide show
  1. package/dist/cli/index.js +1 -1
  2. package/node_modules/@pinta-ai/core/README.md +180 -0
  3. package/node_modules/@pinta-ai/core/dist/atomic-write.d.ts +9 -0
  4. package/node_modules/@pinta-ai/core/dist/atomic-write.d.ts.map +1 -0
  5. package/node_modules/@pinta-ai/core/dist/atomic-write.js +20 -0
  6. package/node_modules/@pinta-ai/core/dist/atomic-write.js.map +1 -0
  7. package/node_modules/@pinta-ai/core/dist/credential-semantics.d.ts +20 -0
  8. package/node_modules/@pinta-ai/core/dist/credential-semantics.d.ts.map +1 -0
  9. package/node_modules/@pinta-ai/core/dist/credential-semantics.js +156 -0
  10. package/node_modules/@pinta-ai/core/dist/credential-semantics.js.map +1 -0
  11. package/node_modules/@pinta-ai/core/dist/env-file.d.ts +17 -0
  12. package/node_modules/@pinta-ai/core/dist/env-file.d.ts.map +1 -0
  13. package/node_modules/@pinta-ai/core/dist/env-file.js +81 -0
  14. package/node_modules/@pinta-ai/core/dist/env-file.js.map +1 -0
  15. package/node_modules/@pinta-ai/core/dist/export-mask.d.ts +26 -0
  16. package/node_modules/@pinta-ai/core/dist/export-mask.d.ts.map +1 -0
  17. package/node_modules/@pinta-ai/core/dist/export-mask.js +202 -0
  18. package/node_modules/@pinta-ai/core/dist/export-mask.js.map +1 -0
  19. package/node_modules/@pinta-ai/core/dist/guard.d.ts +196 -0
  20. package/node_modules/@pinta-ai/core/dist/guard.d.ts.map +1 -0
  21. package/node_modules/@pinta-ai/core/dist/guard.js +275 -0
  22. package/node_modules/@pinta-ai/core/dist/guard.js.map +1 -0
  23. package/node_modules/@pinta-ai/core/dist/index.d.ts +23 -0
  24. package/node_modules/@pinta-ai/core/dist/index.d.ts.map +1 -0
  25. package/node_modules/@pinta-ai/core/dist/index.js +85 -0
  26. package/node_modules/@pinta-ai/core/dist/index.js.map +1 -0
  27. package/node_modules/@pinta-ai/core/dist/json-text.d.ts +45 -0
  28. package/node_modules/@pinta-ai/core/dist/json-text.d.ts.map +1 -0
  29. package/node_modules/@pinta-ai/core/dist/json-text.js +116 -0
  30. package/node_modules/@pinta-ai/core/dist/json-text.js.map +1 -0
  31. package/node_modules/@pinta-ai/core/dist/lifecycle.d.ts +143 -0
  32. package/node_modules/@pinta-ai/core/dist/lifecycle.d.ts.map +1 -0
  33. package/node_modules/@pinta-ai/core/dist/lifecycle.js +20 -0
  34. package/node_modules/@pinta-ai/core/dist/lifecycle.js.map +1 -0
  35. package/node_modules/@pinta-ai/core/dist/matches.d.ts +24 -0
  36. package/node_modules/@pinta-ai/core/dist/matches.d.ts.map +1 -0
  37. package/node_modules/@pinta-ai/core/dist/matches.js +39 -0
  38. package/node_modules/@pinta-ai/core/dist/matches.js.map +1 -0
  39. package/node_modules/@pinta-ai/core/dist/mysql-password.d.ts +15 -0
  40. package/node_modules/@pinta-ai/core/dist/mysql-password.d.ts.map +1 -0
  41. package/node_modules/@pinta-ai/core/dist/mysql-password.js +375 -0
  42. package/node_modules/@pinta-ai/core/dist/mysql-password.js.map +1 -0
  43. package/node_modules/@pinta-ai/core/dist/otlp-types.d.ts +41 -0
  44. package/node_modules/@pinta-ai/core/dist/otlp-types.d.ts.map +1 -0
  45. package/node_modules/@pinta-ai/core/dist/otlp-types.js +7 -0
  46. package/node_modules/@pinta-ai/core/dist/otlp-types.js.map +1 -0
  47. package/node_modules/@pinta-ai/core/dist/otlp.d.ts +142 -0
  48. package/node_modules/@pinta-ai/core/dist/otlp.d.ts.map +1 -0
  49. package/node_modules/@pinta-ai/core/dist/otlp.js +638 -0
  50. package/node_modules/@pinta-ai/core/dist/otlp.js.map +1 -0
  51. package/node_modules/@pinta-ai/core/dist/output-denial.d.ts +69 -0
  52. package/node_modules/@pinta-ai/core/dist/output-denial.d.ts.map +1 -0
  53. package/node_modules/@pinta-ai/core/dist/output-denial.js +105 -0
  54. package/node_modules/@pinta-ai/core/dist/output-denial.js.map +1 -0
  55. package/node_modules/@pinta-ai/core/dist/redact.d.ts +65 -0
  56. package/node_modules/@pinta-ai/core/dist/redact.d.ts.map +1 -0
  57. package/node_modules/@pinta-ai/core/dist/redact.js +193 -0
  58. package/node_modules/@pinta-ai/core/dist/redact.js.map +1 -0
  59. package/node_modules/@pinta-ai/core/dist/retry-queue.d.ts +47 -0
  60. package/node_modules/@pinta-ai/core/dist/retry-queue.d.ts.map +1 -0
  61. package/node_modules/@pinta-ai/core/dist/retry-queue.js +177 -0
  62. package/node_modules/@pinta-ai/core/dist/retry-queue.js.map +1 -0
  63. package/node_modules/@pinta-ai/core/dist/secret-shapes.d.ts +47 -0
  64. package/node_modules/@pinta-ai/core/dist/secret-shapes.d.ts.map +1 -0
  65. package/node_modules/@pinta-ai/core/dist/secret-shapes.js +377 -0
  66. package/node_modules/@pinta-ai/core/dist/secret-shapes.js.map +1 -0
  67. package/node_modules/@pinta-ai/core/dist/session-trace.d.ts +50 -0
  68. package/node_modules/@pinta-ai/core/dist/session-trace.d.ts.map +1 -0
  69. package/node_modules/@pinta-ai/core/dist/session-trace.js +103 -0
  70. package/node_modules/@pinta-ai/core/dist/session-trace.js.map +1 -0
  71. package/node_modules/@pinta-ai/core/dist/shape-rules.d.ts +117 -0
  72. package/node_modules/@pinta-ai/core/dist/shape-rules.d.ts.map +1 -0
  73. package/node_modules/@pinta-ai/core/dist/shape-rules.js +592 -0
  74. package/node_modules/@pinta-ai/core/dist/shape-rules.js.map +1 -0
  75. package/node_modules/@pinta-ai/core/dist/trace.d.ts +17 -0
  76. package/node_modules/@pinta-ai/core/dist/trace.d.ts.map +1 -0
  77. package/node_modules/@pinta-ai/core/dist/trace.js +78 -0
  78. package/node_modules/@pinta-ai/core/dist/trace.js.map +1 -0
  79. package/node_modules/@pinta-ai/core/dist/transport.d.ts +75 -0
  80. package/node_modules/@pinta-ai/core/dist/transport.d.ts.map +1 -0
  81. package/node_modules/@pinta-ai/core/dist/transport.js +260 -0
  82. package/node_modules/@pinta-ai/core/dist/transport.js.map +1 -0
  83. package/node_modules/@pinta-ai/core/dist/value-copies.d.ts +46 -0
  84. package/node_modules/@pinta-ai/core/dist/value-copies.d.ts.map +1 -0
  85. package/node_modules/@pinta-ai/core/dist/value-copies.js +279 -0
  86. package/node_modules/@pinta-ai/core/dist/value-copies.js.map +1 -0
  87. package/node_modules/@pinta-ai/core/dist/value-masking.d.ts +22 -0
  88. package/node_modules/@pinta-ai/core/dist/value-masking.d.ts.map +1 -0
  89. package/node_modules/@pinta-ai/core/dist/value-masking.js +243 -0
  90. package/node_modules/@pinta-ai/core/dist/value-masking.js.map +1 -0
  91. package/node_modules/@pinta-ai/core/package.json +50 -0
  92. package/package.json +3 -1
@@ -0,0 +1,638 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MAX_SPAN_BYTES = void 0;
7
+ exports.ulidToTraceId = ulidToTraceId;
8
+ exports.newSpanId = newSpanId;
9
+ exports.snakeCase = snakeCase;
10
+ exports.guardVersionOf = guardVersionOf;
11
+ exports.toOtlpValue = toOtlpValue;
12
+ exports.attrsFromRecord = attrsFromRecord;
13
+ exports.guardAttrs = guardAttrs;
14
+ exports.clientAttrs = clientAttrs;
15
+ exports.enforceSpanBudget = enforceSpanBudget;
16
+ exports.buildPayload = buildPayload;
17
+ exports.attachGuard = attachGuard;
18
+ exports.mergeBatch = mergeBatch;
19
+ const crypto_1 = __importDefault(require("crypto"));
20
+ const matches_js_1 = require("./matches.js");
21
+ const redact_js_1 = require("./redact.js");
22
+ const json_text_js_1 = require("./json-text.js");
23
+ const value_copies_js_1 = require("./value-copies.js");
24
+ const export_mask_js_1 = require("./export-mask.js");
25
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
26
+ /**
27
+ * Convert a 26-char Crockford ULID into 32 lowercase hex chars (16 bytes)
28
+ * suitable for an OTLP traceId. Decoding is straightforward because each
29
+ * Crockford char carries 5 bits and 26 chars = 130 bits; we keep the low
30
+ * 128 bits (the spec already pads timestamp+randomness into 128 bits).
31
+ */
32
+ function ulidToTraceId(ulid) {
33
+ if (ulid.length !== 26) {
34
+ throw new Error(`ulidToTraceId: expected 26 chars, got ${ulid.length}`);
35
+ }
36
+ // Decode to a BigInt then to 16-byte big-endian buffer.
37
+ let n = 0n;
38
+ for (const ch of ulid) {
39
+ const idx = CROCKFORD.indexOf(ch);
40
+ if (idx < 0)
41
+ throw new Error(`ulidToTraceId: invalid Crockford char "${ch}"`);
42
+ n = (n << 5n) | BigInt(idx);
43
+ }
44
+ // Mask to 128 bits (drop the top 2 bits of the 130-bit decode).
45
+ const mask = (1n << 128n) - 1n;
46
+ n &= mask;
47
+ // Render as 32 hex chars, lowercase.
48
+ return n.toString(16).padStart(32, "0");
49
+ }
50
+ /** Generate a fresh 16-hex-char (8-byte) span ID. */
51
+ function newSpanId() {
52
+ return crypto_1.default.randomBytes(8).toString("hex");
53
+ }
54
+ /** "PreToolUse" → "pre_tool_use". */
55
+ function snakeCase(name) {
56
+ return name
57
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
58
+ .replace(/([A-Z])([A-Z][a-z])/g, "$1_$2")
59
+ .toLowerCase();
60
+ }
61
+ const EMPTY_SET = new Set();
62
+ const NO_MATCHES = [];
63
+ // Non-serializable provenance survives the adapters' shallow attribute copies.
64
+ // Build copies only masked values into the payload, not these original input objects.
65
+ const stringSources = new WeakMap();
66
+ const outputSources = new WeakMap();
67
+ /** How a payload's text is masked, kept for `attachGuard`. */
68
+ const payloadMaskers = new WeakMap();
69
+ /** The text the guard judges when it differs from the text stored (see `buildPayload`). */
70
+ const guardVersions = new WeakMap();
71
+ /**
72
+ * The version of `payload` the guard judges, or the payload itself. `buildPayload`
73
+ * returns the version that is stored; the guard sees the one built with the
74
+ * masker `pinta-core` has always used, so its verdicts do not move.
75
+ */
76
+ function guardVersionOf(payload) {
77
+ return guardVersions.get(payload) ?? payload;
78
+ }
79
+ function sourceText(value) {
80
+ if (typeof value === "string")
81
+ return value;
82
+ try {
83
+ return JSON.stringify(value);
84
+ }
85
+ catch (error) {
86
+ if (!(error instanceof TypeError))
87
+ throw error;
88
+ return String(value);
89
+ }
90
+ }
91
+ /** Some, but not all, of `range` lies inside the (merged, sorted) `replaced` ranges. */
92
+ function partlyReplaced(replaced, range) {
93
+ let covered = 0;
94
+ // `replaced` is merged and sorted, so its ends are sorted too: binary-search the first one that reaches `range`.
95
+ let lo = 0;
96
+ let hi = replaced.length;
97
+ while (lo < hi) {
98
+ const mid = (lo + hi) >>> 1;
99
+ if (replaced[mid].replaceEnd <= range.replaceStart)
100
+ lo = mid + 1;
101
+ else
102
+ hi = mid;
103
+ }
104
+ for (let i = lo; i < replaced.length; i++) {
105
+ const r = replaced[i];
106
+ if (r.replaceStart >= range.replaceEnd)
107
+ break;
108
+ covered += Math.max(0, Math.min(range.replaceEnd, r.replaceEnd) - Math.max(range.replaceStart, r.replaceStart));
109
+ }
110
+ return covered > 0 && covered < range.replaceEnd - range.replaceStart;
111
+ }
112
+ /** JSON text of an object value, or undefined when it cannot be serialized (cycle, BigInt). */
113
+ function jsonText(value) {
114
+ try {
115
+ return JSON.stringify(value);
116
+ }
117
+ catch (error) {
118
+ if (!(error instanceof TypeError))
119
+ throw error;
120
+ return undefined;
121
+ }
122
+ }
123
+ function stringValue(key, raw, policy, json) {
124
+ const context = (policy.bashContextKeys ?? EMPTY_SET).has(key) ? "bash" : undefined;
125
+ const skip = (policy.skipRedactKeys ?? EMPTY_SET).has(key);
126
+ const main = skip ? NO_MATCHES : (0, redact_js_1.collectMatches)(raw, { context });
127
+ const detections = main.map((match) => ({ value: raw.slice(match.replaceStart, match.replaceEnd), type: match.type }));
128
+ let scan = export_mask_js_1.NO_EXPORT_SCAN;
129
+ if (!skip && raw.length > 0) {
130
+ try {
131
+ scan = (0, export_mask_js_1.scanExport)(raw, main, json ?? (0, json_text_js_1.looksLikeJson)(raw), context);
132
+ }
133
+ catch {
134
+ // The stored span keeps main's masking alone; the hook must still answer.
135
+ scan = export_mask_js_1.NO_EXPORT_SCAN;
136
+ }
137
+ }
138
+ const value = { stringValue: (0, redact_js_1.truncate)((0, matches_js_1.applyMatches)(raw, (0, matches_js_1.resolveOverlaps)(main))) };
139
+ stringSources.set(value, {
140
+ original: raw,
141
+ main,
142
+ detections,
143
+ copyValues: detections.filter((_, index) => !main[index].fake),
144
+ export: scan,
145
+ });
146
+ return value;
147
+ }
148
+ /**
149
+ * Convert a JS value into an OTLP attribute value (with redaction/truncation
150
+ * applied to strings). `key` is the final attribute key. Returns null to omit.
151
+ */
152
+ function toOtlpValue(key, v, policy = {}) {
153
+ if (v === null || v === undefined)
154
+ return null;
155
+ let value;
156
+ switch (typeof v) {
157
+ case "string":
158
+ value = stringValue(key, v, policy);
159
+ break;
160
+ case "boolean":
161
+ value = { boolValue: v };
162
+ break;
163
+ case "number":
164
+ value = Number.isInteger(v) ? { intValue: v } : { doubleValue: v };
165
+ break;
166
+ case "object": {
167
+ const text = jsonText(v);
168
+ value = stringValue(key, text ?? String(v), policy, text !== undefined);
169
+ break;
170
+ }
171
+ default:
172
+ value = stringValue(key, String(v), policy);
173
+ }
174
+ const outputText = sourceText(policy.outputForKey?.(key, v));
175
+ if (outputText !== undefined)
176
+ outputSources.set(value, outputText);
177
+ return value;
178
+ }
179
+ /**
180
+ * Flatten a record into prefixed OTLP attributes, applying the redaction
181
+ * pipeline. Each adapter passes its own `prefix` (e.g. "cc") and policy.
182
+ * Keys are emitted as `<prefix>.<recordKey>`; null/undefined values are omitted.
183
+ */
184
+ function attrsFromRecord(record, prefix, policy = {}) {
185
+ const out = [];
186
+ for (const [k, v] of Object.entries(record)) {
187
+ const key = `${prefix}.${k}`;
188
+ const value = toOtlpValue(key, v, policy);
189
+ if (value === null)
190
+ continue;
191
+ out.push({ key, value });
192
+ }
193
+ return out;
194
+ }
195
+ /** Build the standard pinta.guard.* attributes from a guard result. */
196
+ function guardAttrs(guard) {
197
+ const out = [
198
+ { key: "pinta.guard.decision", value: { stringValue: guard.decision.toLowerCase() } },
199
+ { key: "pinta.guard.duration_ms", value: { intValue: guard.durationMs } },
200
+ ];
201
+ if (guard.reason && !guard.holdReason) {
202
+ out.push({ key: "pinta.guard.matched_rule", value: { stringValue: guard.reason } });
203
+ }
204
+ if (guard.failOpenReason) {
205
+ out.push({ key: "pinta.guard.fail_open_reason", value: { stringValue: guard.failOpenReason } });
206
+ }
207
+ if (guard.assessment) {
208
+ out.push({ key: "pinta.guard.assessment_status", value: { stringValue: guard.assessment.status } });
209
+ }
210
+ if (guard.holdReason) {
211
+ out.push({ key: "pinta.guard.hold_reason", value: { stringValue: guard.holdReason } });
212
+ }
213
+ return out;
214
+ }
215
+ /**
216
+ * Build the `pinta.client.*` attributes describing how long *this* client waited
217
+ * on a sidecar call. The sidecar can only time its own handler, so it cannot see
218
+ * the transport/IPC overhead; reporting our wall-clock lets it derive that.
219
+ *
220
+ * Note `op: "trace_post"` is intentionally not emitted automatically: a trace
221
+ * POST's RTT is only known once the POST completes, by which point its spans are
222
+ * already on the wire (and may be re-batched by the retry queue), so it could
223
+ * only ride a later batch. `op: "guard"` has no such lag — the guard call is
224
+ * awaited before the span is built.
225
+ */
226
+ function clientAttrs(timing) {
227
+ return [
228
+ {
229
+ key: "pinta.client.rtt_ms",
230
+ value: Number.isInteger(timing.rttMs) ? { intValue: timing.rttMs } : { doubleValue: timing.rttMs },
231
+ },
232
+ { key: "pinta.client.op", value: { stringValue: timing.op } },
233
+ ];
234
+ }
235
+ /**
236
+ * Per-span byte budget, enforced by `buildPayload`.
237
+ *
238
+ * Sits under the transport's per-POST budget (`MAX_POST_BYTES`, 900 KiB —
239
+ * itself sized against aware-backend's 1,000,000 B `POST /traces` bodyLimit)
240
+ * with headroom for the resource/scope envelope. Without this, per-string
241
+ * truncation alone (`MAX_BYTES`, 100 KiB) lets a span with ~10 payload
242
+ * attributes exceed what the backend will ever accept, and such a span is
243
+ * indivisible downstream — it can only be dropped whole.
244
+ */
245
+ exports.MAX_SPAN_BYTES = 800 * 1024;
246
+ function byteLen(value) {
247
+ const json = JSON.stringify(value);
248
+ return json === undefined ? 0 : Buffer.byteLength(json, "utf-8");
249
+ }
250
+ /** Never shave an attribute below this — the win no longer matters. */
251
+ const MIN_ATTR_KEEP_BYTES = 1024;
252
+ /**
253
+ * Shrink a span in place until it serializes to <= `maxBytes`, by re-truncating
254
+ * its largest string attributes (largest first). Non-string values, keys, and
255
+ * already-small strings are left untouched. Gives up (span stays oversized)
256
+ * only when no truncatable string above `MIN_ATTR_KEEP_BYTES` remains — the
257
+ * transport then drops it with a diagnostic instead of poisoning a batch.
258
+ */
259
+ function enforceSpanBudget(span, maxBytes = exports.MAX_SPAN_BYTES) {
260
+ let size = byteLen(span);
261
+ // Bounded loop: each pass strictly shrinks the largest attribute, but JSON
262
+ // escaping means raw-string bytes underestimate serialized bytes, so a
263
+ // single pass may not land under budget.
264
+ for (let pass = 0; pass < 100 && size > maxBytes; pass++) {
265
+ let largestValue = null;
266
+ let largest = 0;
267
+ for (const attr of span.attributes) {
268
+ if (!("stringValue" in attr.value))
269
+ continue;
270
+ const bytes = Buffer.byteLength(attr.value.stringValue, "utf-8");
271
+ if (bytes > largest) {
272
+ largest = bytes;
273
+ largestValue = attr.value;
274
+ }
275
+ }
276
+ if (largestValue === null || largest <= MIN_ATTR_KEEP_BYTES)
277
+ break;
278
+ const overshoot = size - maxBytes;
279
+ // 64 B slack for the truncation marker and escape-length drift.
280
+ const target = Math.max(MIN_ATTR_KEEP_BYTES, largest - overshoot - 64);
281
+ largestValue.stringValue = (0, redact_js_1.truncateTo)(largestValue.stringValue, target);
282
+ size = byteLen(span);
283
+ }
284
+ return span;
285
+ }
286
+ const marker = (m) => m.replacement ?? `[REDACTED:${m.type}]`;
287
+ /** Number of leading characters of `text` that fit in `bytes` UTF-8 bytes (a split character is left out). */
288
+ function charsWithin(text, bytes) {
289
+ if (bytes <= 0)
290
+ return 0;
291
+ if (Buffer.byteLength(text, "utf-8") <= bytes)
292
+ return text.length;
293
+ const head = Buffer.from(text, "utf-8").subarray(0, bytes).toString("utf-8");
294
+ return head.endsWith("\uFFFD") && !text.startsWith(head) ? head.length - 1 : head.length;
295
+ }
296
+ /**
297
+ * How much of the original text the guard's first `MAX_BYTES` bytes cover.
298
+ * `edits` are the places the guard text replaced; a cut that falls inside one
299
+ * takes the whole place in.
300
+ */
301
+ function guardCut(original, edits) {
302
+ let at = 0;
303
+ let used = 0;
304
+ for (const m of edits) {
305
+ const segment = original.slice(at, m.replaceStart);
306
+ const bytes = Buffer.byteLength(segment, "utf-8");
307
+ if (used + bytes >= redact_js_1.MAX_BYTES)
308
+ return at + charsWithin(segment, redact_js_1.MAX_BYTES - used);
309
+ used += bytes;
310
+ used += Buffer.byteLength(marker(m), "utf-8");
311
+ if (used > redact_js_1.MAX_BYTES)
312
+ return m.replaceEnd;
313
+ at = m.replaceEnd;
314
+ }
315
+ return at + charsWithin(original.slice(at), redact_js_1.MAX_BYTES - used);
316
+ }
317
+ /**
318
+ * The stored text of one attribute: the original with the ranges replaced. The
319
+ * guard's text decides whether it is cut (`guardBytes`, its size before the cut);
320
+ * when it is, the stored text keeps the same part of the original, masked, and
321
+ * ends with the same marker.
322
+ */
323
+ function exportText(source, edits, guard) {
324
+ const ranges = (0, matches_js_1.resolveOverlaps)(edits);
325
+ const whole = () => (0, matches_js_1.applyMatches)(source.original, ranges);
326
+ if (guard === null)
327
+ return (0, redact_js_1.truncate)(whole());
328
+ if (guard.bytes <= redact_js_1.MAX_BYTES)
329
+ return whole();
330
+ let cut = guard.cutAt();
331
+ for (const m of ranges)
332
+ if (m.replaceStart < cut && cut < m.replaceEnd)
333
+ cut = m.replaceEnd;
334
+ const head = (0, matches_js_1.applyMatches)(source.original.slice(0, cut), ranges.filter((m) => m.replaceEnd <= cut));
335
+ return `${head}…[TRUNCATED:${guard.bytes}]`;
336
+ }
337
+ /** The findings for the values, as `pinta.facts` carries them. */
338
+ function factsAttribute(found, outputValues, detailed) {
339
+ return {
340
+ key: "pinta.facts",
341
+ value: { stringValue: JSON.stringify({
342
+ items: [
343
+ { origin: "attributes", values: found.filter((entry) => !outputValues.has(entry.value)) },
344
+ { origin: "toolOutput", values: found.filter((entry) => outputValues.has(entry.value)) },
345
+ ].filter((group) => group.values.length > 0).map(({ origin, values }) => ({
346
+ category: "DATA_EXFILTRATION",
347
+ source: "CORE_REDACT",
348
+ path: "$",
349
+ ...(detailed && new Set(values.map((entry) => entry.type)).size === 1
350
+ ? { evidence: { ruleId: values[0].type } }
351
+ : {}),
352
+ secrets: {
353
+ kinds: ["credential"],
354
+ count: new Set(values.map((entry) => entry.value)).size,
355
+ origins: [origin],
356
+ scannedFields: ["attributes"],
357
+ scanner: "core-tier1",
358
+ truncated: false,
359
+ corroboration: ["pattern"],
360
+ },
361
+ })),
362
+ }) },
363
+ };
364
+ }
365
+ /** Original scalar coordinates, not offsets into the subsequently masked text. */
366
+ function credentialMatches(attributes) {
367
+ const items = [];
368
+ let complete = true;
369
+ let found = false;
370
+ const seen = new Set();
371
+ const fields = new Set();
372
+ for (const attribute of attributes) {
373
+ const source = stringSources.get(attribute.value);
374
+ if (!source)
375
+ continue;
376
+ const ranges = [...source.main.filter((match) => !match.fake), ...source.export.placed];
377
+ if (!ranges.length)
378
+ continue;
379
+ found = true;
380
+ if (fields.has(attribute.key))
381
+ complete = false;
382
+ fields.add(attribute.key);
383
+ // Only protocol field names enter this value-free metadata. An arbitrary
384
+ // user-defined attribute key is not a safe label to repeat as a value.
385
+ if (!/^(?:cc|copilot|codex|gemini|antigravity|opencode|musecode)\.(?:tool_input|tool_response|tool_calls|tool_result|prompt|message)$/.test(attribute.key)) {
386
+ complete = false;
387
+ continue;
388
+ }
389
+ for (const range of ranges) {
390
+ const key = `${attribute.key}:${range.type}:${range.replaceStart}:${range.replaceEnd}`;
391
+ if (seen.has(key))
392
+ continue;
393
+ seen.add(key);
394
+ if (items.length === 32) {
395
+ complete = false;
396
+ continue;
397
+ }
398
+ items.push({
399
+ attribute: attribute.key,
400
+ pattern: range.type,
401
+ start: range.replaceStart,
402
+ end: range.replaceEnd,
403
+ ...(range.nonstandardFetchMode ? { nonstandardFetchMode: true } : {}),
404
+ });
405
+ }
406
+ }
407
+ return found ? {
408
+ key: "pinta.credential_matches",
409
+ value: { stringValue: JSON.stringify({
410
+ version: 1, coordinateSpace: "original_attribute_utf16", complete, items,
411
+ }) },
412
+ } : null;
413
+ }
414
+ /**
415
+ * Assemble a single-span OTLP payload. The adapter owns attribute/resource
416
+ * construction; this owns the envelope shape and guard-attr appending.
417
+ *
418
+ * Two versions of the span are built from the same ids and time (PTA-735). The
419
+ * one returned is what is relayed and stored: the original text with only the
420
+ * ranges of values replaced, so a secret is hidden and every other byte keeps
421
+ * its place. The one the guard judges is attached to it (`guardVersionOf`) and
422
+ * is the text `pinta-core` has always produced, so the verdicts the sidecar
423
+ * gives do not move. If that version cannot be built the guard is sent the
424
+ * stored one.
425
+ */
426
+ function buildPayload(args) {
427
+ const ts = args.now ?? Date.now();
428
+ const tsNano = (BigInt(ts) * 1000000n).toString();
429
+ const traceId = ulidToTraceId(args.traceId);
430
+ const spanId = newSpanId();
431
+ const all = [...args.resource, ...args.attributes];
432
+ const sources = all.flatMap((attr) => {
433
+ const source = stringSources.get(attr.value);
434
+ return source ? [source] : [];
435
+ });
436
+ const detected = sources.flatMap((source) => source.detections);
437
+ const shapeValues = sources.flatMap((source) => source.export.values);
438
+ // Findings count every value, including the line-continuation backslashes and the short values that are
439
+ // replaced in place only.
440
+ const found = detected.concat(shapeValues.map(({ value, type }) => ({ value, type })));
441
+ const outputs = all.flatMap((attr) => {
442
+ const output = outputSources.get(attr.value);
443
+ return output === undefined ? [] : [output];
444
+ });
445
+ const outputValues = new Set();
446
+ if (outputs.length > 0) {
447
+ // Once per distinct value: a value repeated a thousand times is one finding.
448
+ for (const entry of new Map(found.map((item) => [item.value, item])).values()) {
449
+ const maskValue = (0, value_copies_js_1.createDetectedValueMasker)([entry]);
450
+ if (outputs.some((text) => maskValue(text) !== text))
451
+ outputValues.add(entry.value);
452
+ }
453
+ }
454
+ const make = (masker, facts, detailed = false) => {
455
+ const attrs = args.attributes.map((attr) => maskAttribute(attr, masker));
456
+ const span = {
457
+ traceId,
458
+ spanId,
459
+ name: args.spanName,
460
+ kind: args.spanKind ?? 1,
461
+ startTimeUnixNano: tsNano,
462
+ endTimeUnixNano: tsNano,
463
+ attributes: attrs,
464
+ };
465
+ const payload = {
466
+ resourceSpans: [
467
+ {
468
+ resource: { attributes: args.resource.map((attr) => maskAttribute(attr, masker, true)) },
469
+ scopeSpans: [{
470
+ scope: { name: args.scope.name, version: args.scope.version },
471
+ spans: [span],
472
+ }],
473
+ },
474
+ ],
475
+ };
476
+ if (facts.length > 0)
477
+ attrs.push(factsAttribute(facts, outputValues, detailed));
478
+ enforceSpanBudget(span);
479
+ return { payload, attrs };
480
+ };
481
+ // The guard's version: main's masker over main's values, keys and labels as written.
482
+ let guard = null;
483
+ try {
484
+ const mask = (0, value_copies_js_1.createDetectedValueMasker)(detected, { keepJsonKeys: redact_js_1.STRUCTURAL_JSON_KEYS });
485
+ const bytes = new Map();
486
+ const built = make({
487
+ source: (source) => {
488
+ const text = mask(source.original);
489
+ bytes.set(source, Buffer.byteLength(text, "utf-8"));
490
+ return (0, redact_js_1.truncate)(text);
491
+ },
492
+ plain: mask,
493
+ }, detected);
494
+ guard = { payload: built.payload, bytes };
495
+ }
496
+ catch {
497
+ guard = null;
498
+ }
499
+ // The stored version: the original text, only the ranges of values replaced.
500
+ const entries = [
501
+ ...sources.flatMap((source) => source.copyValues),
502
+ ...shapeValues.filter((entry) => entry.copy).map(({ value, type }) => ({ value, type, site: true })),
503
+ ];
504
+ const editor = (0, value_copies_js_1.createCopyEditor)(entries, { keepJsonKeys: redact_js_1.STRUCTURAL_JSON_KEYS });
505
+ let guardFind;
506
+ // The search runs once for each original text; every use below shares its result.
507
+ const guardEdits = new Map();
508
+ const guardEditor = (original) => {
509
+ let edits = guardEdits.get(original);
510
+ if (edits === undefined) {
511
+ guardFind ??= (0, value_copies_js_1.createCopyEditor)(detected, { keepJsonKeys: redact_js_1.STRUCTURAL_JSON_KEYS });
512
+ edits = (0, matches_js_1.resolveOverlaps)(guardFind(original).edits);
513
+ guardEdits.set(original, edits);
514
+ }
515
+ return edits;
516
+ };
517
+ const storedEdits = new Map();
518
+ const storedEditor = (original) => {
519
+ let edits = storedEdits.get(original);
520
+ if (edits === undefined) {
521
+ edits = editor(original).edits;
522
+ storedEdits.set(original, edits);
523
+ }
524
+ return edits;
525
+ };
526
+ const stored = {
527
+ source: (source) => {
528
+ const edits = [...source.export.placed, ...storedEditor(source.original)];
529
+ if (source.export.own.length > 0) {
530
+ // A place main found stays as the guard text has it when that text replaced a part of it (⑤).
531
+ const replaced = guardEditor(source.original);
532
+ for (const range of source.export.own)
533
+ if (!partlyReplaced(replaced, range))
534
+ edits.push(range);
535
+ }
536
+ const bytes = guard?.bytes.get(source);
537
+ if (bytes === undefined)
538
+ return exportText(source, edits, null);
539
+ return exportText(source, edits, {
540
+ bytes,
541
+ cutAt: () => guardCut(source.original, guardEditor(source.original)),
542
+ });
543
+ },
544
+ plain: (text) => (0, matches_js_1.applyMatches)(text, (0, matches_js_1.resolveOverlaps)(editor(text).edits)),
545
+ };
546
+ const built = make(stored, found, true);
547
+ const locations = credentialMatches(all);
548
+ if (locations) {
549
+ built.attrs.push(locations);
550
+ enforceSpanBudget(built.payload.resourceSpans[0].scopeSpans[0].spans[0]);
551
+ }
552
+ if (found.length > 0)
553
+ payloadMaskers.set(built.payload, stored);
554
+ if (guard !== null)
555
+ guardVersions.set(built.payload, guard.payload);
556
+ // Exactly one pinta.client.* set: an explicit timing wins, otherwise derive it
557
+ // from the guard call we just awaited. A guard result without `clientRttMs`
558
+ // (hand-built, or from an older core) simply contributes nothing. Kept for
559
+ // callers that still ask the guard before building; the 0.8.0 flow builds
560
+ // first and uses `attachGuard` on the result.
561
+ return attachGuard(built.payload, args.guard, args.clientTiming);
562
+ }
563
+ // Attributes whose value says what the span is, not what the user did. The
564
+ // adapter sets them from the host's event and tool names.
565
+ const LABEL_KEYS = new Set([
566
+ "ingest.type", "service.name", "service.version",
567
+ "telemetry.sdk.name", "telemetry.sdk.language", "telemetry.sdk.version",
568
+ "pinta.guard.decision", "pinta.guard.fail_open_reason", "pinta.guard.target", "pinta.client.op",
569
+ "pinta.guard.assessment_status", "pinta.guard.hold_reason",
570
+ ]);
571
+ function isLabelKey(key) {
572
+ return LABEL_KEYS.has(key) || key.endsWith(".hook") || key.endsWith(".tool_name") || key.endsWith(".toolName");
573
+ }
574
+ /**
575
+ * Mask the value of an attribute. The key is never touched. A number the
576
+ * adapter or this package sets (resource attributes such as the pid, `pinta.*`
577
+ * durations) keeps its type: a password that spells the same digits would
578
+ * otherwise turn it into a string the receiving side no longer reads as a
579
+ * number. A number from the host's event is still masked, as before.
580
+ */
581
+ function maskAttribute(attr, masker, resource = false) {
582
+ const result = { key: attr.key, value: { ...attr.value } };
583
+ if (isLabelKey(attr.key))
584
+ return result;
585
+ const value = result.value;
586
+ if ("stringValue" in value) {
587
+ const source = stringSources.get(attr.value);
588
+ value.stringValue = source ? masker.source(source) : masker.plain(value.stringValue);
589
+ }
590
+ else if (!resource && !attr.key.startsWith("pinta.") && ("intValue" in value || "doubleValue" in value)) {
591
+ const text = String("intValue" in value ? value.intValue : value.doubleValue);
592
+ const masked = masker.plain(text);
593
+ if (masked !== text)
594
+ result.value = { stringValue: masked };
595
+ }
596
+ return result;
597
+ }
598
+ /**
599
+ * Append the guard verdict — and the client-measured RTT of the call that
600
+ * produced it — to a payload that was built before the guard was asked.
601
+ *
602
+ * This is the second half of the 0.8.0 guard flow: `buildPayload` (no guard)
603
+ * → `evaluateGuard(payload)` → `attachGuard(payload, guard)` → send. The same
604
+ * object goes to the manager and to the relay, so the span judged and the span
605
+ * stored share one `spanId`. Appends to the first span only — a single-span
606
+ * payload is what `buildPayload` produces and what the guard route takes.
607
+ *
608
+ * Mirrors the `guard`/`clientTiming` handling of `buildPayload` exactly; the
609
+ * attributes are the same, only the moment they are added differs. A null or
610
+ * undefined `guard` (guarding inactive) attaches nothing unless an explicit
611
+ * `clientTiming` is given. Returns the same object for chaining.
612
+ */
613
+ function attachGuard(payload, guard, clientTiming) {
614
+ const span = payload.resourceSpans[0]?.scopeSpans[0]?.spans[0];
615
+ if (!span)
616
+ return payload;
617
+ if (guard) {
618
+ const attributes = guardAttrs(guard);
619
+ const masker = payloadMaskers.get(payload);
620
+ span.attributes.push(...(masker ? attributes.map((attr) => maskAttribute(attr, masker)) : attributes));
621
+ }
622
+ const timing = clientTiming ??
623
+ (guard?.clientRttMs !== undefined ? { op: "guard", rttMs: guard.clientRttMs } : null);
624
+ if (timing)
625
+ span.attributes.push(...clientAttrs(timing));
626
+ return payload;
627
+ }
628
+ /**
629
+ * Combine multiple per-event payloads into one by concatenating their
630
+ * resourceSpans arrays. aware-backend's parser iterates resourceSpans natively.
631
+ */
632
+ function mergeBatch(payloads) {
633
+ const out = [];
634
+ for (const p of payloads)
635
+ out.push(...p.resourceSpans);
636
+ return { resourceSpans: out };
637
+ }
638
+ //# sourceMappingURL=otlp.js.map