@particle-academy/agent-integrations 0.18.0 → 0.20.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,5 +1,5 @@
1
- import { ShareControls, AgentCursor, AgentActivityHighlight, AgentPanel } from './chunk-YEEOTIGY.js';
2
- import { createSessionDescriptor, attachSseRelay } from './chunk-CPNOF4HI.js';
1
+ import { ShareControls, AgentCursor, AgentActivityHighlight, AgentPanel } from './chunk-HKQBG2HZ.js';
2
+ import { createSessionDescriptor, attachSseRelay } from './chunk-FUI7KXE7.js';
3
3
  import { attachInProcess } from './chunk-AFUULW5E.js';
4
4
  import { registerWhiteboardBridge } from './chunk-3QJSOS7G.js';
5
5
  import './chunk-KJ5AOOV7.js';
@@ -0,0 +1,78 @@
1
+ import { AutoActivityEvent } from '@particle-academy/fancy-auto-common';
2
+
3
+ /**
4
+ * In-browser heuristics analytics sink for agent traffic.
5
+ *
6
+ * Agent bridge mutations emit `AutoActivityEvent`s into the in-page
7
+ * `@particle-academy/fancy-auto-common` activity bus (presence / cursors).
8
+ * This sink — living in THIS package so it shares the SAME bundled
9
+ * `fancy-auto-common` module instance the bridges emit into — subscribes to
10
+ * that bus and POSTs each event to the `fancy-heuristics` `/collect` endpoint
11
+ * as `actor:"agent"`, so agent traffic shows up in the heuristics dashboard.
12
+ *
13
+ * It does NOT depend on `fancy-heuristics` / `fancy-heuristics-js`: it only
14
+ * emits the frozen wire shape over HTTP. The mapping mirrors
15
+ * `fancy-heuristics-js/src/agent.ts` `mapActivityToEvent` — keep parity.
16
+ */
17
+
18
+ /** What kind of interaction an event captures (mirrors fancy-heuristics-js). */
19
+ type HeuristicsEventKind = "pageview" | "click" | "scroll" | "pointer" | "dwell";
20
+ /** Who produced the interaction. */
21
+ type HeuristicsActor = "human" | "agent";
22
+ /**
23
+ * A single interaction event — mirrors `fancy-heuristics-js` `HeuristicsEvent`.
24
+ * Optional fields are omitted (never `null`) when not relevant to the `kind`.
25
+ */
26
+ interface HeuristicsEvent {
27
+ kind: HeuristicsEventKind;
28
+ actor: HeuristicsActor;
29
+ /** location.pathname at capture time. */
30
+ path: string;
31
+ /** ms epoch. */
32
+ ts: number;
33
+ x?: number;
34
+ y?: number;
35
+ vw?: number;
36
+ vh?: number;
37
+ scrollPct?: number;
38
+ dwellMs?: number;
39
+ targetId?: string;
40
+ label?: string;
41
+ meta?: Record<string, unknown>;
42
+ }
43
+ /** The batched POST body sent to `${endpoint}/collect`. */
44
+ interface CollectBatch {
45
+ siteKey: string;
46
+ sessionId: string;
47
+ events: HeuristicsEvent[];
48
+ }
49
+ interface AttachHeuristicsSinkOptions {
50
+ /** Base URL, e.g. "/heuristics". POSTs to `${endpoint}/collect`. */
51
+ endpoint: string;
52
+ /** Identifies the site to the ingestion endpoint. */
53
+ siteKey: string;
54
+ /** Stable session id. Default: a generated "agent-<rand>" per attach. */
55
+ sessionId?: string;
56
+ /** Resolves the current path. Default: `() => location.pathname`. */
57
+ path?: () => string;
58
+ /** Which activity sources to record. Default "all". */
59
+ source?: "agent" | "flow" | "all";
60
+ /** Flush interval in ms. Default 2000. */
61
+ batchMs?: number;
62
+ }
63
+ /**
64
+ * Map one activity event to an `actor:"agent"` HeuristicsEvent. Activities
65
+ * carrying a finite `meta.dwellMs` become `kind:"dwell"`; everything else is a
66
+ * discrete `kind:"click"` with x/y/vw/vh pulled from numeric meta (default 0).
67
+ * Mirrors `fancy-heuristics-js/src/agent.ts` `mapActivityToEvent`.
68
+ */
69
+ declare function mapActivityToEvent(e: AutoActivityEvent, path: string): HeuristicsEvent;
70
+ /**
71
+ * Subscribe to the in-page agent activity bus and forward each matching event
72
+ * to the heuristics `/collect` endpoint as `actor:"agent"`. SSR-safe (returns a
73
+ * no-op when there is no `window`). Returns an unsubscribe that flushes the
74
+ * buffer and detaches all listeners/timers.
75
+ */
76
+ declare function attachHeuristicsSink(opts: AttachHeuristicsSinkOptions): () => void;
77
+
78
+ export { type AttachHeuristicsSinkOptions, type CollectBatch, type HeuristicsEvent, attachHeuristicsSink, mapActivityToEvent };
@@ -0,0 +1,78 @@
1
+ import { AutoActivityEvent } from '@particle-academy/fancy-auto-common';
2
+
3
+ /**
4
+ * In-browser heuristics analytics sink for agent traffic.
5
+ *
6
+ * Agent bridge mutations emit `AutoActivityEvent`s into the in-page
7
+ * `@particle-academy/fancy-auto-common` activity bus (presence / cursors).
8
+ * This sink — living in THIS package so it shares the SAME bundled
9
+ * `fancy-auto-common` module instance the bridges emit into — subscribes to
10
+ * that bus and POSTs each event to the `fancy-heuristics` `/collect` endpoint
11
+ * as `actor:"agent"`, so agent traffic shows up in the heuristics dashboard.
12
+ *
13
+ * It does NOT depend on `fancy-heuristics` / `fancy-heuristics-js`: it only
14
+ * emits the frozen wire shape over HTTP. The mapping mirrors
15
+ * `fancy-heuristics-js/src/agent.ts` `mapActivityToEvent` — keep parity.
16
+ */
17
+
18
+ /** What kind of interaction an event captures (mirrors fancy-heuristics-js). */
19
+ type HeuristicsEventKind = "pageview" | "click" | "scroll" | "pointer" | "dwell";
20
+ /** Who produced the interaction. */
21
+ type HeuristicsActor = "human" | "agent";
22
+ /**
23
+ * A single interaction event — mirrors `fancy-heuristics-js` `HeuristicsEvent`.
24
+ * Optional fields are omitted (never `null`) when not relevant to the `kind`.
25
+ */
26
+ interface HeuristicsEvent {
27
+ kind: HeuristicsEventKind;
28
+ actor: HeuristicsActor;
29
+ /** location.pathname at capture time. */
30
+ path: string;
31
+ /** ms epoch. */
32
+ ts: number;
33
+ x?: number;
34
+ y?: number;
35
+ vw?: number;
36
+ vh?: number;
37
+ scrollPct?: number;
38
+ dwellMs?: number;
39
+ targetId?: string;
40
+ label?: string;
41
+ meta?: Record<string, unknown>;
42
+ }
43
+ /** The batched POST body sent to `${endpoint}/collect`. */
44
+ interface CollectBatch {
45
+ siteKey: string;
46
+ sessionId: string;
47
+ events: HeuristicsEvent[];
48
+ }
49
+ interface AttachHeuristicsSinkOptions {
50
+ /** Base URL, e.g. "/heuristics". POSTs to `${endpoint}/collect`. */
51
+ endpoint: string;
52
+ /** Identifies the site to the ingestion endpoint. */
53
+ siteKey: string;
54
+ /** Stable session id. Default: a generated "agent-<rand>" per attach. */
55
+ sessionId?: string;
56
+ /** Resolves the current path. Default: `() => location.pathname`. */
57
+ path?: () => string;
58
+ /** Which activity sources to record. Default "all". */
59
+ source?: "agent" | "flow" | "all";
60
+ /** Flush interval in ms. Default 2000. */
61
+ batchMs?: number;
62
+ }
63
+ /**
64
+ * Map one activity event to an `actor:"agent"` HeuristicsEvent. Activities
65
+ * carrying a finite `meta.dwellMs` become `kind:"dwell"`; everything else is a
66
+ * discrete `kind:"click"` with x/y/vw/vh pulled from numeric meta (default 0).
67
+ * Mirrors `fancy-heuristics-js/src/agent.ts` `mapActivityToEvent`.
68
+ */
69
+ declare function mapActivityToEvent(e: AutoActivityEvent, path: string): HeuristicsEvent;
70
+ /**
71
+ * Subscribe to the in-page agent activity bus and forward each matching event
72
+ * to the heuristics `/collect` endpoint as `actor:"agent"`. SSR-safe (returns a
73
+ * no-op when there is no `window`). Returns an unsubscribe that flushes the
74
+ * buffer and detaches all listeners/timers.
75
+ */
76
+ declare function attachHeuristicsSink(opts: AttachHeuristicsSinkOptions): () => void;
77
+
78
+ export { type AttachHeuristicsSinkOptions, type CollectBatch, type HeuristicsEvent, attachHeuristicsSink, mapActivityToEvent };
@@ -0,0 +1,115 @@
1
+ 'use strict';
2
+
3
+ var fancyAutoCommon = require('@particle-academy/fancy-auto-common');
4
+
5
+ // src/presence/registry.ts
6
+
7
+ // src/heuristics/sink.ts
8
+ function numericMeta(meta, key) {
9
+ const v = meta?.[key];
10
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
11
+ }
12
+ function mapActivityToEvent(e, path) {
13
+ const source = e.source ?? "agent";
14
+ const targetId = e.target?.elementId;
15
+ const label = e.target?.label;
16
+ const meta = {
17
+ action: e.action,
18
+ agentId: e.agentId,
19
+ source,
20
+ kind: e.target?.kind
21
+ };
22
+ const dwellMs = numericMeta(e.meta, "dwellMs");
23
+ if (dwellMs !== void 0) {
24
+ const ev2 = {
25
+ kind: "dwell",
26
+ actor: "agent",
27
+ path,
28
+ ts: e.timestamp,
29
+ dwellMs,
30
+ meta
31
+ };
32
+ if (targetId !== void 0) ev2.targetId = targetId;
33
+ if (label !== void 0) ev2.label = label;
34
+ return ev2;
35
+ }
36
+ const ev = {
37
+ kind: "click",
38
+ actor: "agent",
39
+ path,
40
+ ts: e.timestamp,
41
+ x: numericMeta(e.meta, "x") ?? 0,
42
+ y: numericMeta(e.meta, "y") ?? 0,
43
+ vw: numericMeta(e.meta, "vw") ?? 0,
44
+ vh: numericMeta(e.meta, "vh") ?? 0,
45
+ meta
46
+ };
47
+ if (targetId !== void 0) ev.targetId = targetId;
48
+ if (label !== void 0) ev.label = label;
49
+ return ev;
50
+ }
51
+ function randomId() {
52
+ return Math.random().toString(36).slice(2, 10);
53
+ }
54
+ function attachHeuristicsSink(opts) {
55
+ if (typeof window === "undefined") return () => {
56
+ };
57
+ const endpoint = opts.endpoint.replace(/\/$/, "");
58
+ const url = `${endpoint}/collect`;
59
+ const siteKey = opts.siteKey;
60
+ const sessionId = opts.sessionId ?? `agent-${randomId()}`;
61
+ const getPath = opts.path ?? (() => location.pathname);
62
+ const source = opts.source ?? "all";
63
+ const batchMs = opts.batchMs ?? 2e3;
64
+ const filter = source === "all" ? void 0 : { source };
65
+ let buffer = [];
66
+ function flush() {
67
+ if (buffer.length === 0) return;
68
+ const events = buffer;
69
+ buffer = [];
70
+ const batch = { siteKey, sessionId, events };
71
+ const body = JSON.stringify(batch);
72
+ try {
73
+ if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
74
+ const blob = new Blob([body], { type: "application/json" });
75
+ navigator.sendBeacon(url, blob);
76
+ return;
77
+ }
78
+ } catch {
79
+ }
80
+ try {
81
+ void fetch(url, {
82
+ method: "POST",
83
+ headers: { "content-type": "application/json" },
84
+ body,
85
+ keepalive: true
86
+ });
87
+ } catch {
88
+ }
89
+ }
90
+ const unsubscribeActivity = fancyAutoCommon.onActivity((e) => {
91
+ try {
92
+ buffer.push(mapActivityToEvent(e, getPath()));
93
+ } catch {
94
+ }
95
+ }, filter);
96
+ const timer = setInterval(flush, batchMs);
97
+ const onPageHide = () => flush();
98
+ const onVisibility = () => {
99
+ if (document.visibilityState === "hidden") flush();
100
+ };
101
+ window.addEventListener("pagehide", onPageHide);
102
+ document.addEventListener("visibilitychange", onVisibility);
103
+ return () => {
104
+ unsubscribeActivity();
105
+ window.removeEventListener("pagehide", onPageHide);
106
+ document.removeEventListener("visibilitychange", onVisibility);
107
+ clearInterval(timer);
108
+ flush();
109
+ };
110
+ }
111
+
112
+ exports.attachHeuristicsSink = attachHeuristicsSink;
113
+ exports.mapActivityToEvent = mapActivityToEvent;
114
+ //# sourceMappingURL=heuristics.cjs.map
115
+ //# sourceMappingURL=heuristics.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/heuristics/sink.ts"],"names":["ev","onActivity"],"mappings":";;;;;;;AAkEA,SAAS,WAAA,CACP,MACA,GAAA,EACoB;AACpB,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,OAAO,QAAA,CAAS,CAAC,IAAI,CAAA,GAAI,MAAA;AAC3D;AAQO,SAAS,kBAAA,CACd,GACA,IAAA,EACiB;AACjB,EAAA,MAAM,MAAA,GAAS,EAAE,MAAA,IAAU,OAAA;AAC3B,EAAA,MAAM,QAAA,GAAW,EAAE,MAAA,EAAQ,SAAA;AAC3B,EAAA,MAAM,KAAA,GAAQ,EAAE,MAAA,EAAQ,KAAA;AACxB,EAAA,MAAM,IAAA,GAAgC;AAAA,IACpC,QAAQ,CAAA,CAAE,MAAA;AAAA,IACV,SAAS,CAAA,CAAE,OAAA;AAAA,IACX,MAAA;AAAA,IACA,IAAA,EAAM,EAAE,MAAA,EAAQ;AAAA,GAClB;AAC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AACF","file":"heuristics.cjs","sourcesContent":["/**\n * In-browser heuristics analytics sink for agent traffic.\n *\n * Agent bridge mutations emit `AutoActivityEvent`s into the in-page\n * `@particle-academy/fancy-auto-common` activity bus (presence / cursors).\n * This sink — living in THIS package so it shares the SAME bundled\n * `fancy-auto-common` module instance the bridges emit into — subscribes to\n * that bus and POSTs each event to the `fancy-heuristics` `/collect` endpoint\n * as `actor:\"agent\"`, so agent traffic shows up in the heuristics dashboard.\n *\n * It does NOT depend on `fancy-heuristics` / `fancy-heuristics-js`: it only\n * emits the frozen wire shape over HTTP. The mapping mirrors\n * `fancy-heuristics-js/src/agent.ts` `mapActivityToEvent` — keep parity.\n */\nimport { onActivity, type AgentActivityEvent } from \"../presence\";\n\n/** What kind of interaction an event captures (mirrors fancy-heuristics-js). */\ntype HeuristicsEventKind = \"pageview\" | \"click\" | \"scroll\" | \"pointer\" | \"dwell\";\n\n/** Who produced the interaction. */\ntype HeuristicsActor = \"human\" | \"agent\";\n\n/**\n * A single interaction event — mirrors `fancy-heuristics-js` `HeuristicsEvent`.\n * Optional fields are omitted (never `null`) when not relevant to the `kind`.\n */\nexport interface HeuristicsEvent {\n kind: HeuristicsEventKind;\n actor: HeuristicsActor;\n /** location.pathname at capture time. */\n path: string;\n /** ms epoch. */\n ts: number;\n x?: number;\n y?: number;\n vw?: number;\n vh?: number;\n scrollPct?: number;\n dwellMs?: number;\n targetId?: string;\n label?: string;\n meta?: Record<string, unknown>;\n}\n\n/** The batched POST body sent to `${endpoint}/collect`. */\nexport interface CollectBatch {\n siteKey: string;\n sessionId: string;\n events: HeuristicsEvent[];\n}\n\nexport interface AttachHeuristicsSinkOptions {\n /** Base URL, e.g. \"/heuristics\". POSTs to `${endpoint}/collect`. */\n endpoint: string;\n /** Identifies the site to the ingestion endpoint. */\n siteKey: string;\n /** Stable session id. Default: a generated \"agent-<rand>\" per attach. */\n sessionId?: string;\n /** Resolves the current path. Default: `() => location.pathname`. */\n path?: () => string;\n /** Which activity sources to record. Default \"all\". */\n source?: \"agent\" | \"flow\" | \"all\";\n /** Flush interval in ms. Default 2000. */\n batchMs?: number;\n}\n\nfunction numericMeta(\n meta: Record<string, unknown> | undefined,\n key: string,\n): number | undefined {\n const v = meta?.[key];\n return typeof v === \"number\" && Number.isFinite(v) ? v : undefined;\n}\n\n/**\n * Map one activity event to an `actor:\"agent\"` HeuristicsEvent. Activities\n * carrying a finite `meta.dwellMs` become `kind:\"dwell\"`; everything else is a\n * discrete `kind:\"click\"` with x/y/vw/vh pulled from numeric meta (default 0).\n * Mirrors `fancy-heuristics-js/src/agent.ts` `mapActivityToEvent`.\n */\nexport function mapActivityToEvent(\n e: AgentActivityEvent,\n path: string,\n): HeuristicsEvent {\n const source = e.source ?? \"agent\";\n const targetId = e.target?.elementId;\n const label = e.target?.label;\n const meta: Record<string, unknown> = {\n action: e.action,\n agentId: e.agentId,\n source,\n kind: e.target?.kind,\n };\n const dwellMs = numericMeta(e.meta, \"dwellMs\");\n\n if (dwellMs !== undefined) {\n const ev: HeuristicsEvent = {\n kind: \"dwell\",\n actor: \"agent\",\n path,\n ts: e.timestamp,\n dwellMs,\n meta,\n };\n if (targetId !== undefined) ev.targetId = targetId;\n if (label !== undefined) ev.label = label;\n return ev;\n }\n\n const ev: HeuristicsEvent = {\n kind: \"click\",\n actor: \"agent\",\n path,\n ts: e.timestamp,\n x: numericMeta(e.meta, \"x\") ?? 0,\n y: numericMeta(e.meta, \"y\") ?? 0,\n vw: numericMeta(e.meta, \"vw\") ?? 0,\n vh: numericMeta(e.meta, \"vh\") ?? 0,\n meta,\n };\n if (targetId !== undefined) ev.targetId = targetId;\n if (label !== undefined) ev.label = label;\n return ev;\n}\n\nfunction randomId(): string {\n return Math.random().toString(36).slice(2, 10);\n}\n\n/**\n * Subscribe to the in-page agent activity bus and forward each matching event\n * to the heuristics `/collect` endpoint as `actor:\"agent\"`. SSR-safe (returns a\n * no-op when there is no `window`). Returns an unsubscribe that flushes the\n * buffer and detaches all listeners/timers.\n */\nexport function attachHeuristicsSink(\n opts: AttachHeuristicsSinkOptions,\n): () => void {\n // Browser guard — SSR-safe no-op.\n if (typeof window === \"undefined\") return () => {};\n\n const endpoint = opts.endpoint.replace(/\\/$/, \"\");\n const url = `${endpoint}/collect`;\n const siteKey = opts.siteKey;\n const sessionId = opts.sessionId ?? `agent-${randomId()}`;\n const getPath = opts.path ?? (() => location.pathname);\n const source = opts.source ?? \"all\";\n const batchMs = opts.batchMs ?? 2000;\n\n // onActivity's `source` filter is strict-equality; only set it when we want a\n // single source. \"all\" subscribes unfiltered.\n const filter = source === \"all\" ? undefined : { source };\n\n let buffer: HeuristicsEvent[] = [];\n\n function flush(): void {\n if (buffer.length === 0) return;\n const events = buffer;\n buffer = [];\n const batch: CollectBatch = { siteKey, sessionId, events };\n const body = JSON.stringify(batch);\n try {\n if (\n typeof navigator !== \"undefined\" &&\n typeof navigator.sendBeacon === \"function\"\n ) {\n const blob = new Blob([body], { type: \"application/json\" });\n navigator.sendBeacon(url, blob);\n return;\n }\n } catch {\n // fall through to fetch\n }\n try {\n void fetch(url, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body,\n keepalive: true,\n });\n } catch {\n // never throw from a flush\n }\n }\n\n const unsubscribeActivity = onActivity((e) => {\n try {\n buffer.push(mapActivityToEvent(e, getPath()));\n } catch {\n // never let a malformed event break the bus\n }\n }, filter);\n\n const timer: ReturnType<typeof setInterval> = setInterval(flush, batchMs);\n\n const onPageHide = () => flush();\n const onVisibility = () => {\n if (document.visibilityState === \"hidden\") flush();\n };\n window.addEventListener(\"pagehide\", onPageHide);\n document.addEventListener(\"visibilitychange\", onVisibility);\n\n return () => {\n unsubscribeActivity();\n window.removeEventListener(\"pagehide\", onPageHide);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n clearInterval(timer);\n flush();\n };\n}\n"]}
@@ -0,0 +1,6 @@
1
+ export { attachHeuristicsSink, mapActivityToEvent } from './chunk-7R6RMROL.js';
2
+ import './chunk-UCKJAUBY.js';
3
+ import './chunk-ULJL53DL.js';
4
+ import './chunk-C3TYI5TJ.js';
5
+ //# sourceMappingURL=heuristics.js.map
6
+ //# sourceMappingURL=heuristics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"heuristics.js"}
package/dist/index.cjs CHANGED
@@ -2490,6 +2490,7 @@ function constantTimeEqual(a, b) {
2490
2490
  // src/sharing/sse-relay.ts
2491
2491
  var SseRelayTransport = class {
2492
2492
  constructor(options) {
2493
+ this.disposed = false;
2493
2494
  this.sendQueue = [];
2494
2495
  this.connected = false;
2495
2496
  this.listeners = /* @__PURE__ */ new Set();
@@ -2500,26 +2501,45 @@ var SseRelayTransport = class {
2500
2501
  bindServer(server) {
2501
2502
  this.server = server;
2502
2503
  }
2503
- /** Open the SSE channel. Idempotent. */
2504
+ /** Open the receive channel. Idempotent. */
2504
2505
  start() {
2505
- if (this.connected || typeof window === "undefined") return;
2506
- const url = `${this.opts.baseUrl}/${encodeURIComponent(this.opts.sessionId)}/events?token=${encodeURIComponent(this.opts.token)}`;
2506
+ if (this.connected || this.disposed || typeof window === "undefined") return;
2507
2507
  this.setState("connecting");
2508
+ void import('@particle-academy/fancy-cf-relay').then(({ createRelayChannel }) => {
2509
+ if (this.connected || this.disposed) return;
2510
+ this.channel = createRelayChannel({
2511
+ baseUrl: this.opts.baseUrl,
2512
+ session: this.opts.sessionId,
2513
+ token: this.opts.token,
2514
+ transport: "auto",
2515
+ receiveDirection: "inbound",
2516
+ sendPath: "outbox",
2517
+ onFrame: (raw) => this.handleInbound(raw),
2518
+ onOpen: () => this.markOpen(),
2519
+ onError: () => this.setState("error"),
2520
+ fetchImpl: this.opts.fetch
2521
+ });
2522
+ this.channel.start();
2523
+ }).catch(() => {
2524
+ if (!this.disposed) this.startSse();
2525
+ });
2526
+ }
2527
+ /** Fallback receive leg: a plain EventSource (no fancy-cf-relay installed). */
2528
+ startSse() {
2529
+ if (this.connected || this.disposed) return;
2530
+ const url = `${this.opts.baseUrl}/${encodeURIComponent(this.opts.sessionId)}/events?token=${encodeURIComponent(this.opts.token)}`;
2508
2531
  const es = new EventSource(url, { withCredentials: false });
2509
2532
  this.es = es;
2510
- es.addEventListener("open", () => {
2511
- this.connected = true;
2512
- this.setState("open");
2513
- const queued = this.sendQueue.splice(0);
2514
- for (const msg of queued) this.postOut(msg);
2515
- });
2516
- es.addEventListener("mcp", (ev) => {
2517
- const raw = ev.data;
2518
- this.handleInbound(raw);
2519
- });
2520
- es.addEventListener("error", () => {
2521
- this.setState("error");
2522
- });
2533
+ es.addEventListener("open", () => this.markOpen());
2534
+ es.addEventListener("mcp", (ev) => this.handleInbound(ev.data));
2535
+ es.addEventListener("error", () => this.setState("error"));
2536
+ }
2537
+ /** Mark the channel live + flush any queued outbound frames. */
2538
+ markOpen() {
2539
+ this.connected = true;
2540
+ this.setState("open");
2541
+ const queued = this.sendQueue.splice(0);
2542
+ for (const msg of queued) this.postOut(msg);
2523
2543
  }
2524
2544
  send(message) {
2525
2545
  if (!this.connected) {
@@ -2529,6 +2549,9 @@ var SseRelayTransport = class {
2529
2549
  this.postOut(message);
2530
2550
  }
2531
2551
  close() {
2552
+ this.disposed = true;
2553
+ this.channel?.stop();
2554
+ this.channel = void 0;
2532
2555
  this.es?.close();
2533
2556
  this.es = void 0;
2534
2557
  this.connected = false;
@@ -3557,6 +3580,111 @@ function SimulateUsersButton({
3557
3580
 
3558
3581
  // src/presence/index.ts
3559
3582
  init_registry();
3583
+
3584
+ // src/heuristics/sink.ts
3585
+ function numericMeta(meta, key) {
3586
+ const v = meta?.[key];
3587
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
3588
+ }
3589
+ function mapActivityToEvent(e, path) {
3590
+ const source = e.source ?? "agent";
3591
+ const targetId = e.target?.elementId;
3592
+ const label = e.target?.label;
3593
+ const meta = {
3594
+ action: e.action,
3595
+ agentId: e.agentId,
3596
+ source,
3597
+ kind: e.target?.kind
3598
+ };
3599
+ const dwellMs = numericMeta(e.meta, "dwellMs");
3600
+ if (dwellMs !== void 0) {
3601
+ const ev2 = {
3602
+ kind: "dwell",
3603
+ actor: "agent",
3604
+ path,
3605
+ ts: e.timestamp,
3606
+ dwellMs,
3607
+ meta
3608
+ };
3609
+ if (targetId !== void 0) ev2.targetId = targetId;
3610
+ if (label !== void 0) ev2.label = label;
3611
+ return ev2;
3612
+ }
3613
+ const ev = {
3614
+ kind: "click",
3615
+ actor: "agent",
3616
+ path,
3617
+ ts: e.timestamp,
3618
+ x: numericMeta(e.meta, "x") ?? 0,
3619
+ y: numericMeta(e.meta, "y") ?? 0,
3620
+ vw: numericMeta(e.meta, "vw") ?? 0,
3621
+ vh: numericMeta(e.meta, "vh") ?? 0,
3622
+ meta
3623
+ };
3624
+ if (targetId !== void 0) ev.targetId = targetId;
3625
+ if (label !== void 0) ev.label = label;
3626
+ return ev;
3627
+ }
3628
+ function randomId2() {
3629
+ return Math.random().toString(36).slice(2, 10);
3630
+ }
3631
+ function attachHeuristicsSink(opts) {
3632
+ if (typeof window === "undefined") return () => {
3633
+ };
3634
+ const endpoint = opts.endpoint.replace(/\/$/, "");
3635
+ const url = `${endpoint}/collect`;
3636
+ const siteKey = opts.siteKey;
3637
+ const sessionId = opts.sessionId ?? `agent-${randomId2()}`;
3638
+ const getPath = opts.path ?? (() => location.pathname);
3639
+ const source = opts.source ?? "all";
3640
+ const batchMs = opts.batchMs ?? 2e3;
3641
+ const filter = source === "all" ? void 0 : { source };
3642
+ let buffer = [];
3643
+ function flush() {
3644
+ if (buffer.length === 0) return;
3645
+ const events = buffer;
3646
+ buffer = [];
3647
+ const batch = { siteKey, sessionId, events };
3648
+ const body = JSON.stringify(batch);
3649
+ try {
3650
+ if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
3651
+ const blob = new Blob([body], { type: "application/json" });
3652
+ navigator.sendBeacon(url, blob);
3653
+ return;
3654
+ }
3655
+ } catch {
3656
+ }
3657
+ try {
3658
+ void fetch(url, {
3659
+ method: "POST",
3660
+ headers: { "content-type": "application/json" },
3661
+ body,
3662
+ keepalive: true
3663
+ });
3664
+ } catch {
3665
+ }
3666
+ }
3667
+ const unsubscribeActivity = fancyAutoCommon.onActivity((e) => {
3668
+ try {
3669
+ buffer.push(mapActivityToEvent(e, getPath()));
3670
+ } catch {
3671
+ }
3672
+ }, filter);
3673
+ const timer = setInterval(flush, batchMs);
3674
+ const onPageHide = () => flush();
3675
+ const onVisibility = () => {
3676
+ if (document.visibilityState === "hidden") flush();
3677
+ };
3678
+ window.addEventListener("pagehide", onPageHide);
3679
+ document.addEventListener("visibilitychange", onVisibility);
3680
+ return () => {
3681
+ unsubscribeActivity();
3682
+ window.removeEventListener("pagehide", onPageHide);
3683
+ document.removeEventListener("visibilitychange", onVisibility);
3684
+ clearInterval(timer);
3685
+ flush();
3686
+ };
3687
+ }
3560
3688
  function useUndoStack(agentId, intervalMs = 500) {
3561
3689
  const [history, setHistory] = react.useState(() => fancyAutoCommon.readHistory(agentId));
3562
3690
  react.useEffect(() => {
@@ -3702,6 +3830,7 @@ exports.SseRelayTransport = SseRelayTransport;
3702
3830
  exports.ToolRegistry = ToolRegistry;
3703
3831
  exports.VscodeMark = VscodeMark;
3704
3832
  exports.WrenchMark = WrenchMark;
3833
+ exports.attachHeuristicsSink = attachHeuristicsSink;
3705
3834
  exports.attachInProcess = attachInProcess;
3706
3835
  exports.attachRelay = attachRelay;
3707
3836
  exports.attachSseRelay = attachSseRelay;
@@ -3720,6 +3849,7 @@ exports.describeSession = describeSession;
3720
3849
  exports.encodeBase64Json = encodeBase64Json;
3721
3850
  exports.ensureUndoToolsRegistered = ensureUndoToolsRegistered;
3722
3851
  exports.errorResult = errorResult;
3852
+ exports.mapActivityToHeuristicsEvent = mapActivityToEvent;
3723
3853
  exports.readSessionFromUrl = readSessionFromUrl;
3724
3854
  exports.registerChartsBridge = registerChartsBridge;
3725
3855
  exports.registerCodeBridge = registerCodeBridge;