@wrongstack/core 0.310.1 → 0.313.1

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 (187) hide show
  1. package/dist/chronicle/index.js +84 -6391
  2. package/dist/chronicle/project-server.js +84 -4868
  3. package/dist/chunk-2BUUIMQB.js +225 -0
  4. package/dist/chunk-2FK4WTFF.js +207 -0
  5. package/dist/chunk-2FQL4PDC.js +292 -0
  6. package/dist/chunk-2KKODIQU.js +2256 -0
  7. package/dist/chunk-2YU4WVBW.js +134 -0
  8. package/dist/chunk-3E244UDA.js +356 -0
  9. package/dist/chunk-3XPVB7BA.js +135 -0
  10. package/dist/chunk-4LJJYBAU.js +388 -0
  11. package/dist/chunk-4VWO3ZXL.js +342 -0
  12. package/dist/chunk-4XV6IR37.js +187 -0
  13. package/dist/chunk-4ZHTKJHM.js +183 -0
  14. package/dist/chunk-52RTVH4M.js +361 -0
  15. package/dist/chunk-57GEWK5X.js +26 -0
  16. package/dist/chunk-5DSMEVA4.js +931 -0
  17. package/dist/chunk-5RP3QTRL.js +1223 -0
  18. package/dist/chunk-5S437PRC.js +50 -0
  19. package/dist/chunk-5XDUGTKN.js +511 -0
  20. package/dist/chunk-62V2AFVG.js +422 -0
  21. package/dist/chunk-65RDIOR2.js +2470 -0
  22. package/dist/chunk-6AKOTGLM.js +597 -0
  23. package/dist/chunk-7ZHZE5EO.js +28 -0
  24. package/dist/chunk-A455ATZB.js +140 -0
  25. package/dist/chunk-AD7ZFZCS.js +46 -0
  26. package/dist/chunk-AI4LLQ2U.js +856 -0
  27. package/dist/chunk-ASX6AW36.js +789 -0
  28. package/dist/chunk-AT4V4XGI.js +3522 -0
  29. package/dist/chunk-AWNQ6ED6.js +311 -0
  30. package/dist/chunk-B4AMLZPB.js +9 -0
  31. package/dist/chunk-BAKVJLEV.js +417 -0
  32. package/dist/chunk-BJHVULHO.js +55 -0
  33. package/dist/chunk-CB2HFKTP.js +9 -0
  34. package/dist/chunk-CE4ZOCOI.js +1640 -0
  35. package/dist/chunk-CQQL4ZOQ.js +151 -0
  36. package/dist/chunk-DEIQMBD2.js +65 -0
  37. package/dist/chunk-E6I5RXVK.js +58 -0
  38. package/dist/chunk-EFEHDQGY.js +1589 -0
  39. package/dist/chunk-EODDVJBM.js +82 -0
  40. package/dist/chunk-EPC3GZD4.js +308 -0
  41. package/dist/chunk-FAYRX2AD.js +13 -0
  42. package/dist/chunk-FFSX2QDQ.js +362 -0
  43. package/dist/chunk-FHAMQS7Q.js +5856 -0
  44. package/dist/chunk-FIV4IJL7.js +2263 -0
  45. package/dist/chunk-FNXVT7HF.js +52 -0
  46. package/dist/chunk-FSWCWSTS.js +395 -0
  47. package/dist/chunk-FW5LDDMJ.js +16464 -0
  48. package/dist/chunk-FXQLIX3K.js +211 -0
  49. package/dist/chunk-G5AAKEEZ.js +228 -0
  50. package/dist/chunk-G5S3S5ZN.js +38 -0
  51. package/dist/chunk-GAZEWQEZ.js +231 -0
  52. package/dist/chunk-GFJOMSHG.js +125 -0
  53. package/dist/chunk-GFXZTHNI.js +158 -0
  54. package/dist/chunk-GM54GJBU.js +960 -0
  55. package/dist/chunk-GPQ3NJPR.js +900 -0
  56. package/dist/chunk-GTCU6DZ3.js +1 -0
  57. package/dist/chunk-H5E77KUJ.js +15 -0
  58. package/dist/chunk-H72H4XDU.js +1023 -0
  59. package/dist/chunk-HA4ZYA6T.js +178 -0
  60. package/dist/chunk-I45KAW2N.js +5020 -0
  61. package/dist/chunk-IQ35HMQL.js +1396 -0
  62. package/dist/chunk-IYFBFX34.js +86 -0
  63. package/dist/chunk-JJPMWPB6.js +109 -0
  64. package/dist/chunk-JTHKOYWU.js +663 -0
  65. package/dist/chunk-JVGPR3TS.js +365 -0
  66. package/dist/chunk-JVKB2TBL.js +48 -0
  67. package/dist/chunk-JX7VBZDK.js +31 -0
  68. package/dist/chunk-K3G6JBUC.js +5232 -0
  69. package/dist/chunk-K4YUNKU7.js +589 -0
  70. package/dist/chunk-KBZGE6LN.js +710 -0
  71. package/dist/chunk-KDQJCT2J.js +45 -0
  72. package/dist/chunk-KI4L2DUL.js +560 -0
  73. package/dist/chunk-KJ2ZTQSL.js +47 -0
  74. package/dist/chunk-KSJ5UTP7.js +154 -0
  75. package/dist/chunk-LHOA5DWA.js +28 -0
  76. package/dist/chunk-LX5QWLBL.js +27 -0
  77. package/dist/chunk-LZDDLNCZ.js +279 -0
  78. package/dist/chunk-M2WF6AXG.js +115 -0
  79. package/dist/chunk-M7BS2K6U.js +1 -0
  80. package/dist/chunk-NDBIPFNY.js +102 -0
  81. package/dist/chunk-NEMIWEXC.js +1199 -0
  82. package/dist/chunk-NFAYHPRH.js +323 -0
  83. package/dist/chunk-O37BQ65S.js +21 -0
  84. package/dist/chunk-O74MJHXU.js +187 -0
  85. package/dist/chunk-OJZEX73F.js +112 -0
  86. package/dist/chunk-PAAWLLZX.js +74 -0
  87. package/dist/chunk-PFXFQQRT.js +339 -0
  88. package/dist/chunk-PFZO3C6H.js +14 -0
  89. package/dist/chunk-PHH7LD45.js +113 -0
  90. package/dist/chunk-QRTG4XTI.js +188 -0
  91. package/dist/chunk-QVOVMXJR.js +1351 -0
  92. package/dist/chunk-RCQYT2I4.js +757 -0
  93. package/dist/chunk-RD6DEE36.js +1178 -0
  94. package/dist/chunk-RJIZEJ42.js +30 -0
  95. package/dist/chunk-RPOA7IAE.js +150 -0
  96. package/dist/chunk-SN2DQRL6.js +1172 -0
  97. package/dist/chunk-SQJVFEBV.js +41 -0
  98. package/dist/chunk-SQP64RCS.js +5391 -0
  99. package/dist/chunk-SVT4RNTR.js +49 -0
  100. package/dist/chunk-SWUFN7XM.js +43 -0
  101. package/dist/chunk-SXMVYC5H.js +174 -0
  102. package/dist/chunk-SZ6AYUIZ.js +23 -0
  103. package/dist/chunk-T3KGZBU5.js +3171 -0
  104. package/dist/chunk-TBRL2RCC.js +9 -0
  105. package/dist/chunk-TRT2HRWZ.js +18 -0
  106. package/dist/chunk-TYW2GI5I.js +1077 -0
  107. package/dist/chunk-UIWONWVG.js +4959 -0
  108. package/dist/chunk-VB3H5WWB.js +151 -0
  109. package/dist/chunk-W4A6QA3D.js +258 -0
  110. package/dist/chunk-WBPVKEEE.js +227 -0
  111. package/dist/chunk-WEBMSQP2.js +123 -0
  112. package/dist/chunk-WOEZV3Q4.js +333 -0
  113. package/dist/chunk-WQQON3SV.js +473 -0
  114. package/dist/chunk-WQTOVMGV.js +119 -0
  115. package/dist/chunk-WZO23AWO.js +2779 -0
  116. package/dist/chunk-XBDP4QPW.js +7 -0
  117. package/dist/chunk-XEBHSJLT.js +103 -0
  118. package/dist/chunk-XQ2ECNK3.js +1 -0
  119. package/dist/chunk-XQ2XGIBF.js +2086 -0
  120. package/dist/chunk-Y2GE5TSI.js +355 -0
  121. package/dist/chunk-YBUJCZ57.js +351 -0
  122. package/dist/chunk-YNCVSFGF.js +149 -0
  123. package/dist/chunk-YUPMXOGP.js +282 -0
  124. package/dist/chunk-YY6APYUM.js +49 -0
  125. package/dist/chunk-Z2IJUO45.js +691 -0
  126. package/dist/chunk-ZEHUCJHY.js +129 -0
  127. package/dist/chunk-ZYU2YOJ6.js +1496 -0
  128. package/dist/chunk-ZZ4V3WIZ.js +163 -0
  129. package/dist/coordination/agents/index.js +145 -6260
  130. package/dist/coordination/index.js +365 -34323
  131. package/dist/coordination/mailbox-project-server.js +48 -3220
  132. package/dist/coordination/mailbox-types.d.ts +13 -1
  133. package/dist/coordination/provider-status-tracker.d.ts +4 -0
  134. package/dist/coordination/sqlite-mailbox.d.ts +2 -1
  135. package/dist/core/agent.d.ts +14 -1
  136. package/dist/core/index.js +267 -12479
  137. package/dist/core/model-ref.js +5 -23
  138. package/dist/core/provider-runner.d.ts +36 -1
  139. package/dist/design/index.js +50 -1087
  140. package/dist/execution/index.d.ts +1 -1
  141. package/dist/execution/index.js +1599 -21887
  142. package/dist/execution/prompt-enhancer.js +16 -535
  143. package/dist/execution/retry-policy.d.ts +31 -1
  144. package/dist/extension/index.js +7 -311
  145. package/dist/goal/index.js +33 -3435
  146. package/dist/hooks/index.js +14 -1138
  147. package/dist/hq/index.js +112 -5139
  148. package/dist/hq/protocol.js +21 -668
  149. package/dist/index.js +1410 -92655
  150. package/dist/infrastructure/index.js +64 -4811
  151. package/dist/kernel/events/provider-events.d.ts +15 -0
  152. package/dist/kernel/events/wrongtrace-events.d.ts +26 -0
  153. package/dist/kernel/events.d.ts +16 -7
  154. package/dist/kernel/index.js +14 -992
  155. package/dist/models/index.js +40 -1117
  156. package/dist/notifications/index.js +3 -108
  157. package/dist/observability/index.js +17 -279
  158. package/dist/plugin/index.js +584 -14835
  159. package/dist/prompts/index.js +14 -948
  160. package/dist/registry/index.js +9 -822
  161. package/dist/registry-R23UBE7H.js +14 -0
  162. package/dist/replay/index.js +6 -84
  163. package/dist/review-finding-store-DKAV3AS6.js +21 -0
  164. package/dist/review-report-store-OWY3EC3N.js +19 -0
  165. package/dist/security/index.js +114 -2202
  166. package/dist/session-catalog/index.js +36 -2103
  167. package/dist/session-catalog/project-server.js +42 -1435
  168. package/dist/skills/index.js +35 -1578
  169. package/dist/storage/index.js +182 -15600
  170. package/dist/tasking/index.js +10 -676
  171. package/dist/tools/index.js +52 -9589
  172. package/dist/types/config/autonomy.d.ts +5 -0
  173. package/dist/types/config/tools.d.ts +2 -2
  174. package/dist/types/config/ui.d.ts +1 -1
  175. package/dist/types/errors.d.ts +18 -0
  176. package/dist/types/index.js +121 -1341
  177. package/dist/types/provider-runner.d.ts +8 -0
  178. package/dist/types/session-markers.js +8 -144
  179. package/dist/utils/error.js +3 -4
  180. package/dist/utils/expect-defined.js +3 -9
  181. package/dist/utils/heap-watchdog.js +6 -706
  182. package/dist/utils/index.js +269 -5685
  183. package/dist/utils/sage-output-block.js +5 -42
  184. package/dist/wiring/proxy-rewrite.d.ts +92 -4
  185. package/dist/wiring/proxy-rewrite.js +20 -61
  186. package/dist/worktree/index.js +6 -887
  187. package/package.json +4 -4
