@sagepilot-ai/react-native-events-addon 0.0.0-stage → 0.5.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.
@@ -0,0 +1,249 @@
1
+ package ai.sagepilot.events;
2
+
3
+ import android.app.Activity;
4
+ import android.app.Application;
5
+ import android.graphics.Rect;
6
+ import android.os.Bundle;
7
+ import android.os.SystemClock;
8
+ import android.view.MotionEvent;
9
+ import android.view.View;
10
+ import android.view.ViewGroup;
11
+ import android.view.Window;
12
+ import com.facebook.react.bridge.ReactApplicationContext;
13
+ import java.lang.reflect.InvocationTargetException;
14
+ import java.lang.reflect.Proxy;
15
+ import java.util.*;
16
+ import java.util.concurrent.ThreadPoolExecutor;
17
+ import java.util.concurrent.atomic.AtomicInteger;
18
+ import java.util.concurrent.atomic.AtomicLong;
19
+ import org.json.JSONObject;
20
+
21
+ /** Passive native lifecycle/window observers with a bounded handoff to one I/O worker. */
22
+ final class SagepilotEventsRuntime implements Application.ActivityLifecycleCallbacks {
23
+ private final ReactApplicationContext react;
24
+ private final ThreadPoolExecutor worker;
25
+ private final Map<Window, Wrapped> windows = new WeakHashMap<>();
26
+ private final AtomicInteger pending = new AtomicInteger();
27
+ private final AtomicLong pendingBytes = new AtomicLong(), dropped = new AtomicLong(), sequence = new AtomicLong();
28
+ private final String processId = UUID.randomUUID().toString();
29
+ private volatile JSONObject owner;
30
+ private volatile boolean enabled, registered;
31
+ private volatile long generation;
32
+ private JSONObject config;
33
+ private SagepilotEventsStore store;
34
+ private volatile SagepilotEventsStore.Batch prepared;
35
+ private volatile String preparedEpoch;
36
+ private boolean started;
37
+
38
+ /** Reuses the module's single bounded worker for projection and persistence. */
39
+ SagepilotEventsRuntime(ReactApplicationContext react, ThreadPoolExecutor worker) { this.react = react; this.worker = worker; }
40
+
41
+ /** Opens only SDK-owned no-backup files; no UI traversal or storage occurs on the JS thread. */
42
+ void configure(JSONObject config) throws Exception {
43
+ if (registered) throw new IllegalStateException("Only one Sagepilot app-event collector may run");
44
+ owner = null;
45
+ this.config = config;
46
+ store = new SagepilotEventsStore(new java.io.File(react.getNoBackupFilesDir(), "sagepilot-app-events"),
47
+ SagepilotEventsStore.scope(config.getString("workspace_id"), config.has("sdk_installation_id")
48
+ ? "sdk:" + config.getString("sdk_installation_id") : config.getString("channel_id")));
49
+ enabled = config.optBoolean("enabled", false); started = false; generation++;
50
+ if (!enabled) store.clear();
51
+ registered = true;
52
+ react.runOnUiQueueThread(() -> {
53
+ if (!registered) return;
54
+ ((Application)react.getApplicationContext()).registerActivityLifecycleCallbacks(this);
55
+ Activity current = react.getCurrentActivity(); if (current != null) attach(current);
56
+ });
57
+ }
58
+
59
+ /** Applies verified ownership on the worker; callbacks snapshot this immutable reference. */
60
+ String identity(JSONObject next) throws Exception {
61
+ owner = store.owner(next);
62
+ if (owner != null && enabled && !started) {
63
+ started = true;
64
+ emit("lifecycle", new JSONObject().put("state", "collector_started"), System.currentTimeMillis());
65
+ react.runOnUiQueueThread(() -> {
66
+ Activity current = react.getCurrentActivity();
67
+ if (current != null) try { emit("screen", new JSONObject().put("screen_class", current.getClass().getName()).put("state", "observed_at_start"), System.currentTimeMillis()); } catch (Exception error) { dropped.incrementAndGet(); }
68
+ });
69
+ }
70
+ return enabled && owner != null ? owner.getString("identity_epoch") : null;
71
+ }
72
+
73
+ /** Stops capture immediately before an asynchronous identity or consent transition. */
74
+ void fence() { owner = null; prepared = null; preparedEpoch = null; }
75
+
76
+ /** Revokes unuploaded records and invalidates queued descriptors when collection is disabled. */
77
+ String enabled(boolean next, JSONObject identity) throws Exception {
78
+ generation++; enabled = next;
79
+ if (!next) store.clear();
80
+ return identity(identity);
81
+ }
82
+
83
+ /** Returns only the current owner's bounded native-compressed batch. */
84
+ JSONObject batch(long bridgeDrops) throws Exception {
85
+ if (!enabled || owner == null) return null;
86
+ SagepilotEventsStore.Batch batch = store.nextBatch(owner, dropped.get() + bridgeDrops);
87
+ prepared = batch; preparedEpoch = owner.optString("identity_epoch");
88
+ return batch == null ? null : batch.metadata;
89
+ }
90
+
91
+ /** Releases only the exact current-owner lease to the native HTTP worker. */
92
+ byte[] uploadBody(String lease) throws Exception {
93
+ SagepilotEventsStore.Batch batch = prepared; JSONObject current = owner;
94
+ if (!enabled || !registered || current == null || batch == null || !lease.equals(batch.metadata.optString("lease")) || !current.optString("identity_epoch").equals(preparedEpoch)) throw new IllegalStateException("App-event upload lease expired");
95
+ return batch.gzip;
96
+ }
97
+
98
+ /** Commits explicit admission receipts against the exact native lease. */
99
+ void acknowledge(String lease, org.json.JSONArray ids) throws Exception { if (store != null) store.acknowledge(lease, ids); }
100
+
101
+ /** Projects supported network bodies after handoff; raw values are never written to the journal. */
102
+ void network(JSONObject input, Runnable complete) {
103
+ JSONObject captured = owner;
104
+ if (!enabled || captured == null || !captured.optString("identity_epoch").equals(input.optString("identity_epoch"))) { dropped.incrementAndGet(); complete.run(); return; }
105
+ int cost = input.optString("request_body").length() * 2 + input.optString("response_body").length() * 2 + 2048;
106
+ submit(captured, "network", input, input.optLong("occurred_at_ms", System.currentTimeMillis()), cost, true, complete);
107
+ }
108
+
109
+ /** Captures tiny immutable descriptors; disk, compression and JSON parsing stay off the callback. */
110
+ private void emit(String kind, JSONObject data, long occurred) {
111
+ JSONObject captured = owner;
112
+ if (enabled && captured != null) submit(captured, kind, data, occurred, 2048, false, null);
113
+ }
114
+
115
+ /** Enforces independent descriptor-count and raw-byte budgets before queueing work. */
116
+ private void submit(JSONObject captured, String kind, JSONObject data, long occurred, int cost, boolean network, Runnable complete) {
117
+ if (cost > 270336) { dropped.incrementAndGet(); if (complete != null) complete.run(); return; }
118
+ if (pending.incrementAndGet() > 128) { pending.decrementAndGet(); dropped.incrementAndGet(); if (complete != null) complete.run(); return; }
119
+ if (pendingBytes.addAndGet(cost) > 524288) { pendingBytes.addAndGet(-cost); pending.decrementAndGet(); dropped.incrementAndGet(); if (complete != null) complete.run(); return; }
120
+ long revision = generation, seq = sequence.incrementAndGet(), monotonic = SystemClock.elapsedRealtime();
121
+ String eventId = processId + "-" + seq;
122
+ try {
123
+ worker.execute(() -> {
124
+ try {
125
+ if (revision != generation || !enabled || !registered) { dropped.incrementAndGet(); return; }
126
+ JSONObject payload = network ? networkData(data) : data;
127
+ java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
128
+ format.setTimeZone(TimeZone.getTimeZone("UTC"));
129
+ JSONObject event = new JSONObject().put("event_id", eventId).put("kind", kind).put("occurred_at", format.format(new Date(occurred)))
130
+ .put("clock_source", "device_wall").put("clock_quality", "unverified").put("capture_generation", processId + "-" + revision)
131
+ .put("monotonic_ms", monotonic).put("sequence", seq).put("capture_process_id", processId).put("installation_id", store.installationId())
132
+ .put("workspace_id", config.getString("workspace_id"))
133
+ .put("sdk_version", config.getString("sdk_version")).put("addon_version", config.getString("addon_version"))
134
+ .put("platform", "android").put("owner", captured).put("data", payload).put("capture_gap_count", dropped.get());
135
+ if (config.has("sdk_installation_id")) {
136
+ event.put("device_installation_id", store.installationId()).put("installation_id", config.getString("sdk_installation_id"));
137
+ } else { event.put("channel_id", config.getString("channel_id")); }
138
+ store.append(event);
139
+ } catch (Exception error) { dropped.incrementAndGet(); }
140
+ finally { pending.decrementAndGet(); pendingBytes.addAndGet(-cost); if (complete != null) complete.run(); }
141
+ });
142
+ } catch (java.util.concurrent.RejectedExecutionException error) { pending.decrementAndGet(); pendingBytes.addAndGet(-cost); dropped.incrementAndGet(); if (complete != null) complete.run(); }
143
+ }
144
+
145
+ /** Fingerprints routes and projects typed context before any descriptor reaches the journal. */
146
+ private JSONObject networkData(JSONObject input) throws Exception {
147
+ JSONObject data = new JSONObject();
148
+ for (String key : new String[]{"method", "status", "duration_ms", "outcome", "body_omitted", "request_body_omitted", "request_id", "phase"}) if (input.has(key)) data.put(key, input.get(key));
149
+ String route = SagepilotEventsProjection.route(input.optString("route"));
150
+ if (route == null) throw new IllegalArgumentException("Invalid observation route");
151
+ data.put("route", route).put("route_version", 2);
152
+ for (String name : new String[]{"request_body", "response_body"}) if (input.has(name)) {
153
+ JSONObject projected = SagepilotEventsProjection.project(input.optString(name));
154
+ if (projected.has("omitted")) store.reject();
155
+ data.put(name.equals("request_body") ? "request" : "response", projected);
156
+ }
157
+ return data;
158
+ }
159
+
160
+ /** Returns small counters; it never bridges all queued observations into JavaScript. */
161
+ JSONObject diagnostics() throws Exception {
162
+ JSONObject result = store == null ? new JSONObject().put("pending_records", 0).put("pending_bytes", 0).put("dropped_records", 0).put("rejected_payloads", 0) : store.diagnostics();
163
+ return result.put("enabled", enabled && owner != null).put("worker_backlog", pending.get())
164
+ .put("dropped_records", result.optLong("dropped_records") + dropped.get()).put("network_observation_supported", true);
165
+ }
166
+
167
+ /** Detaches only this observer; wrappers owned by later instrumentation remain intact and inert. */
168
+ void stop() {
169
+ registered = false; enabled = false; fence(); generation++;
170
+ react.runOnUiQueueThread(() -> {
171
+ ((Application)react.getApplicationContext()).unregisterActivityLifecycleCallbacks(this);
172
+ for (Map.Entry<Window, Wrapped> item : new ArrayList<>(windows.entrySet())) if (item.getKey().getCallback() == item.getValue().proxy) item.getKey().setCallback(item.getValue().original);
173
+ windows.clear();
174
+ });
175
+ }
176
+
177
+ /** Chains every Window.Callback call, preserving original return values and host exceptions. */
178
+ private void attach(Activity activity) {
179
+ if (!registered) return;
180
+ Window window = activity.getWindow();
181
+ if (window == null || window.getCallback() == null) return;
182
+ Wrapped known = windows.get(window); if (known != null && window.getCallback() == known.proxy) return;
183
+ Window.Callback original = window.getCallback();
184
+ Window.Callback proxy = (Window.Callback)Proxy.newProxyInstance(Window.Callback.class.getClassLoader(), new Class<?>[]{Window.Callback.class}, (ignored, method, args) -> {
185
+ if (registered && enabled && owner != null && method.getName().equals("dispatchTouchEvent") && args != null && args[0] instanceof MotionEvent) {
186
+ try { touch(activity, (MotionEvent)args[0]); } catch (Exception error) { dropped.incrementAndGet(); }
187
+ }
188
+ try { return method.invoke(original, args); } catch (InvocationTargetException error) { throw error.getCause(); }
189
+ });
190
+ windows.put(window, new Wrapped(original, proxy)); window.setCallback(proxy);
191
+ }
192
+
193
+ /** Records completed/cancelled touches only; text entry and raw move streams are never captured. */
194
+ private void touch(Activity activity, MotionEvent event) throws Exception {
195
+ int action = event.getActionMasked();
196
+ if (action != MotionEvent.ACTION_UP && action != MotionEvent.ACTION_CANCEL) return;
197
+ View root = activity.getWindow().getDecorView();
198
+ View target = target(root, (int)event.getRawX(), (int)event.getRawY(), 0, new int[]{64});
199
+ JSONObject descriptor = new JSONObject().put("action", action == MotionEvent.ACTION_CANCEL ? "touch_cancelled" : "touch_ended")
200
+ .put("screen_class", activity.getClass().getName()).put("target_class", target.getClass().getName()).put("target_path", ancestry(target))
201
+ .put("native_tag", target.getId()).put("duration_ms", Math.max(0, event.getEventTime() - event.getDownTime()));
202
+ emit("interaction", descriptor, System.currentTimeMillis());
203
+ }
204
+
205
+ /** Captures structural ancestry without reading labels, text, app props or an unbounded child list. */
206
+ private org.json.JSONArray ancestry(View target) throws Exception {
207
+ org.json.JSONArray path = new org.json.JSONArray(); View current = target;
208
+ for (int depth = 0; current != null && depth < 8; depth++) {
209
+ android.view.ViewParent parent = current.getParent(); int index = -1;
210
+ if (parent instanceof ViewGroup && ((ViewGroup)parent).getChildCount() <= 64) index = ((ViewGroup)parent).indexOfChild(current);
211
+ path.put(new JSONObject().put("class", current.getClass().getName()).put("sibling_index", index).put("native_tag", current.getId()));
212
+ current = parent instanceof View ? (View)parent : null;
213
+ }
214
+ return path;
215
+ }
216
+
217
+ /** Finds a bounded native hit-target hint, never walking the entire view tree or reading text. */
218
+ private View target(View view, int x, int y, int depth, int[] budget) {
219
+ if (--budget[0] < 0 || depth >= 8 || !(view instanceof ViewGroup)) return view;
220
+ ViewGroup group = (ViewGroup)view; Rect bounds = new Rect();
221
+ for (int index = group.getChildCount() - 1; index >= 0 && budget[0] > 0; index--) {
222
+ budget[0]--; View child = group.getChildAt(index);
223
+ if (child.getVisibility() == View.VISIBLE && child.getGlobalVisibleRect(bounds) && bounds.contains(x, y)) return target(child, x, y, depth + 1, budget);
224
+ }
225
+ return view;
226
+ }
227
+
228
+ /** Observes native screen visibility; RN logical route names require separately supported visibility. */
229
+ @Override public void onActivityResumed(Activity activity) { attach(activity); try { emit("screen", new JSONObject().put("screen_class", activity.getClass().getName()).put("state", "resumed"), System.currentTimeMillis()); } catch (Exception error) { dropped.incrementAndGet(); } }
230
+ /** Captures an actual native pause without asserting a completed business action. */
231
+ @Override public void onActivityPaused(Activity activity) { try { emit("lifecycle", new JSONObject().put("state", "activity_paused"), System.currentTimeMillis()); } catch (Exception error) { dropped.incrementAndGet(); } }
232
+ /** Installs observers after the Activity has created its window. */
233
+ @Override public void onActivityCreated(Activity activity, Bundle state) { attach(activity); }
234
+ /** Activity start alone is not an app installation or purchase event. */
235
+ @Override public void onActivityStarted(Activity activity) {}
236
+ /** Activity stop is already represented by native pause visibility. */
237
+ @Override public void onActivityStopped(Activity activity) {}
238
+ /** Does not inspect persisted application state. */
239
+ @Override public void onActivitySaveInstanceState(Activity activity, Bundle state) {}
240
+ /** Releases this Activity's weak window tracking. */
241
+ @Override public void onActivityDestroyed(Activity activity) { windows.remove(activity.getWindow()); }
242
+
243
+ /** Retains the host callback so teardown never removes somebody else's instrumentation. */
244
+ private static final class Wrapped {
245
+ final Window.Callback original, proxy;
246
+ /** Remembers both sides of one callback chain. */
247
+ Wrapped(Window.Callback original, Window.Callback proxy) { this.original = original; this.proxy = proxy; }
248
+ }
249
+ }
@@ -0,0 +1,173 @@
1
+ package ai.sagepilot.events;
2
+
3
+ import org.json.JSONArray;
4
+ import org.json.JSONObject;
5
+ import java.io.*;
6
+ import java.nio.charset.StandardCharsets;
7
+ import java.security.MessageDigest;
8
+ import java.util.*;
9
+ import java.util.zip.GZIPOutputStream;
10
+
11
+ /** Single-worker file journal; platform collectors must never call it on a UI thread. */
12
+ public final class SagepilotEventsStore {
13
+ public static final int MAX_RECORDS = 2048, MAX_EVENT_BYTES = 32768, MAX_BATCH_BYTES = 131072;
14
+ public static final long MAX_BYTES = 10L * 1024 * 1024;
15
+ private final File directory;
16
+ private final LinkedHashMap<String, Entry> entries = new LinkedHashMap<>();
17
+ private long bytes, dropped, rejected;
18
+ private JSONObject metadata;
19
+ private String lease;
20
+ private Set<String> leased = new HashSet<>();
21
+
22
+ /** Recovers bounded records, preserving event IDs and capture ownership through a restart. */
23
+ public SagepilotEventsStore(File directory, String scope) throws Exception {
24
+ this.directory = directory;
25
+ if (!directory.isDirectory() && !directory.mkdirs()) throw new IOException("Could not create app-event journal");
26
+ File metadataFile = new File(directory, "metadata.json");
27
+ try { metadata = new JSONObject(read(metadataFile)); } catch (Exception error) { metadata = new JSONObject(); }
28
+ if (!scope.equals(metadata.optString("scope"))) {
29
+ for (File file : files()) { if (file.getName().endsWith(".event")) dropped++; if (!file.delete()) throw new IOException("Could not clear old app-event scope"); }
30
+ metadata = new JSONObject().put("scope", scope).put("installation_id", UUID.randomUUID().toString());
31
+ atomic(metadataFile, metadata.toString().getBytes(StandardCharsets.UTF_8));
32
+ }
33
+ File[] files = files();
34
+ Arrays.sort(files, Comparator.comparingLong(File::lastModified).thenComparing(File::getName));
35
+ for (File file : files) {
36
+ if (!file.getName().endsWith(".event")) { if (file.getName().endsWith(".tmp")) file.delete(); continue; }
37
+ try {
38
+ if (file.length() > MAX_EVENT_BYTES) throw new IOException("Oversized event");
39
+ JSONObject event = new JSONObject(read(file));
40
+ String id = event.getString("event_id");
41
+ entries.put(id, new Entry(file, file.length(), ownerKey(event.getJSONObject("owner")))); bytes += file.length();
42
+ } catch (Exception error) { file.delete(); rejected++; }
43
+ }
44
+ trim(0);
45
+ }
46
+
47
+ /** Returns a path-safe digest for one workspace/app binding. */
48
+ public static String scope(String workspace, String channel) throws Exception {
49
+ byte[] digest = MessageDigest.getInstance("SHA-256").digest((workspace + ":" + channel).getBytes(StandardCharsets.UTF_8));
50
+ StringBuilder result = new StringBuilder(); for (byte item : digest) result.append(String.format(Locale.ROOT, "%02x", item & 255));
51
+ return result.toString();
52
+ }
53
+
54
+ /** Supplies a pseudonymous installation identity within this app binding. */
55
+ public String installationId() throws Exception { return metadata.getString("installation_id"); }
56
+
57
+ /** Persists a new identity epoch only when verified session ownership actually changes. */
58
+ public JSONObject owner(JSONObject owner) throws Exception {
59
+ if (owner == null) return null;
60
+ JSONObject previous = metadata.optJSONObject("owner");
61
+ if (previous != null && ownerKey(previous).equals(ownerKey(owner))) return new JSONObject(previous.toString());
62
+ JSONObject next = new JSONObject(owner.toString()).put("identity_epoch", UUID.randomUUID().toString());
63
+ metadata.put("owner", next);
64
+ atomic(new File(directory, "metadata.json"), metadata.toString().getBytes(StandardCharsets.UTF_8));
65
+ return next;
66
+ }
67
+
68
+ /** Compares both the original session and customer; a bare customer match cannot adopt a backlog. */
69
+ public static String ownerKey(JSONObject owner) {
70
+ return new JSONArray().put(owner.optString("session_id")).put(owner.opt("customer_id")).toString();
71
+ }
72
+
73
+ /** Writes one complete record atomically and reports explicit overflow rather than growing indefinitely. */
74
+ public void append(JSONObject event) throws Exception {
75
+ byte[] data = event.toString().getBytes(StandardCharsets.UTF_8);
76
+ if (data.length > MAX_EVENT_BYTES) { rejected++; return; }
77
+ trim(data.length);
78
+ String id = event.getString("event_id");
79
+ if (!id.matches("[A-Za-z0-9-]{1,100}")) throw new IOException("Invalid internal event id");
80
+ if (entries.containsKey(id)) return;
81
+ File file = new File(directory, id + ".event");
82
+ atomic(file, data);
83
+ entries.put(id, new Entry(file, data.length, ownerKey(event.getJSONObject("owner")))); bytes += data.length;
84
+ }
85
+
86
+ /** Produces a gzip batch entirely on the native worker, without exposing raw bodies through JS. */
87
+ public Batch nextBatch(JSONObject owner, long nativeDropped) throws Exception {
88
+ JSONArray events = new JSONArray(), ids = new JSONArray(); int size = 64;
89
+ String key = ownerKey(owner);
90
+ for (Map.Entry<String, Entry> item : entries.entrySet()) {
91
+ Entry entry = item.getValue(); if (!entry.owner.equals(key)) continue;
92
+ if (events.length() >= 100 || size + entry.bytes > MAX_BATCH_BYTES - 1024) break;
93
+ events.put(new JSONObject(read(entry.file))); ids.put(item.getKey()); size += entry.bytes + 1;
94
+ }
95
+ if (events.length() == 0) return null;
96
+ byte[] body = new JSONObject().put("schema_version", 1).put("observations", events)
97
+ .put("capture_gaps", new JSONObject().put("quota_evicted", dropped).put("rejected_payloads", rejected).put("collector_dropped", nativeDropped)).toString().getBytes(StandardCharsets.UTF_8);
98
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
99
+ try (GZIPOutputStream gzip = new GZIPOutputStream(output)) { gzip.write(body); }
100
+ lease = UUID.randomUUID().toString(); leased.clear(); for (int i = 0; i < ids.length(); i++) leased.add(ids.getString(i));
101
+ return new Batch(new JSONObject().put("lease", lease).put("event_ids", ids), output.toByteArray());
102
+ }
103
+
104
+ /** Removes only members of the exact batch lease that received terminal admission receipts. */
105
+ public void acknowledge(String batchLease, JSONArray ids) throws Exception {
106
+ if (!Objects.equals(lease, batchLease)) return;
107
+ for (int i = 0; i < ids.length(); i++) {
108
+ String id = ids.getString(i); if (!leased.contains(id)) continue;
109
+ Entry entry = entries.get(id);
110
+ if (entry != null && !entry.file.delete()) throw new IOException("Could not acknowledge app event");
111
+ if (entry != null) { entries.remove(id); bytes -= entry.bytes; }
112
+ leased.remove(id);
113
+ }
114
+ }
115
+
116
+ /** Deletes unuploaded records on explicit collection revocation, without rewriting ownership. */
117
+ public void clear() throws Exception {
118
+ for (Entry entry : entries.values()) if (!entry.file.delete()) throw new IOException("Could not clear app events");
119
+ entries.clear(); bytes = 0; leased.clear(); lease = null;
120
+ metadata.remove("owner"); atomic(new File(directory, "metadata.json"), metadata.toString().getBytes(StandardCharsets.UTF_8));
121
+ }
122
+
123
+ /** Exposes bounded diagnostics, including quota eviction and malformed input counters. */
124
+ public JSONObject diagnostics() throws Exception {
125
+ return new JSONObject().put("pending_records", entries.size()).put("pending_bytes", bytes).put("dropped_records", dropped).put("rejected_payloads", rejected);
126
+ }
127
+
128
+ /** Accounts for an unsupported or unsafe network payload without retaining it. */
129
+ public void reject() { rejected++; }
130
+
131
+ /** Evicts oldest complete records before an append reaches the approved local hard caps. */
132
+ private void trim(long incoming) throws Exception {
133
+ while (!entries.isEmpty() && (entries.size() + (incoming > 0 ? 1 : 0) > MAX_RECORDS || bytes + incoming > MAX_BYTES)) {
134
+ Map.Entry<String, Entry> oldest = entries.entrySet().iterator().next();
135
+ if (!oldest.getValue().file.delete()) throw new IOException("Could not bound app-event journal");
136
+ bytes -= oldest.getValue().bytes; entries.remove(oldest.getKey()); dropped++;
137
+ }
138
+ }
139
+
140
+ /** Lists only this SDK-owned directory. */
141
+ private File[] files() { File[] files = directory.listFiles(); return files == null ? new File[0] : files; }
142
+
143
+ /** Reads only bounded journal records or the small metadata file. */
144
+ private static String read(File file) throws Exception {
145
+ if (!file.isFile() || file.length() > MAX_EVENT_BYTES) throw new IOException("Invalid app-event file");
146
+ try (FileInputStream input = new FileInputStream(file); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
147
+ byte[] buffer = new byte[4096]; int length;
148
+ while ((length = input.read(buffer)) != -1) { output.write(buffer, 0, length); if (output.size() > MAX_EVENT_BYTES) throw new IOException("Invalid app-event file"); }
149
+ return new String(output.toByteArray(), StandardCharsets.UTF_8);
150
+ }
151
+ }
152
+
153
+ /** Flushes a complete temporary record before an atomic same-directory rename. */
154
+ private static void atomic(File target, byte[] bytes) throws Exception {
155
+ File temporary = new File(target.getParentFile(), target.getName() + ".tmp");
156
+ try (FileOutputStream stream = new FileOutputStream(temporary)) { stream.write(bytes); stream.getFD().sync(); }
157
+ if (!temporary.renameTo(target)) throw new IOException("Could not commit app-event file");
158
+ }
159
+
160
+ /** Indexes bounded disk records without retaining their product payloads in memory. */
161
+ private static final class Entry {
162
+ final File file; final long bytes; final String owner;
163
+ /** Retains only file accounting and the original ownership key. */
164
+ Entry(File file, long bytes, String owner) { this.file = file; this.bytes = bytes; this.owner = owner; }
165
+ }
166
+
167
+ /** Keeps compression native while allowing the bridge to use Android's API-24-compatible Base64. */
168
+ public static final class Batch {
169
+ public final JSONObject metadata; public final byte[] gzip;
170
+ /** Retains the small receipt envelope and already-compressed upload bytes. */
171
+ Batch(JSONObject metadata, byte[] gzip) { this.metadata = metadata; this.gzip = gzip; }
172
+ }
173
+ }
@@ -0,0 +1,49 @@
1
+ type InstallationStorage = {
2
+ getItem(key: string): string | null | Promise<string | null>;
3
+ setItem(key: string, value: string): void | Promise<void>;
4
+ removeItem(key: string): void | Promise<void>;
5
+ };
6
+ type SagepilotInstallationOptions = {
7
+ key: string;
8
+ /** Gateway origin; HTTPS is required except for loopback development. */
9
+ apiHost?: string;
10
+ platform: "web" | "android" | "ios";
11
+ sdk: {
12
+ name: string;
13
+ version: string;
14
+ };
15
+ appId?: string;
16
+ fetch?: typeof fetch;
17
+ /** Optional scoped session persistence; tokens never enter the observation journal. */
18
+ storage?: InstallationStorage;
19
+ };
20
+
21
+ type SagepilotEventsDiagnostics = {
22
+ enabled: boolean;
23
+ pending_records: number;
24
+ pending_bytes: number;
25
+ dropped_records: number;
26
+ rejected_payloads: number;
27
+ worker_backlog: number;
28
+ network_observation_supported: boolean;
29
+ };
30
+
31
+ /** Starts the existing native collectors with a channel-free anonymous installation session. */
32
+ declare function createSagepilotInstallationEvents(options: Omit<SagepilotInstallationOptions, "platform" | "sdk"> & {
33
+ anonymousId: string;
34
+ collectionEnabled?: boolean;
35
+ onError?: (error: unknown) => void;
36
+ }): {
37
+ /** Bootstraps installation scope and attaches the existing native lifecycle, projection and journal. */
38
+ start(): Promise<void>;
39
+ /** Applies local permission while keeping server collection policy authoritative. */
40
+ setCollectionEnabled(enabled: boolean): Promise<void>;
41
+ /** Flushes the existing native journal through the installation ingress. */
42
+ flush(): Promise<void>;
43
+ /** Reads aggregate native diagnostics without exposing observation bodies. */
44
+ diagnostics(): Promise<SagepilotEventsDiagnostics>;
45
+ /** Stops the collector and its installation session. */
46
+ destroy(): void;
47
+ };
48
+
49
+ export { type SagepilotEventsDiagnostics, createSagepilotInstallationEvents };
@@ -0,0 +1,49 @@
1
+ type InstallationStorage = {
2
+ getItem(key: string): string | null | Promise<string | null>;
3
+ setItem(key: string, value: string): void | Promise<void>;
4
+ removeItem(key: string): void | Promise<void>;
5
+ };
6
+ type SagepilotInstallationOptions = {
7
+ key: string;
8
+ /** Gateway origin; HTTPS is required except for loopback development. */
9
+ apiHost?: string;
10
+ platform: "web" | "android" | "ios";
11
+ sdk: {
12
+ name: string;
13
+ version: string;
14
+ };
15
+ appId?: string;
16
+ fetch?: typeof fetch;
17
+ /** Optional scoped session persistence; tokens never enter the observation journal. */
18
+ storage?: InstallationStorage;
19
+ };
20
+
21
+ type SagepilotEventsDiagnostics = {
22
+ enabled: boolean;
23
+ pending_records: number;
24
+ pending_bytes: number;
25
+ dropped_records: number;
26
+ rejected_payloads: number;
27
+ worker_backlog: number;
28
+ network_observation_supported: boolean;
29
+ };
30
+
31
+ /** Starts the existing native collectors with a channel-free anonymous installation session. */
32
+ declare function createSagepilotInstallationEvents(options: Omit<SagepilotInstallationOptions, "platform" | "sdk"> & {
33
+ anonymousId: string;
34
+ collectionEnabled?: boolean;
35
+ onError?: (error: unknown) => void;
36
+ }): {
37
+ /** Bootstraps installation scope and attaches the existing native lifecycle, projection and journal. */
38
+ start(): Promise<void>;
39
+ /** Applies local permission while keeping server collection policy authoritative. */
40
+ setCollectionEnabled(enabled: boolean): Promise<void>;
41
+ /** Flushes the existing native journal through the installation ingress. */
42
+ flush(): Promise<void>;
43
+ /** Reads aggregate native diagnostics without exposing observation bodies. */
44
+ diagnostics(): Promise<SagepilotEventsDiagnostics>;
45
+ /** Stops the collector and its installation session. */
46
+ destroy(): void;
47
+ };
48
+
49
+ export { type SagepilotEventsDiagnostics, createSagepilotInstallationEvents };