@@ -1,111 +1,6 @@
1
- // src/notifications/notifier-impl.ts
2
- function emptyCounters() {
3
- return { attempted: 0, delivered: 0, failed: 0, suppressed: 0 };
4
- }
5
- var NotifierImpl = class _NotifierImpl {
6
- #channels = /* @__PURE__ */ new Map();
7
- #counters = /* @__PURE__ */ new Map();
8
- /** Soft cap for #counters — prevents unbounded growth if channels are
9
- * repeatedly registered with distinct names. */
10
- static #MAX_COUNTERS = 100;
11
- // -----------------------------------------------------------------------
12
- // Lifecycle
13
- // -----------------------------------------------------------------------
14
- notify(channels, message) {
15
- const names = typeof channels === "string" ? [channels] : channels;
16
- if (names.length === 0) return Promise.resolve([]);
17
- const results = [];
18
- for (const name of names) {
19
- const channel = this.#channels.get(name);
20
- if (!channel) continue;
21
- const counters = this.#counters.get(name) ?? emptyCounters();
22
- counters.attempted += 1;
23
- this.#counters.set(name, counters);
24
- results.push(
25
- channel.deliver(message).then(
26
- (result) => {
27
- if (result.ok) {
28
- counters.delivered += 1;
29
- } else {
30
- counters.failed += 1;
31
- }
32
- return result;
33
- },
34
- (err) => {
35
- counters.failed += 1;
36
- const error = err instanceof Error ? err.message : "unknown rejection";
37
- return {
38
- ok: false,
39
- channel: name,
40
- error: `threw: ${error}`,
41
- deliveredAt: (/* @__PURE__ */ new Date()).toISOString()
42
- };
43
- }
44
- )
45
- );
46
- }
47
- return Promise.all(results);
48
- }
49
- registerChannel(channel) {
50
- this.#channels.set(channel.name, channel);
51
- if (!this.#counters.has(channel.name)) {
52
- if (this.#counters.size >= _NotifierImpl.#MAX_COUNTERS) {
53
- const oldest = this.#counters.keys().next();
54
- if (!oldest.done && oldest.value !== void 0) {
55
- this.#counters.delete(oldest.value);
56
- }
57
- }
58
- this.#counters.set(channel.name, emptyCounters());
59
- }
60
- }
61
- unregisterChannel(name) {
62
- this.#channels.delete(name);
63
- }
64
- async channels() {
65
- const entries = Array.from(this.#channels.entries());
66
- const results = await Promise.allSettled(
67
- entries.map(async ([name, channel]) => {
68
- try {
69
- const ping = await channel.ping();
70
- return { name, type: channel.type, ok: ping.ok, error: ping.error };
71
- } catch {
72
- return { name, type: channel.type, ok: false, error: "ping threw" };
73
- }
74
- })
75
- );
76
- return results.map(
77
- (r) => r.status === "fulfilled" ? r.value : { name: "unknown", type: "unknown", ok: false, error: "unhandled ping rejection" }
78
- );
79
- }
80
- counters() {
81
- let attempted = 0;
82
- let delivered = 0;
83
- let failed = 0;
84
- let suppressed = 0;
85
- for (const c of this.#counters.values()) {
86
- attempted += c.attempted;
87
- delivered += c.delivered;
88
- failed += c.failed;
89
- suppressed += c.suppressed;
90
- }
91
- return { attempted, delivered, failed, suppressed };
92
- }
93
- /**
94
- * Return per-channel counters for detailed diagnostics.
95
- * Not part of the `Notifier` interface — available on the concrete class.
96
- */
97
- perChannelCounters() {
98
- const result = {};
99
- for (const [name, c] of this.#counters) {
100
- result[name] = {
101
- attempted: c.attempted,
102
- delivered: c.delivered,
103
- failed: c.failed
104
- };
105
- }
106
- return result;
107
- }
108
- };
1
+ import {
2
+ NotifierImpl
3
+ } from "../chunk-PHH7LD45.js";
109
4
  export {
110
5
  NotifierImpl
111
6
  };
@@ -1,3 +1,20 @@
1
+ import {
2
+ emitProcessCompleted,
3
+ emitProcessOutput,
4
+ emitProcessStarted,
5
+ redactCommand,
6
+ redactCommandArgs,
7
+ runWithProcessTelemetry
8
+ } from "../chunk-NDBIPFNY.js";
9
+ import {
10
+ runWithNetworkTelemetry,
11
+ startNetworkTelemetryMonitor
12
+ } from "../chunk-HA4ZYA6T.js";
13
+ import {
14
+ toErrorMessage
15
+ } from "../chunk-TBRL2RCC.js";
16
+ import "../chunk-PFZO3C6H.js";
17
+
1
18
  // src/observability/metrics.ts
2
19
  var RESERVOIR_SIZE = 1024;
3
20
  function labelKey(labels) {
@@ -195,11 +212,6 @@ var NoopMetricsSink = class {
195
212
  }
196
213
  };
197
214
 
198
- // src/utils/error.ts
199
- function toErrorMessage(err) {
200
- return err instanceof Error ? err.message : String(err);
201
- }
202
-
203
215
  // src/observability/health.ts
204
216
  var SEVERITY = {
205
217
  healthy: 0,
@@ -358,280 +370,6 @@ function metricToolName(name) {
358
370
  return name.startsWith("mcp__") ? "mcp_proxy" : name;
359
371
  }
360
372
 
361
- // src/observability/process-telemetry.ts
362
- import { AsyncLocalStorage } from "node:async_hooks";
363
- import { createHash } from "node:crypto";
364
-
365
- // src/utils/expect-defined.ts
366
- function expectDefined(value, label) {
367
- if (value === null || value === void 0) {
368
- const err = new Error(label ? `Expected ${label} to be defined` : "Expected value to be defined");
369
- err.name = "ExpectDefinedError";
370
- throw err;
371
- }
372
- return value;
373
- }
374
-
375
- // src/observability/redact-command.ts
376
- var SENSITIVE_FLAG_PATTERNS = [
377
- // --flag=value or --flag "value" (value captured up to next space or comma)
378
- /--(?:token|password|passwd|pwd|secret|api[-_]?key|api[-_]?secret|auth|credential|private[-_]?key|access[-_]?key|github[-_]?token|gh[-_]?token|bearer|jwt|oauth|pin|pincode|passphrase|access[-_]?token)(?:[=\s,][^\s]*)?/gi,
379
- // -t short flag (token): attached (-tVALUE), separated (-t VALUE), or -t=VALUE.
380
- // The separator group is optional so the attached form (the common one) matches.
381
- // (?<![-\w]) anchors to a token start so we don't match the `-t` inside `--token`.
382
- // The value must be token-like (>= 8 chars) so ordinary combined flags such
383
- // as `tar -tf` / `ssh -tt` are not eaten. Global flag: EVERY occurrence is
384
- // redacted, not just the first. Synced with packages/tools _redact-command.ts.
385
- /(?<![-\w])-t(?:[=\s]+)?[^\s,-]{8,}/g,
386
- // -p|-password|-a (redis auth) short flags: attached + separated + =value.
387
- // Same token-start anchor; over-redaction is an accepted tradeoff for a
388
- // redaction function (false positive = cosmetic noise; false negative = leak).
389
- /(?<![-\w])-(?:password|p|a)(?:[=\s]+)?[^\s,-]+/gi,
390
- // env var–style secrets: TOKEN=x, API_KEY=y, etc.
391
- /(?:TOKEN|API_KEY|API_SECRET|AUTH_TOKEN|GITHUB_TOKEN|GH_TOKEN|BEARER|JWT|OAUTH|CREDENTIAL|SECRET|PRIVATE_KEY|PASSWORD|PASSWD|PASSPHRASE)\s*[=:]\s*[^\s,]+/gi,
392
- // Generic high-entropy look: base64 strings >32 chars or hex strings >32 digits — but only
393
- // when preceded by a flag name (e.g. --github-token=EyJ...). Global flag so
394
- // every such flag in the command line is redacted, not just the first.
395
- /--\w*(?:token|key|secret|password|passwd|auth|credential)\w*[=\s,][A-Za-z0-9+/=]{32,}/g
396
- ];
397
- function redactCommand(cmd) {
398
- let result = cmd;
399
- for (const pattern of SENSITIVE_FLAG_PATTERNS) {
400
- result = result.replace(pattern, (match) => {
401
- const eq = match.indexOf("=");
402
- const sp = match.search(/\s/);
403
- const delim = eq !== -1 ? "=" : sp !== -1 ? match[sp] : null;
404
- if (delim !== null) {
405
- const flag = match.slice(0, match.indexOf(expectDefined(delim)) + 1);
406
- return `${flag}[REDACTED]`;
407
- }
408
- if (match.startsWith("--")) {
409
- return match;
410
- }
411
- return `${match.slice(0, 2)}[REDACTED]`;
412
- });
413
- }
414
- return result;
415
- }
416
- var BARE_SENSITIVE_LONG_FLAG = /^--(?:token|password|passwd|pwd|secret|api[-_]?key|api[-_]?secret|auth|credential|private[-_]?key|access[-_]?key|github[-_]?token|gh[-_]?token|bearer|jwt|oauth|pin|pincode|passphrase|access[-_]?token)$/i;
417
- var BARE_SENSITIVE_SHORT_FLAG = /^-(?:p|t|a)$/i;
418
- function redactCommandArgs(command, args) {
419
- const redactedCommand = redactCommand(command);
420
- const redactedArgs = args.map((a) => redactCommand(a));
421
- for (let i = 0; i < redactedArgs.length - 1; i++) {
422
- const flag = redactedArgs[i];
423
- const next = redactedArgs[i + 1];
424
- if (flag === void 0 || next === void 0) continue;
425
- const isBareSensitive = (BARE_SENSITIVE_LONG_FLAG.test(flag) || BARE_SENSITIVE_SHORT_FLAG.test(flag)) && !flag.includes("[REDACTED]");
426
- if (isBareSensitive && !next.startsWith("-")) {
427
- redactedArgs[i + 1] = "[REDACTED]";
428
- }
429
- }
430
- return { command: redactedCommand, args: redactedArgs };
431
- }
432
-
433
- // src/observability/process-telemetry.ts
434
- var storage = new AsyncLocalStorage();
435
- function runWithProcessTelemetry(context, run) {
436
- return storage.run(context, run);
437
- }
438
- function emitProcessStarted(event) {
439
- const { command, args } = redactCommandArgs(event.command, event.args);
440
- emit("process.started", { ...event, command, args });
441
- }
442
- function emitProcessOutput(input) {
443
- const bytes = Buffer.byteLength(input.chunk);
444
- emit("process.output", {
445
- ...input.pid !== void 0 ? { pid: input.pid } : {},
446
- stream: input.stream,
447
- bytes,
448
- chunkHash: createHash("sha256").update(input.chunk).digest("hex"),
449
- at: (/* @__PURE__ */ new Date()).toISOString()
450
- });
451
- }
452
- function emitProcessCompleted(event) {
453
- emit("process.completed", event);
454
- }
455
- function emit(name, event) {
456
- const context = storage.getStore();
457
- if (!context) return;
458
- const { events, ...identity2 } = context;
459
- events.emit(name, { ...identity2, ...event });
460
- }
461
-
462
- // src/observability/network-telemetry.ts
463
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
464
- import { createHash as createHash2, randomUUID } from "node:crypto";
465
- import { channel } from "node:diagnostics_channel";
466
- var storage2 = new AsyncLocalStorage2();
467
- var requests = /* @__PURE__ */ new WeakMap();
468
- var users = 0;
469
- var unsubscribe;
470
- function runWithNetworkTelemetry(context, run) {
471
- return storage2.run(context, run);
472
- }
473
- function startNetworkTelemetryMonitor() {
474
- users++;
475
- if (!unsubscribe) unsubscribe = subscribe();
476
- let stopped = false;
477
- return () => {
478
- if (stopped) return;
479
- stopped = true;
480
- users--;
481
- if (users <= 0) {
482
- unsubscribe?.();
483
- unsubscribe = void 0;
484
- users = 0;
485
- }
486
- };
487
- }
488
- function subscribe() {
489
- const create = channel("undici:request:create");
490
- const headers = channel("undici:request:headers");
491
- const error = channel("undici:request:error");
492
- const onCreate = (message) => {
493
- const context = storage2.getStore();
494
- const request = objectField(message, "request");
495
- if (!context || !request) return;
496
- const target = safeTarget(request);
497
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
498
- const requestBytes = numberField(request, "contentLength");
499
- const state = {
500
- ...context,
501
- requestId: randomUUID(),
502
- ...target,
503
- ...requestBytes !== void 0 ? { requestBytes } : {},
504
- startedAt,
505
- startedNs: process.hrtime.bigint()
506
- };
507
- requests.set(request, state);
508
- context.events.emit("network.request.started", {
509
- ...identity(state),
510
- requestId: state.requestId,
511
- method: state.method,
512
- scheme: state.scheme,
513
- serverAddress: state.serverAddress,
514
- ...state.serverPort !== void 0 ? { serverPort: state.serverPort } : {},
515
- pathHash: state.pathHash,
516
- queryKeys: queryKeys(request),
517
- ...state.requestBytes !== void 0 ? { requestBytes: state.requestBytes } : {},
518
- startedAt
519
- });
520
- };
521
- const onHeaders = (message) => {
522
- const request = objectField(message, "request");
523
- if (!request) return;
524
- const state = requests.get(request);
525
- if (!state) return;
526
- requests.delete(request);
527
- const response = objectField(message, "response");
528
- const responseBytes = contentLength(response);
529
- state.events.emit("network.request.completed", {
530
- ...identity(state),
531
- requestId: state.requestId,
532
- method: state.method,
533
- scheme: state.scheme,
534
- serverAddress: state.serverAddress,
535
- ...state.serverPort !== void 0 ? { serverPort: state.serverPort } : {},
536
- pathHash: state.pathHash,
537
- statusCode: numberField(response, "statusCode") ?? 0,
538
- durationMs: elapsed(state.startedNs),
539
- ...state.requestBytes !== void 0 ? { requestBytes: state.requestBytes } : {},
540
- ...responseBytes !== void 0 ? { responseBytes } : {},
541
- completedAt: (/* @__PURE__ */ new Date()).toISOString()
542
- });
543
- };
544
- const onError = (message) => {
545
- const request = objectField(message, "request");
546
- if (!request) return;
547
- const state = requests.get(request);
548
- if (!state) return;
549
- requests.delete(request);
550
- const err = objectField(message, "error");
551
- const errorCode = stringField(err, "code");
552
- state.events.emit("network.request.failed", {
553
- ...identity(state),
554
- requestId: state.requestId,
555
- method: state.method,
556
- scheme: state.scheme,
557
- serverAddress: state.serverAddress,
558
- ...state.serverPort !== void 0 ? { serverPort: state.serverPort } : {},
559
- pathHash: state.pathHash,
560
- durationMs: elapsed(state.startedNs),
561
- errorName: stringField(err, "name") ?? "Error",
562
- ...errorCode ? { errorCode } : {},
563
- failedAt: (/* @__PURE__ */ new Date()).toISOString()
564
- });
565
- };
566
- create.subscribe(onCreate);
567
- headers.subscribe(onHeaders);
568
- error.subscribe(onError);
569
- return () => {
570
- create.unsubscribe(onCreate);
571
- headers.unsubscribe(onHeaders);
572
- error.unsubscribe(onError);
573
- };
574
- }
575
- function identity(state) {
576
- return {
577
- sessionId: state.sessionId,
578
- ...state.traceId ? { traceId: state.traceId } : {},
579
- ...state.agentId ? { agentId: state.agentId } : {},
580
- ...state.toolCallId ? { toolCallId: state.toolCallId } : {},
581
- ...state.attemptId ? { attemptId: state.attemptId } : {},
582
- initiator: state.initiator,
583
- operationName: state.operationName
584
- };
585
- }
586
- function safeTarget(request) {
587
- const origin = String(request.origin ?? "");
588
- const path = String(request.path ?? "");
589
- let url;
590
- try {
591
- url = new URL(path, origin);
592
- } catch {
593
- url = new URL("http://invalid.local/");
594
- }
595
- return {
596
- method: String(request.method ?? "GET").toUpperCase(),
597
- scheme: url.protocol.replace(":", ""),
598
- serverAddress: url.hostname,
599
- ...url.port ? { serverPort: Number(url.port) } : {},
600
- pathHash: hash(url.pathname)
601
- };
602
- }
603
- function queryKeys(request) {
604
- try {
605
- return [...new URL(String(request.path ?? ""), String(request.origin ?? "")).searchParams.keys()].filter((v, i, a) => a.indexOf(v) === i).slice(0, 50);
606
- } catch {
607
- return [];
608
- }
609
- }
610
- function contentLength(response) {
611
- const raw = response?.headers;
612
- if (!Array.isArray(raw)) return void 0;
613
- for (let index = 0; index < raw.length - 1; index += 2) if (String(raw[index]).toLowerCase() === "content-length") {
614
- const value = Number(String(raw[index + 1]));
615
- return Number.isFinite(value) ? value : void 0;
616
- }
617
- return void 0;
618
- }
619
- function objectField(value, key) {
620
- return value && typeof value === "object" && value[key] && typeof value[key] === "object" ? value[key] : void 0;
621
- }
622
- function stringField(value, key) {
623
- return typeof value?.[key] === "string" ? value[key] : void 0;
624
- }
625
- function numberField(value, key) {
626
- return typeof value?.[key] === "number" ? value[key] : void 0;
627
- }
628
- function elapsed(start) {
629
- return Number(process.hrtime.bigint() - start) / 1e6;
630
- }
631
- function hash(value) {
632
- return createHash2("sha256").update(value).digest("hex");
633
- }
634
-
635
373
  // src/observability/prometheus.ts
636
374
  import { timingSafeEqual } from "node:crypto";
637
375
  var NUMBER_FORMAT_INFINITY = "NaN";