@openscout/scout 0.2.60 → 0.2.61

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.
@@ -10189,114 +10189,6 @@ function buildScoutReturnAddress(input) {
10189
10189
  }
10190
10190
  return next;
10191
10191
  }
10192
- // ../protocol/dist/collaboration.js
10193
- function isQuestionTerminalState(state) {
10194
- return state === "closed" || state === "declined";
10195
- }
10196
- function isWorkItemTerminalState(state) {
10197
- return state === "done" || state === "cancelled";
10198
- }
10199
- function collaborationRequiresNextMoveOwner(record) {
10200
- if (record.kind === "question") {
10201
- return !isQuestionTerminalState(record.state);
10202
- }
10203
- return !isWorkItemTerminalState(record.state);
10204
- }
10205
- function collaborationRequiresOwner(record) {
10206
- return record.kind === "work_item" && !isWorkItemTerminalState(record.state);
10207
- }
10208
- function collaborationRequiresWaitingOn(record) {
10209
- return record.kind === "work_item" && record.state === "waiting";
10210
- }
10211
- function collaborationRequiresAcceptance(record) {
10212
- if (record.acceptanceState === "none") {
10213
- return false;
10214
- }
10215
- if (record.kind === "question") {
10216
- return Boolean(record.askedById && record.askedOfId);
10217
- }
10218
- return Boolean(record.requestedById);
10219
- }
10220
- function validateCollaborationRecord(record) {
10221
- const errors = [];
10222
- if (!record.id.trim()) {
10223
- errors.push("collaboration record id is required");
10224
- }
10225
- if (!record.title.trim()) {
10226
- errors.push("collaboration title is required");
10227
- }
10228
- if (!record.createdById.trim()) {
10229
- errors.push("createdById is required");
10230
- }
10231
- if (record.parentId && record.parentId === record.id) {
10232
- errors.push("parentId cannot reference the record itself");
10233
- }
10234
- if (record.createdAt > record.updatedAt) {
10235
- errors.push("updatedAt must be greater than or equal to createdAt");
10236
- }
10237
- if (collaborationRequiresOwner(record) && !record.ownerId) {
10238
- errors.push("non-terminal work items require ownerId");
10239
- }
10240
- if (collaborationRequiresNextMoveOwner(record) && !record.nextMoveOwnerId) {
10241
- errors.push("non-terminal collaboration records require nextMoveOwnerId");
10242
- }
10243
- if (record.kind === "work_item" && collaborationRequiresWaitingOn(record) && !record.waitingOn) {
10244
- errors.push("waiting work items require waitingOn");
10245
- }
10246
- if (record.kind === "question") {
10247
- if (record.spawnedWorkItemId && record.spawnedWorkItemId === record.id) {
10248
- errors.push("question spawnedWorkItemId cannot reference the question itself");
10249
- }
10250
- } else if (record.waitingOn?.targetId && record.waitingOn.targetId === record.id) {
10251
- errors.push("waitingOn.targetId cannot reference the work item itself");
10252
- }
10253
- if (record.acceptanceState !== "none" && !collaborationRequiresAcceptance(record)) {
10254
- errors.push("acceptanceState requires the corresponding requester and reviewer identities");
10255
- }
10256
- return errors;
10257
- }
10258
- function assertValidCollaborationRecord(record) {
10259
- const errors = validateCollaborationRecord(record);
10260
- if (errors.length > 0) {
10261
- throw new Error(errors.join("; "));
10262
- }
10263
- }
10264
- function validateCollaborationEvent(event, record) {
10265
- const errors = [];
10266
- if (!event.id.trim()) {
10267
- errors.push("collaboration event id is required");
10268
- }
10269
- if (!event.recordId.trim()) {
10270
- errors.push("collaboration event recordId is required");
10271
- }
10272
- if (!event.actorId.trim()) {
10273
- errors.push("collaboration event actorId is required");
10274
- }
10275
- if (record) {
10276
- if (record.id !== event.recordId) {
10277
- errors.push("collaboration event recordId does not match the target record");
10278
- }
10279
- if (record.kind !== event.recordKind) {
10280
- errors.push("collaboration event recordKind does not match the target record");
10281
- }
10282
- }
10283
- if (event.kind === "answered" && event.recordKind !== "question") {
10284
- errors.push("answered events only apply to questions");
10285
- }
10286
- if (event.kind === "declined" && event.recordKind !== "question") {
10287
- errors.push("declined events only apply to questions");
10288
- }
10289
- if ((event.kind === "waiting" || event.kind === "progressed" || event.kind === "review_requested" || event.kind === "done" || event.kind === "cancelled") && event.recordKind !== "work_item") {
10290
- errors.push(`${event.kind} events only apply to work items`);
10291
- }
10292
- return errors;
10293
- }
10294
- function assertValidCollaborationEvent(event, record) {
10295
- const errors = validateCollaborationEvent(event, record);
10296
- if (errors.length > 0) {
10297
- throw new Error(errors.join("; "));
10298
- }
10299
- }
10300
10192
  // ../runtime/src/user-project-hints.ts
10301
10193
  import { readdir, readFile as readFile3, stat } from "fs/promises";
10302
10194
  import { homedir as homedir11 } from "os";
@@ -31932,2364 +31824,187 @@ function date4(params) {
31932
31824
 
31933
31825
  // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v4/classic/external.js
31934
31826
  config(en_default());
31935
- // ../runtime/src/registry.ts
31936
- function createRuntimeRegistrySnapshot(value = {}) {
31937
- return {
31938
- nodes: value.nodes ?? {},
31939
- actors: value.actors ?? {},
31940
- agents: value.agents ?? {},
31941
- endpoints: value.endpoints ?? {},
31942
- conversations: value.conversations ?? {},
31943
- bindings: value.bindings ?? {},
31944
- messages: value.messages ?? {},
31945
- flights: value.flights ?? {},
31946
- collaborationRecords: value.collaborationRecords ?? {}
31947
- };
31948
- }
31949
- // ../runtime/src/planner.ts
31950
- function createDeliveryId(messageId, targetId, reason, transport) {
31951
- return `del-${messageId}-${targetId}-${reason}-${transport}`;
31952
- }
31953
- function unique(values) {
31954
- return [...new Set(values)];
31955
- }
31956
- function resolveVisibilityAudience(message, conversation) {
31957
- if (message.audience?.visibleTo?.length) {
31958
- return unique(message.audience.visibleTo);
31959
- }
31960
- return unique(conversation.participantIds.filter((participantId) => participantId !== message.actorId));
31961
- }
31962
- function resolveNotifyAudience(message) {
31963
- const fromMentions = (message.mentions ?? []).map((mention) => mention.actorId);
31964
- const explicit = message.audience?.notify ?? [];
31965
- return unique([...fromMentions, ...explicit].filter((actorId) => actorId !== message.actorId));
31827
+ // ../runtime/src/mobile-push.ts
31828
+ import { Database as Database2 } from "bun:sqlite";
31829
+ import { mkdirSync as mkdirSync9, readFileSync as readFileSync10 } from "fs";
31830
+ import { connect as connectHttp2 } from "http2";
31831
+ import { createPrivateKey, sign as signWithKey } from "crypto";
31832
+ import { dirname as dirname7, join as join18 } from "path";
31833
+ var MOBILE_PUSH_SCHEMA = `
31834
+ CREATE TABLE IF NOT EXISTS mobile_push_registrations (
31835
+ id TEXT PRIMARY KEY,
31836
+ device_id TEXT NOT NULL,
31837
+ platform TEXT NOT NULL,
31838
+ app_bundle_id TEXT NOT NULL,
31839
+ apns_environment TEXT NOT NULL,
31840
+ push_token TEXT NOT NULL,
31841
+ authorization_status TEXT NOT NULL,
31842
+ app_version TEXT,
31843
+ build_number TEXT,
31844
+ device_model TEXT,
31845
+ system_version TEXT,
31846
+ created_at INTEGER NOT NULL,
31847
+ updated_at INTEGER NOT NULL
31848
+ );
31849
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_mobile_push_registrations_device_bundle_env
31850
+ ON mobile_push_registrations (device_id, platform, app_bundle_id, apns_environment);
31851
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_mobile_push_registrations_push_token
31852
+ ON mobile_push_registrations (push_token);
31853
+ CREATE INDEX IF NOT EXISTS idx_mobile_push_registrations_device_updated_at
31854
+ ON mobile_push_registrations (device_id, updated_at DESC);
31855
+ `;
31856
+ var dbHandle = null;
31857
+ var dbPath = null;
31858
+ var cachedApnsJwt = null;
31859
+ function resolveControlPlaneDbPath() {
31860
+ return join18(resolveOpenScoutSupportPaths().controlHome, "control-plane.sqlite");
31966
31861
  }
31967
- function resolveInvocationAudience(message) {
31968
- return unique((message.audience?.invoke ?? []).filter((actorId) => actorId !== message.actorId));
31862
+ function ensureMobilePushSchema(database) {
31863
+ database.exec("PRAGMA busy_timeout = 5000;");
31864
+ database.exec("PRAGMA journal_mode = WAL;");
31865
+ database.exec(MOBILE_PUSH_SCHEMA);
31969
31866
  }
31970
- function planTargetDelivery(message, route2, reason, policy) {
31971
- return {
31972
- id: createDeliveryId(message.id, route2.targetId, reason, route2.transport),
31973
- messageId: message.id,
31974
- targetId: route2.targetId,
31975
- targetNodeId: route2.nodeId,
31976
- targetKind: route2.targetKind,
31977
- transport: route2.transport,
31978
- reason,
31979
- policy,
31980
- status: "pending",
31981
- bindingId: route2.bindingId
31982
- };
31983
- }
31984
- function planMessageDeliveries(input) {
31985
- const visibilityIds = new Set(resolveVisibilityAudience(input.message, input.conversation));
31986
- const notifyIds = new Set(resolveNotifyAudience(input.message));
31987
- const invokeIds = new Set(resolveInvocationAudience(input.message));
31988
- const deliveries2 = new Map;
31989
- for (const route2 of input.participantRoutes) {
31990
- if (visibilityIds.has(route2.targetId)) {
31991
- const intent = planTargetDelivery(input.message, {
31992
- ...route2,
31993
- transport: route2.nodeId && input.localNodeId && route2.nodeId !== input.localNodeId ? "peer_broker" : route2.transport
31994
- }, input.conversation.kind === "direct" || input.conversation.kind === "group_direct" ? "direct_message" : "conversation_visibility", "durable");
31995
- deliveries2.set(intent.id, intent);
31996
- }
31997
- if (notifyIds.has(route2.targetId)) {
31998
- const intent = planTargetDelivery(input.message, {
31999
- ...route2,
32000
- transport: route2.nodeId && input.localNodeId && route2.nodeId !== input.localNodeId ? "peer_broker" : route2.transport
32001
- }, "mention", "must_ack");
32002
- deliveries2.set(intent.id, intent);
32003
- }
32004
- if (invokeIds.has(route2.targetId)) {
32005
- const intent = planTargetDelivery(input.message, {
32006
- ...route2,
32007
- transport: route2.nodeId && input.localNodeId && route2.nodeId !== input.localNodeId ? "peer_broker" : route2.transport
32008
- }, "invocation", "must_ack");
32009
- deliveries2.set(intent.id, intent);
32010
- }
32011
- if (input.message.speech?.text && route2.speechEnabled) {
32012
- const speechIntent = planTargetDelivery(input.message, {
32013
- ...route2,
32014
- transport: route2.transport === "local_socket" ? "native_voice" : "tts",
32015
- targetKind: route2.targetKind === "device" ? "voice_session" : route2.targetKind
32016
- }, "speech", "best_effort");
32017
- deliveries2.set(speechIntent.id, speechIntent);
32018
- }
32019
- }
32020
- for (const route2 of input.bindingRoutes ?? []) {
32021
- const intent = planTargetDelivery(input.message, route2, "bridge_outbound", "durable");
32022
- deliveries2.set(intent.id, intent);
32023
- }
32024
- return [...deliveries2.values()];
32025
- }
32026
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/entity.js
32027
- var entityKind = Symbol.for("drizzle:entityKind");
32028
- var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
32029
- function is(value, type) {
32030
- if (!value || typeof value !== "object") {
32031
- return false;
32032
- }
32033
- if (value instanceof type) {
32034
- return true;
32035
- }
32036
- if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
32037
- throw new Error(`Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);
31867
+ function writeDb() {
31868
+ const nextPath = resolveControlPlaneDbPath();
31869
+ if (dbHandle && dbPath !== nextPath) {
31870
+ dbHandle.close();
31871
+ dbHandle = null;
32038
31872
  }
32039
- let cls = Object.getPrototypeOf(value).constructor;
32040
- if (cls) {
32041
- while (cls) {
32042
- if (entityKind in cls && cls[entityKind] === type[entityKind]) {
32043
- return true;
32044
- }
32045
- cls = Object.getPrototypeOf(cls);
32046
- }
31873
+ if (!dbHandle) {
31874
+ mkdirSync9(dirname7(nextPath), { recursive: true });
31875
+ dbHandle = new Database2(nextPath, { create: true });
31876
+ dbPath = nextPath;
31877
+ ensureMobilePushSchema(dbHandle);
32047
31878
  }
32048
- return false;
31879
+ return dbHandle;
32049
31880
  }
32050
-
32051
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/column.js
32052
- class Column {
32053
- constructor(table, config2) {
32054
- this.table = table;
32055
- this.config = config2;
32056
- this.name = config2.name;
32057
- this.keyAsName = config2.keyAsName;
32058
- this.notNull = config2.notNull;
32059
- this.default = config2.default;
32060
- this.defaultFn = config2.defaultFn;
32061
- this.onUpdateFn = config2.onUpdateFn;
32062
- this.hasDefault = config2.hasDefault;
32063
- this.primary = config2.primaryKey;
32064
- this.isUnique = config2.isUnique;
32065
- this.uniqueName = config2.uniqueName;
32066
- this.uniqueType = config2.uniqueType;
32067
- this.dataType = config2.dataType;
32068
- this.columnType = config2.columnType;
32069
- this.generated = config2.generated;
32070
- this.generatedIdentity = config2.generatedIdentity;
32071
- }
32072
- static [entityKind] = "Column";
32073
- name;
32074
- keyAsName;
32075
- primary;
32076
- notNull;
32077
- default;
32078
- defaultFn;
32079
- onUpdateFn;
32080
- hasDefault;
32081
- isUnique;
32082
- uniqueName;
32083
- uniqueType;
32084
- dataType;
32085
- columnType;
32086
- enumValues = undefined;
32087
- generated = undefined;
32088
- generatedIdentity = undefined;
32089
- config;
32090
- mapFromDriverValue(value) {
32091
- return value;
32092
- }
32093
- mapToDriverValue(value) {
32094
- return value;
32095
- }
32096
- shouldDisableInsert() {
32097
- return this.config.generated !== undefined && this.config.generated.type !== "byDefault";
32098
- }
31881
+ function normalizeToken(token) {
31882
+ return token.trim().replace(/[<>\s]/g, "").toLowerCase();
32099
31883
  }
32100
-
32101
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/column-builder.js
32102
- class ColumnBuilder {
32103
- static [entityKind] = "ColumnBuilder";
32104
- config;
32105
- constructor(name, dataType, columnType) {
32106
- this.config = {
32107
- name,
32108
- keyAsName: name === "",
32109
- notNull: false,
32110
- default: undefined,
32111
- hasDefault: false,
32112
- primaryKey: false,
32113
- isUnique: false,
32114
- uniqueName: undefined,
32115
- uniqueType: undefined,
32116
- dataType,
32117
- columnType,
32118
- generated: undefined
32119
- };
32120
- }
32121
- $type() {
32122
- return this;
32123
- }
32124
- notNull() {
32125
- this.config.notNull = true;
32126
- return this;
32127
- }
32128
- default(value) {
32129
- this.config.default = value;
32130
- this.config.hasDefault = true;
32131
- return this;
32132
- }
32133
- $defaultFn(fn) {
32134
- this.config.defaultFn = fn;
32135
- this.config.hasDefault = true;
32136
- return this;
32137
- }
32138
- $default = this.$defaultFn;
32139
- $onUpdateFn(fn) {
32140
- this.config.onUpdateFn = fn;
32141
- this.config.hasDefault = true;
32142
- return this;
32143
- }
32144
- $onUpdate = this.$onUpdateFn;
32145
- primaryKey() {
32146
- this.config.primaryKey = true;
32147
- this.config.notNull = true;
32148
- return this;
32149
- }
32150
- setName(name) {
32151
- if (this.config.name !== "")
32152
- return;
32153
- this.config.name = name;
31884
+ function pushAllowed(status) {
31885
+ switch (status) {
31886
+ case "authorized":
31887
+ case "provisional":
31888
+ case "ephemeral":
31889
+ return true;
31890
+ case "denied":
31891
+ case "notDetermined":
31892
+ return false;
32154
31893
  }
32155
31894
  }
32156
-
32157
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/table.utils.js
32158
- var TableName = Symbol.for("drizzle:Name");
32159
-
32160
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/tracing-utils.js
32161
- function iife(fn, ...args) {
32162
- return fn(...args);
32163
- }
32164
-
32165
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/pg-core/unique-constraint.js
32166
- function uniqueKeyName(table, columns) {
32167
- return `${table[TableName]}_${columns.join("_")}_unique`;
31895
+ function tokenSuffix(token) {
31896
+ return token.length <= 8 ? token : token.slice(-8);
32168
31897
  }
32169
-
32170
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/pg-core/columns/common.js
32171
- class PgColumn extends Column {
32172
- constructor(table, config2) {
32173
- if (!config2.uniqueName) {
32174
- config2.uniqueName = uniqueKeyName(table, [config2.name]);
32175
- }
32176
- super(table, config2);
32177
- this.table = table;
32178
- }
32179
- static [entityKind] = "PgColumn";
31898
+ function rowToRegistration(row) {
31899
+ return {
31900
+ id: row.id,
31901
+ deviceId: row.device_id,
31902
+ platform: row.platform,
31903
+ appBundleId: row.app_bundle_id,
31904
+ apnsEnvironment: row.apns_environment,
31905
+ pushToken: row.push_token,
31906
+ authorizationStatus: row.authorization_status,
31907
+ appVersion: row.app_version,
31908
+ buildNumber: row.build_number,
31909
+ deviceModel: row.device_model,
31910
+ systemVersion: row.system_version,
31911
+ createdAt: row.created_at,
31912
+ updatedAt: row.updated_at
31913
+ };
32180
31914
  }
32181
-
32182
- class ExtraConfigColumn extends PgColumn {
32183
- static [entityKind] = "ExtraConfigColumn";
32184
- getSQLType() {
32185
- return this.getSQLType();
32186
- }
32187
- indexConfig = {
32188
- order: this.config.order ?? "asc",
32189
- nulls: this.config.nulls ?? "last",
32190
- opClass: this.config.opClass
32191
- };
32192
- defaultConfig = {
32193
- order: "asc",
32194
- nulls: "last",
32195
- opClass: undefined
32196
- };
32197
- asc() {
32198
- this.indexConfig.order = "asc";
32199
- return this;
32200
- }
32201
- desc() {
32202
- this.indexConfig.order = "desc";
32203
- return this;
32204
- }
32205
- nullsFirst() {
32206
- this.indexConfig.nulls = "first";
32207
- return this;
31915
+ function syncMobilePushRegistration(input) {
31916
+ const database = writeDb();
31917
+ const now = Date.now();
31918
+ const deviceId = input.deviceId.trim();
31919
+ const platform = input.platform;
31920
+ const appBundleId = input.appBundleId.trim();
31921
+ const apnsEnvironment = input.apnsEnvironment;
31922
+ const authorizationStatus = input.authorizationStatus;
31923
+ const pushToken = input.pushToken?.trim() ? normalizeToken(input.pushToken) : null;
31924
+ if (!deviceId || !appBundleId) {
31925
+ throw new Error("deviceId and appBundleId are required");
32208
31926
  }
32209
- nullsLast() {
32210
- this.indexConfig.nulls = "last";
32211
- return this;
31927
+ if (!pushAllowed(authorizationStatus)) {
31928
+ database.query(`DELETE FROM mobile_push_registrations
31929
+ WHERE device_id = ?1
31930
+ AND platform = ?2
31931
+ AND app_bundle_id = ?3
31932
+ AND apns_environment = ?4`).run(deviceId, platform, appBundleId, apnsEnvironment);
31933
+ return { ok: true, registered: false, removed: true, token: null };
32212
31934
  }
32213
- op(opClass) {
32214
- this.indexConfig.opClass = opClass;
32215
- return this;
31935
+ if (!pushToken) {
31936
+ return { ok: true, registered: false, removed: false, token: null };
32216
31937
  }
31938
+ database.query(`DELETE FROM mobile_push_registrations
31939
+ WHERE push_token = ?1
31940
+ AND NOT (
31941
+ device_id = ?2
31942
+ AND platform = ?3
31943
+ AND app_bundle_id = ?4
31944
+ AND apns_environment = ?5
31945
+ )`).run(pushToken, deviceId, platform, appBundleId, apnsEnvironment);
31946
+ const existing = database.query(`SELECT id, created_at
31947
+ FROM mobile_push_registrations
31948
+ WHERE device_id = ?1
31949
+ AND platform = ?2
31950
+ AND app_bundle_id = ?3
31951
+ AND apns_environment = ?4
31952
+ LIMIT 1`).get(deviceId, platform, appBundleId, apnsEnvironment);
31953
+ const id = existing?.id ?? `push-${deviceId}-${platform}-${appBundleId}-${apnsEnvironment}`.replace(/[^a-zA-Z0-9._-]+/g, "-");
31954
+ database.query(`INSERT INTO mobile_push_registrations (
31955
+ id,
31956
+ device_id,
31957
+ platform,
31958
+ app_bundle_id,
31959
+ apns_environment,
31960
+ push_token,
31961
+ authorization_status,
31962
+ app_version,
31963
+ build_number,
31964
+ device_model,
31965
+ system_version,
31966
+ created_at,
31967
+ updated_at
31968
+ ) VALUES (
31969
+ ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13
31970
+ )
31971
+ ON CONFLICT(device_id, platform, app_bundle_id, apns_environment)
31972
+ DO UPDATE SET
31973
+ push_token = excluded.push_token,
31974
+ authorization_status = excluded.authorization_status,
31975
+ app_version = excluded.app_version,
31976
+ build_number = excluded.build_number,
31977
+ device_model = excluded.device_model,
31978
+ system_version = excluded.system_version,
31979
+ updated_at = excluded.updated_at`).run(id, deviceId, platform, appBundleId, apnsEnvironment, pushToken, authorizationStatus, input.appVersion?.trim() || null, input.buildNumber?.trim() || null, input.deviceModel?.trim() || null, input.systemVersion?.trim() || null, existing?.created_at ?? now, now);
31980
+ return { ok: true, registered: true, removed: false, token: pushToken };
32217
31981
  }
32218
-
32219
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/pg-core/columns/enum.js
32220
- class PgEnumObjectColumn extends PgColumn {
32221
- static [entityKind] = "PgEnumObjectColumn";
32222
- enum;
32223
- enumValues = this.config.enum.enumValues;
32224
- constructor(table, config2) {
32225
- super(table, config2);
32226
- this.enum = config2.enum;
31982
+ function listMobilePushRegistrations(filters) {
31983
+ const database = writeDb();
31984
+ const where = [];
31985
+ const params = [];
31986
+ if (filters?.deviceId?.trim()) {
31987
+ where.push(`device_id = ?${params.length + 1}`);
31988
+ params.push(filters.deviceId.trim());
32227
31989
  }
32228
- getSQLType() {
32229
- return this.enum.enumName;
31990
+ if (filters?.platform?.trim()) {
31991
+ where.push(`platform = ?${params.length + 1}`);
31992
+ params.push(filters.platform.trim());
32230
31993
  }
31994
+ const clause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
31995
+ const rows = database.query(`SELECT *
31996
+ FROM mobile_push_registrations
31997
+ ${clause}
31998
+ ORDER BY updated_at DESC, id ASC`).all(...params);
31999
+ return rows.map(rowToRegistration);
32231
32000
  }
32232
- var isPgEnumSym = Symbol.for("drizzle:isPgEnum");
32233
- function isPgEnum(obj) {
32234
- return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
32001
+ function listActiveMobilePushRegistrations() {
32002
+ return listMobilePushRegistrations().filter((registration) => pushAllowed(registration.authorizationStatus) && registration.pushToken.trim().length > 0);
32235
32003
  }
32236
- class PgEnumColumn extends PgColumn {
32237
- static [entityKind] = "PgEnumColumn";
32238
- enum = this.config.enum;
32239
- enumValues = this.config.enum.enumValues;
32240
- constructor(table, config2) {
32241
- super(table, config2);
32242
- this.enum = config2.enum;
32243
- }
32244
- getSQLType() {
32245
- return this.enum.enumName;
32246
- }
32247
- }
32248
-
32249
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/subquery.js
32250
- class Subquery {
32251
- static [entityKind] = "Subquery";
32252
- constructor(sql, fields, alias, isWith = false, usedTables = []) {
32253
- this._ = {
32254
- brand: "Subquery",
32255
- sql,
32256
- selectedFields: fields,
32257
- alias,
32258
- isWith,
32259
- usedTables
32260
- };
32261
- }
32262
- }
32263
-
32264
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/version.js
32265
- var version2 = "0.45.2";
32266
-
32267
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/tracing.js
32268
- var otel;
32269
- var rawTracer;
32270
- var tracer = {
32271
- startActiveSpan(name, fn) {
32272
- if (!otel) {
32273
- return fn();
32274
- }
32275
- if (!rawTracer) {
32276
- rawTracer = otel.trace.getTracer("drizzle-orm", version2);
32277
- }
32278
- return iife((otel2, rawTracer2) => rawTracer2.startActiveSpan(name, (span) => {
32279
- try {
32280
- return fn(span);
32281
- } catch (e) {
32282
- span.setStatus({
32283
- code: otel2.SpanStatusCode.ERROR,
32284
- message: e instanceof Error ? e.message : "Unknown error"
32285
- });
32286
- throw e;
32287
- } finally {
32288
- span.end();
32289
- }
32290
- }), otel, rawTracer);
32291
- }
32292
- };
32293
-
32294
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/view-common.js
32295
- var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
32296
-
32297
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/table.js
32298
- var Schema = Symbol.for("drizzle:Schema");
32299
- var Columns = Symbol.for("drizzle:Columns");
32300
- var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
32301
- var OriginalName = Symbol.for("drizzle:OriginalName");
32302
- var BaseName = Symbol.for("drizzle:BaseName");
32303
- var IsAlias = Symbol.for("drizzle:IsAlias");
32304
- var ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
32305
- var IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
32306
-
32307
- class Table {
32308
- static [entityKind] = "Table";
32309
- static Symbol = {
32310
- Name: TableName,
32311
- Schema,
32312
- OriginalName,
32313
- Columns,
32314
- ExtraConfigColumns,
32315
- BaseName,
32316
- IsAlias,
32317
- ExtraConfigBuilder
32318
- };
32319
- [TableName];
32320
- [OriginalName];
32321
- [Schema];
32322
- [Columns];
32323
- [ExtraConfigColumns];
32324
- [BaseName];
32325
- [IsAlias] = false;
32326
- [IsDrizzleTable] = true;
32327
- [ExtraConfigBuilder] = undefined;
32328
- constructor(name, schema, baseName) {
32329
- this[TableName] = this[OriginalName] = name;
32330
- this[Schema] = schema;
32331
- this[BaseName] = baseName;
32332
- }
32333
- }
32334
-
32335
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sql/sql.js
32336
- function isSQLWrapper(value) {
32337
- return value !== null && value !== undefined && typeof value.getSQL === "function";
32338
- }
32339
- function mergeQueries(queries) {
32340
- const result = { sql: "", params: [] };
32341
- for (const query of queries) {
32342
- result.sql += query.sql;
32343
- result.params.push(...query.params);
32344
- if (query.typings?.length) {
32345
- if (!result.typings) {
32346
- result.typings = [];
32347
- }
32348
- result.typings.push(...query.typings);
32349
- }
32350
- }
32351
- return result;
32352
- }
32353
-
32354
- class StringChunk {
32355
- static [entityKind] = "StringChunk";
32356
- value;
32357
- constructor(value) {
32358
- this.value = Array.isArray(value) ? value : [value];
32359
- }
32360
- getSQL() {
32361
- return new SQL([this]);
32362
- }
32363
- }
32364
-
32365
- class SQL {
32366
- constructor(queryChunks) {
32367
- this.queryChunks = queryChunks;
32368
- for (const chunk of queryChunks) {
32369
- if (is(chunk, Table)) {
32370
- const schemaName = chunk[Table.Symbol.Schema];
32371
- this.usedTables.push(schemaName === undefined ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name]);
32372
- }
32373
- }
32374
- }
32375
- static [entityKind] = "SQL";
32376
- decoder = noopDecoder;
32377
- shouldInlineParams = false;
32378
- usedTables = [];
32379
- append(query) {
32380
- this.queryChunks.push(...query.queryChunks);
32381
- return this;
32382
- }
32383
- toQuery(config2) {
32384
- return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
32385
- const query = this.buildQueryFromSourceParams(this.queryChunks, config2);
32386
- span?.setAttributes({
32387
- "drizzle.query.text": query.sql,
32388
- "drizzle.query.params": JSON.stringify(query.params)
32389
- });
32390
- return query;
32391
- });
32392
- }
32393
- buildQueryFromSourceParams(chunks, _config) {
32394
- const config2 = Object.assign({}, _config, {
32395
- inlineParams: _config.inlineParams || this.shouldInlineParams,
32396
- paramStartIndex: _config.paramStartIndex || { value: 0 }
32397
- });
32398
- const {
32399
- casing,
32400
- escapeName,
32401
- escapeParam,
32402
- prepareTyping,
32403
- inlineParams,
32404
- paramStartIndex
32405
- } = config2;
32406
- return mergeQueries(chunks.map((chunk) => {
32407
- if (is(chunk, StringChunk)) {
32408
- return { sql: chunk.value.join(""), params: [] };
32409
- }
32410
- if (is(chunk, Name)) {
32411
- return { sql: escapeName(chunk.value), params: [] };
32412
- }
32413
- if (chunk === undefined) {
32414
- return { sql: "", params: [] };
32415
- }
32416
- if (Array.isArray(chunk)) {
32417
- const result = [new StringChunk("(")];
32418
- for (const [i, p] of chunk.entries()) {
32419
- result.push(p);
32420
- if (i < chunk.length - 1) {
32421
- result.push(new StringChunk(", "));
32422
- }
32423
- }
32424
- result.push(new StringChunk(")"));
32425
- return this.buildQueryFromSourceParams(result, config2);
32426
- }
32427
- if (is(chunk, SQL)) {
32428
- return this.buildQueryFromSourceParams(chunk.queryChunks, {
32429
- ...config2,
32430
- inlineParams: inlineParams || chunk.shouldInlineParams
32431
- });
32432
- }
32433
- if (is(chunk, Table)) {
32434
- const schemaName = chunk[Table.Symbol.Schema];
32435
- const tableName = chunk[Table.Symbol.Name];
32436
- return {
32437
- sql: schemaName === undefined || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
32438
- params: []
32439
- };
32440
- }
32441
- if (is(chunk, Column)) {
32442
- const columnName = casing.getColumnCasing(chunk);
32443
- if (_config.invokeSource === "indexes") {
32444
- return { sql: escapeName(columnName), params: [] };
32445
- }
32446
- const schemaName = chunk.table[Table.Symbol.Schema];
32447
- return {
32448
- sql: chunk.table[IsAlias] || schemaName === undefined ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
32449
- params: []
32450
- };
32451
- }
32452
- if (is(chunk, View)) {
32453
- const schemaName = chunk[ViewBaseConfig].schema;
32454
- const viewName = chunk[ViewBaseConfig].name;
32455
- return {
32456
- sql: schemaName === undefined || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
32457
- params: []
32458
- };
32459
- }
32460
- if (is(chunk, Param)) {
32461
- if (is(chunk.value, Placeholder)) {
32462
- return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
32463
- }
32464
- const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
32465
- if (is(mappedValue, SQL)) {
32466
- return this.buildQueryFromSourceParams([mappedValue], config2);
32467
- }
32468
- if (inlineParams) {
32469
- return { sql: this.mapInlineParam(mappedValue, config2), params: [] };
32470
- }
32471
- let typings = ["none"];
32472
- if (prepareTyping) {
32473
- typings = [prepareTyping(chunk.encoder)];
32474
- }
32475
- return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
32476
- }
32477
- if (is(chunk, Placeholder)) {
32478
- return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
32479
- }
32480
- if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {
32481
- return { sql: escapeName(chunk.fieldAlias), params: [] };
32482
- }
32483
- if (is(chunk, Subquery)) {
32484
- if (chunk._.isWith) {
32485
- return { sql: escapeName(chunk._.alias), params: [] };
32486
- }
32487
- return this.buildQueryFromSourceParams([
32488
- new StringChunk("("),
32489
- chunk._.sql,
32490
- new StringChunk(") "),
32491
- new Name(chunk._.alias)
32492
- ], config2);
32493
- }
32494
- if (isPgEnum(chunk)) {
32495
- if (chunk.schema) {
32496
- return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
32497
- }
32498
- return { sql: escapeName(chunk.enumName), params: [] };
32499
- }
32500
- if (isSQLWrapper(chunk)) {
32501
- if (chunk.shouldOmitSQLParens?.()) {
32502
- return this.buildQueryFromSourceParams([chunk.getSQL()], config2);
32503
- }
32504
- return this.buildQueryFromSourceParams([
32505
- new StringChunk("("),
32506
- chunk.getSQL(),
32507
- new StringChunk(")")
32508
- ], config2);
32509
- }
32510
- if (inlineParams) {
32511
- return { sql: this.mapInlineParam(chunk, config2), params: [] };
32512
- }
32513
- return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
32514
- }));
32515
- }
32516
- mapInlineParam(chunk, { escapeString }) {
32517
- if (chunk === null) {
32518
- return "null";
32519
- }
32520
- if (typeof chunk === "number" || typeof chunk === "boolean") {
32521
- return chunk.toString();
32522
- }
32523
- if (typeof chunk === "string") {
32524
- return escapeString(chunk);
32525
- }
32526
- if (typeof chunk === "object") {
32527
- const mappedValueAsString = chunk.toString();
32528
- if (mappedValueAsString === "[object Object]") {
32529
- return escapeString(JSON.stringify(chunk));
32530
- }
32531
- return escapeString(mappedValueAsString);
32532
- }
32533
- throw new Error("Unexpected param value: " + chunk);
32534
- }
32535
- getSQL() {
32536
- return this;
32537
- }
32538
- as(alias) {
32539
- if (alias === undefined) {
32540
- return this;
32541
- }
32542
- return new SQL.Aliased(this, alias);
32543
- }
32544
- mapWith(decoder) {
32545
- this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
32546
- return this;
32547
- }
32548
- inlineParams() {
32549
- this.shouldInlineParams = true;
32550
- return this;
32551
- }
32552
- if(condition) {
32553
- return condition ? this : undefined;
32554
- }
32555
- }
32556
-
32557
- class Name {
32558
- constructor(value) {
32559
- this.value = value;
32560
- }
32561
- static [entityKind] = "Name";
32562
- brand;
32563
- getSQL() {
32564
- return new SQL([this]);
32565
- }
32566
- }
32567
- var noopDecoder = {
32568
- mapFromDriverValue: (value) => value
32569
- };
32570
- var noopEncoder = {
32571
- mapToDriverValue: (value) => value
32572
- };
32573
- var noopMapper = {
32574
- ...noopDecoder,
32575
- ...noopEncoder
32576
- };
32577
-
32578
- class Param {
32579
- constructor(value, encoder = noopEncoder) {
32580
- this.value = value;
32581
- this.encoder = encoder;
32582
- }
32583
- static [entityKind] = "Param";
32584
- brand;
32585
- getSQL() {
32586
- return new SQL([this]);
32587
- }
32588
- }
32589
- function sql(strings, ...params) {
32590
- const queryChunks = [];
32591
- if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
32592
- queryChunks.push(new StringChunk(strings[0]));
32593
- }
32594
- for (const [paramIndex, param2] of params.entries()) {
32595
- queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
32596
- }
32597
- return new SQL(queryChunks);
32598
- }
32599
- ((sql2) => {
32600
- function empty() {
32601
- return new SQL([]);
32602
- }
32603
- sql2.empty = empty;
32604
- function fromList(list) {
32605
- return new SQL(list);
32606
- }
32607
- sql2.fromList = fromList;
32608
- function raw(str) {
32609
- return new SQL([new StringChunk(str)]);
32610
- }
32611
- sql2.raw = raw;
32612
- function join18(chunks, separator) {
32613
- const result = [];
32614
- for (const [i, chunk] of chunks.entries()) {
32615
- if (i > 0 && separator !== undefined) {
32616
- result.push(separator);
32617
- }
32618
- result.push(chunk);
32619
- }
32620
- return new SQL(result);
32621
- }
32622
- sql2.join = join18;
32623
- function identifier(value) {
32624
- return new Name(value);
32625
- }
32626
- sql2.identifier = identifier;
32627
- function placeholder2(name2) {
32628
- return new Placeholder(name2);
32629
- }
32630
- sql2.placeholder = placeholder2;
32631
- function param2(value, encoder) {
32632
- return new Param(value, encoder);
32633
- }
32634
- sql2.param = param2;
32635
- })(sql || (sql = {}));
32636
- ((SQL2) => {
32637
-
32638
- class Aliased {
32639
- constructor(sql2, fieldAlias) {
32640
- this.sql = sql2;
32641
- this.fieldAlias = fieldAlias;
32642
- }
32643
- static [entityKind] = "SQL.Aliased";
32644
- isSelectionField = false;
32645
- getSQL() {
32646
- return this.sql;
32647
- }
32648
- clone() {
32649
- return new Aliased(this.sql, this.fieldAlias);
32650
- }
32651
- }
32652
- SQL2.Aliased = Aliased;
32653
- })(SQL || (SQL = {}));
32654
-
32655
- class Placeholder {
32656
- constructor(name2) {
32657
- this.name = name2;
32658
- }
32659
- static [entityKind] = "Placeholder";
32660
- getSQL() {
32661
- return new SQL([this]);
32662
- }
32663
- }
32664
- var IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
32665
-
32666
- class View {
32667
- static [entityKind] = "View";
32668
- [ViewBaseConfig];
32669
- [IsDrizzleView] = true;
32670
- constructor({ name: name2, schema, selectedFields, query }) {
32671
- this[ViewBaseConfig] = {
32672
- name: name2,
32673
- originalName: name2,
32674
- schema,
32675
- selectedFields,
32676
- query,
32677
- isExisting: !query,
32678
- isAlias: false
32679
- };
32680
- }
32681
- getSQL() {
32682
- return new SQL([this]);
32683
- }
32684
- }
32685
- Column.prototype.getSQL = function() {
32686
- return new SQL([this]);
32687
- };
32688
- Table.prototype.getSQL = function() {
32689
- return new SQL([this]);
32690
- };
32691
- Subquery.prototype.getSQL = function() {
32692
- return new SQL([this]);
32693
- };
32694
-
32695
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/utils.js
32696
- function getColumnNameAndConfig(a, b) {
32697
- return {
32698
- name: typeof a === "string" && a.length > 0 ? a : "",
32699
- config: typeof a === "object" ? a : b
32700
- };
32701
- }
32702
- var textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder;
32703
-
32704
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
32705
- class ForeignKeyBuilder {
32706
- static [entityKind] = "SQLiteForeignKeyBuilder";
32707
- reference;
32708
- _onUpdate;
32709
- _onDelete;
32710
- constructor(config2, actions) {
32711
- this.reference = () => {
32712
- const { name, columns, foreignColumns } = config2();
32713
- return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };
32714
- };
32715
- if (actions) {
32716
- this._onUpdate = actions.onUpdate;
32717
- this._onDelete = actions.onDelete;
32718
- }
32719
- }
32720
- onUpdate(action) {
32721
- this._onUpdate = action;
32722
- return this;
32723
- }
32724
- onDelete(action) {
32725
- this._onDelete = action;
32726
- return this;
32727
- }
32728
- build(table) {
32729
- return new ForeignKey(table, this);
32730
- }
32731
- }
32732
-
32733
- class ForeignKey {
32734
- constructor(table, builder) {
32735
- this.table = table;
32736
- this.reference = builder.reference;
32737
- this.onUpdate = builder._onUpdate;
32738
- this.onDelete = builder._onDelete;
32739
- }
32740
- static [entityKind] = "SQLiteForeignKey";
32741
- reference;
32742
- onUpdate;
32743
- onDelete;
32744
- getName() {
32745
- const { name, columns, foreignColumns } = this.reference();
32746
- const columnNames = columns.map((column) => column.name);
32747
- const foreignColumnNames = foreignColumns.map((column) => column.name);
32748
- const chunks = [
32749
- this.table[TableName],
32750
- ...columnNames,
32751
- foreignColumns[0].table[TableName],
32752
- ...foreignColumnNames
32753
- ];
32754
- return name ?? `${chunks.join("_")}_fk`;
32755
- }
32756
- }
32757
-
32758
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
32759
- function uniqueKeyName2(table, columns) {
32760
- return `${table[TableName]}_${columns.join("_")}_unique`;
32761
- }
32762
-
32763
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/columns/common.js
32764
- class SQLiteColumnBuilder extends ColumnBuilder {
32765
- static [entityKind] = "SQLiteColumnBuilder";
32766
- foreignKeyConfigs = [];
32767
- references(ref, actions = {}) {
32768
- this.foreignKeyConfigs.push({ ref, actions });
32769
- return this;
32770
- }
32771
- unique(name) {
32772
- this.config.isUnique = true;
32773
- this.config.uniqueName = name;
32774
- return this;
32775
- }
32776
- generatedAlwaysAs(as, config2) {
32777
- this.config.generated = {
32778
- as,
32779
- type: "always",
32780
- mode: config2?.mode ?? "virtual"
32781
- };
32782
- return this;
32783
- }
32784
- buildForeignKeys(column, table) {
32785
- return this.foreignKeyConfigs.map(({ ref, actions }) => {
32786
- return ((ref2, actions2) => {
32787
- const builder = new ForeignKeyBuilder(() => {
32788
- const foreignColumn = ref2();
32789
- return { columns: [column], foreignColumns: [foreignColumn] };
32790
- });
32791
- if (actions2.onUpdate) {
32792
- builder.onUpdate(actions2.onUpdate);
32793
- }
32794
- if (actions2.onDelete) {
32795
- builder.onDelete(actions2.onDelete);
32796
- }
32797
- return builder.build(table);
32798
- })(ref, actions);
32799
- });
32800
- }
32801
- }
32802
-
32803
- class SQLiteColumn extends Column {
32804
- constructor(table, config2) {
32805
- if (!config2.uniqueName) {
32806
- config2.uniqueName = uniqueKeyName2(table, [config2.name]);
32807
- }
32808
- super(table, config2);
32809
- this.table = table;
32810
- }
32811
- static [entityKind] = "SQLiteColumn";
32812
- }
32813
-
32814
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/columns/blob.js
32815
- class SQLiteBigIntBuilder extends SQLiteColumnBuilder {
32816
- static [entityKind] = "SQLiteBigIntBuilder";
32817
- constructor(name) {
32818
- super(name, "bigint", "SQLiteBigInt");
32819
- }
32820
- build(table) {
32821
- return new SQLiteBigInt(table, this.config);
32822
- }
32823
- }
32824
-
32825
- class SQLiteBigInt extends SQLiteColumn {
32826
- static [entityKind] = "SQLiteBigInt";
32827
- getSQLType() {
32828
- return "blob";
32829
- }
32830
- mapFromDriverValue(value) {
32831
- if (typeof Buffer !== "undefined" && Buffer.from) {
32832
- const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value);
32833
- return BigInt(buf.toString("utf8"));
32834
- }
32835
- return BigInt(textDecoder.decode(value));
32836
- }
32837
- mapToDriverValue(value) {
32838
- return Buffer.from(value.toString());
32839
- }
32840
- }
32841
-
32842
- class SQLiteBlobJsonBuilder extends SQLiteColumnBuilder {
32843
- static [entityKind] = "SQLiteBlobJsonBuilder";
32844
- constructor(name) {
32845
- super(name, "json", "SQLiteBlobJson");
32846
- }
32847
- build(table) {
32848
- return new SQLiteBlobJson(table, this.config);
32849
- }
32850
- }
32851
-
32852
- class SQLiteBlobJson extends SQLiteColumn {
32853
- static [entityKind] = "SQLiteBlobJson";
32854
- getSQLType() {
32855
- return "blob";
32856
- }
32857
- mapFromDriverValue(value) {
32858
- if (typeof Buffer !== "undefined" && Buffer.from) {
32859
- const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value);
32860
- return JSON.parse(buf.toString("utf8"));
32861
- }
32862
- return JSON.parse(textDecoder.decode(value));
32863
- }
32864
- mapToDriverValue(value) {
32865
- return Buffer.from(JSON.stringify(value));
32866
- }
32867
- }
32868
-
32869
- class SQLiteBlobBufferBuilder extends SQLiteColumnBuilder {
32870
- static [entityKind] = "SQLiteBlobBufferBuilder";
32871
- constructor(name) {
32872
- super(name, "buffer", "SQLiteBlobBuffer");
32873
- }
32874
- build(table) {
32875
- return new SQLiteBlobBuffer(table, this.config);
32876
- }
32877
- }
32878
-
32879
- class SQLiteBlobBuffer extends SQLiteColumn {
32880
- static [entityKind] = "SQLiteBlobBuffer";
32881
- mapFromDriverValue(value) {
32882
- if (Buffer.isBuffer(value)) {
32883
- return value;
32884
- }
32885
- return Buffer.from(value);
32886
- }
32887
- getSQLType() {
32888
- return "blob";
32889
- }
32890
- }
32891
- function blob(a, b) {
32892
- const { name, config: config2 } = getColumnNameAndConfig(a, b);
32893
- if (config2?.mode === "json") {
32894
- return new SQLiteBlobJsonBuilder(name);
32895
- }
32896
- if (config2?.mode === "bigint") {
32897
- return new SQLiteBigIntBuilder(name);
32898
- }
32899
- return new SQLiteBlobBufferBuilder(name);
32900
- }
32901
-
32902
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/columns/custom.js
32903
- class SQLiteCustomColumnBuilder extends SQLiteColumnBuilder {
32904
- static [entityKind] = "SQLiteCustomColumnBuilder";
32905
- constructor(name, fieldConfig, customTypeParams) {
32906
- super(name, "custom", "SQLiteCustomColumn");
32907
- this.config.fieldConfig = fieldConfig;
32908
- this.config.customTypeParams = customTypeParams;
32909
- }
32910
- build(table) {
32911
- return new SQLiteCustomColumn(table, this.config);
32912
- }
32913
- }
32914
-
32915
- class SQLiteCustomColumn extends SQLiteColumn {
32916
- static [entityKind] = "SQLiteCustomColumn";
32917
- sqlName;
32918
- mapTo;
32919
- mapFrom;
32920
- constructor(table, config2) {
32921
- super(table, config2);
32922
- this.sqlName = config2.customTypeParams.dataType(config2.fieldConfig);
32923
- this.mapTo = config2.customTypeParams.toDriver;
32924
- this.mapFrom = config2.customTypeParams.fromDriver;
32925
- }
32926
- getSQLType() {
32927
- return this.sqlName;
32928
- }
32929
- mapFromDriverValue(value) {
32930
- return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
32931
- }
32932
- mapToDriverValue(value) {
32933
- return typeof this.mapTo === "function" ? this.mapTo(value) : value;
32934
- }
32935
- }
32936
- function customType(customTypeParams) {
32937
- return (a, b) => {
32938
- const { name, config: config2 } = getColumnNameAndConfig(a, b);
32939
- return new SQLiteCustomColumnBuilder(name, config2, customTypeParams);
32940
- };
32941
- }
32942
-
32943
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/columns/integer.js
32944
- class SQLiteBaseIntegerBuilder extends SQLiteColumnBuilder {
32945
- static [entityKind] = "SQLiteBaseIntegerBuilder";
32946
- constructor(name, dataType, columnType) {
32947
- super(name, dataType, columnType);
32948
- this.config.autoIncrement = false;
32949
- }
32950
- primaryKey(config2) {
32951
- if (config2?.autoIncrement) {
32952
- this.config.autoIncrement = true;
32953
- }
32954
- this.config.hasDefault = true;
32955
- return super.primaryKey();
32956
- }
32957
- }
32958
-
32959
- class SQLiteBaseInteger extends SQLiteColumn {
32960
- static [entityKind] = "SQLiteBaseInteger";
32961
- autoIncrement = this.config.autoIncrement;
32962
- getSQLType() {
32963
- return "integer";
32964
- }
32965
- }
32966
-
32967
- class SQLiteIntegerBuilder extends SQLiteBaseIntegerBuilder {
32968
- static [entityKind] = "SQLiteIntegerBuilder";
32969
- constructor(name) {
32970
- super(name, "number", "SQLiteInteger");
32971
- }
32972
- build(table) {
32973
- return new SQLiteInteger(table, this.config);
32974
- }
32975
- }
32976
-
32977
- class SQLiteInteger extends SQLiteBaseInteger {
32978
- static [entityKind] = "SQLiteInteger";
32979
- }
32980
-
32981
- class SQLiteTimestampBuilder extends SQLiteBaseIntegerBuilder {
32982
- static [entityKind] = "SQLiteTimestampBuilder";
32983
- constructor(name, mode) {
32984
- super(name, "date", "SQLiteTimestamp");
32985
- this.config.mode = mode;
32986
- }
32987
- defaultNow() {
32988
- return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`);
32989
- }
32990
- build(table) {
32991
- return new SQLiteTimestamp(table, this.config);
32992
- }
32993
- }
32994
-
32995
- class SQLiteTimestamp extends SQLiteBaseInteger {
32996
- static [entityKind] = "SQLiteTimestamp";
32997
- mode = this.config.mode;
32998
- mapFromDriverValue(value) {
32999
- if (this.config.mode === "timestamp") {
33000
- return new Date(value * 1000);
33001
- }
33002
- return new Date(value);
33003
- }
33004
- mapToDriverValue(value) {
33005
- const unix = value.getTime();
33006
- if (this.config.mode === "timestamp") {
33007
- return Math.floor(unix / 1000);
33008
- }
33009
- return unix;
33010
- }
33011
- }
33012
-
33013
- class SQLiteBooleanBuilder extends SQLiteBaseIntegerBuilder {
33014
- static [entityKind] = "SQLiteBooleanBuilder";
33015
- constructor(name, mode) {
33016
- super(name, "boolean", "SQLiteBoolean");
33017
- this.config.mode = mode;
33018
- }
33019
- build(table) {
33020
- return new SQLiteBoolean(table, this.config);
33021
- }
33022
- }
33023
-
33024
- class SQLiteBoolean extends SQLiteBaseInteger {
33025
- static [entityKind] = "SQLiteBoolean";
33026
- mode = this.config.mode;
33027
- mapFromDriverValue(value) {
33028
- return Number(value) === 1;
33029
- }
33030
- mapToDriverValue(value) {
33031
- return value ? 1 : 0;
33032
- }
33033
- }
33034
- function integer2(a, b) {
33035
- const { name, config: config2 } = getColumnNameAndConfig(a, b);
33036
- if (config2?.mode === "timestamp" || config2?.mode === "timestamp_ms") {
33037
- return new SQLiteTimestampBuilder(name, config2.mode);
33038
- }
33039
- if (config2?.mode === "boolean") {
33040
- return new SQLiteBooleanBuilder(name, config2.mode);
33041
- }
33042
- return new SQLiteIntegerBuilder(name);
33043
- }
33044
-
33045
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
33046
- class SQLiteNumericBuilder extends SQLiteColumnBuilder {
33047
- static [entityKind] = "SQLiteNumericBuilder";
33048
- constructor(name) {
33049
- super(name, "string", "SQLiteNumeric");
33050
- }
33051
- build(table) {
33052
- return new SQLiteNumeric(table, this.config);
33053
- }
33054
- }
33055
-
33056
- class SQLiteNumeric extends SQLiteColumn {
33057
- static [entityKind] = "SQLiteNumeric";
33058
- mapFromDriverValue(value) {
33059
- if (typeof value === "string")
33060
- return value;
33061
- return String(value);
33062
- }
33063
- getSQLType() {
33064
- return "numeric";
33065
- }
33066
- }
33067
-
33068
- class SQLiteNumericNumberBuilder extends SQLiteColumnBuilder {
33069
- static [entityKind] = "SQLiteNumericNumberBuilder";
33070
- constructor(name) {
33071
- super(name, "number", "SQLiteNumericNumber");
33072
- }
33073
- build(table) {
33074
- return new SQLiteNumericNumber(table, this.config);
33075
- }
33076
- }
33077
-
33078
- class SQLiteNumericNumber extends SQLiteColumn {
33079
- static [entityKind] = "SQLiteNumericNumber";
33080
- mapFromDriverValue(value) {
33081
- if (typeof value === "number")
33082
- return value;
33083
- return Number(value);
33084
- }
33085
- mapToDriverValue = String;
33086
- getSQLType() {
33087
- return "numeric";
33088
- }
33089
- }
33090
-
33091
- class SQLiteNumericBigIntBuilder extends SQLiteColumnBuilder {
33092
- static [entityKind] = "SQLiteNumericBigIntBuilder";
33093
- constructor(name) {
33094
- super(name, "bigint", "SQLiteNumericBigInt");
33095
- }
33096
- build(table) {
33097
- return new SQLiteNumericBigInt(table, this.config);
33098
- }
33099
- }
33100
-
33101
- class SQLiteNumericBigInt extends SQLiteColumn {
33102
- static [entityKind] = "SQLiteNumericBigInt";
33103
- mapFromDriverValue = BigInt;
33104
- mapToDriverValue = String;
33105
- getSQLType() {
33106
- return "numeric";
33107
- }
33108
- }
33109
- function numeric(a, b) {
33110
- const { name, config: config2 } = getColumnNameAndConfig(a, b);
33111
- const mode = config2?.mode;
33112
- return mode === "number" ? new SQLiteNumericNumberBuilder(name) : mode === "bigint" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name);
33113
- }
33114
-
33115
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/columns/real.js
33116
- class SQLiteRealBuilder extends SQLiteColumnBuilder {
33117
- static [entityKind] = "SQLiteRealBuilder";
33118
- constructor(name) {
33119
- super(name, "number", "SQLiteReal");
33120
- }
33121
- build(table) {
33122
- return new SQLiteReal(table, this.config);
33123
- }
33124
- }
33125
-
33126
- class SQLiteReal extends SQLiteColumn {
33127
- static [entityKind] = "SQLiteReal";
33128
- getSQLType() {
33129
- return "real";
33130
- }
33131
- }
33132
- function real(name) {
33133
- return new SQLiteRealBuilder(name ?? "");
33134
- }
33135
-
33136
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/columns/text.js
33137
- class SQLiteTextBuilder extends SQLiteColumnBuilder {
33138
- static [entityKind] = "SQLiteTextBuilder";
33139
- constructor(name, config2) {
33140
- super(name, "string", "SQLiteText");
33141
- this.config.enumValues = config2.enum;
33142
- this.config.length = config2.length;
33143
- }
33144
- build(table) {
33145
- return new SQLiteText(table, this.config);
33146
- }
33147
- }
33148
-
33149
- class SQLiteText extends SQLiteColumn {
33150
- static [entityKind] = "SQLiteText";
33151
- enumValues = this.config.enumValues;
33152
- length = this.config.length;
33153
- constructor(table, config2) {
33154
- super(table, config2);
33155
- }
33156
- getSQLType() {
33157
- return `text${this.config.length ? `(${this.config.length})` : ""}`;
33158
- }
33159
- }
33160
-
33161
- class SQLiteTextJsonBuilder extends SQLiteColumnBuilder {
33162
- static [entityKind] = "SQLiteTextJsonBuilder";
33163
- constructor(name) {
33164
- super(name, "json", "SQLiteTextJson");
33165
- }
33166
- build(table) {
33167
- return new SQLiteTextJson(table, this.config);
33168
- }
33169
- }
33170
-
33171
- class SQLiteTextJson extends SQLiteColumn {
33172
- static [entityKind] = "SQLiteTextJson";
33173
- getSQLType() {
33174
- return "text";
33175
- }
33176
- mapFromDriverValue(value) {
33177
- return JSON.parse(value);
33178
- }
33179
- mapToDriverValue(value) {
33180
- return JSON.stringify(value);
33181
- }
33182
- }
33183
- function text(a, b = {}) {
33184
- const { name, config: config2 } = getColumnNameAndConfig(a, b);
33185
- if (config2.mode === "json") {
33186
- return new SQLiteTextJsonBuilder(name);
33187
- }
33188
- return new SQLiteTextBuilder(name, config2);
33189
- }
33190
-
33191
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/columns/all.js
33192
- function getSQLiteColumnBuilders() {
33193
- return {
33194
- blob,
33195
- customType,
33196
- integer: integer2,
33197
- numeric,
33198
- real,
33199
- text
33200
- };
33201
- }
33202
-
33203
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/table.js
33204
- var InlineForeignKeys = Symbol.for("drizzle:SQLiteInlineForeignKeys");
33205
-
33206
- class SQLiteTable extends Table {
33207
- static [entityKind] = "SQLiteTable";
33208
- static Symbol = Object.assign({}, Table.Symbol, {
33209
- InlineForeignKeys
33210
- });
33211
- [Table.Symbol.Columns];
33212
- [InlineForeignKeys] = [];
33213
- [Table.Symbol.ExtraConfigBuilder] = undefined;
33214
- }
33215
- function sqliteTableBase(name, columns, extraConfig, schema, baseName = name) {
33216
- const rawTable = new SQLiteTable(name, schema, baseName);
33217
- const parsedColumns = typeof columns === "function" ? columns(getSQLiteColumnBuilders()) : columns;
33218
- const builtColumns = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
33219
- const colBuilder = colBuilderBase;
33220
- colBuilder.setName(name2);
33221
- const column = colBuilder.build(rawTable);
33222
- rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));
33223
- return [name2, column];
33224
- }));
33225
- const table = Object.assign(rawTable, builtColumns);
33226
- table[Table.Symbol.Columns] = builtColumns;
33227
- table[Table.Symbol.ExtraConfigColumns] = builtColumns;
33228
- if (extraConfig) {
33229
- table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;
33230
- }
33231
- return table;
33232
- }
33233
- var sqliteTable = (name, columns, extraConfig) => {
33234
- return sqliteTableBase(name, columns, extraConfig);
33235
- };
33236
-
33237
- // ../../node_modules/.bun/drizzle-orm@0.45.2+29ab9a45addfc34e/node_modules/drizzle-orm/sqlite-core/indexes.js
33238
- class IndexBuilderOn {
33239
- constructor(name, unique2) {
33240
- this.name = name;
33241
- this.unique = unique2;
33242
- }
33243
- static [entityKind] = "SQLiteIndexBuilderOn";
33244
- on(...columns) {
33245
- return new IndexBuilder(this.name, columns, this.unique);
33246
- }
33247
- }
33248
-
33249
- class IndexBuilder {
33250
- static [entityKind] = "SQLiteIndexBuilder";
33251
- config;
33252
- constructor(name, columns, unique2) {
33253
- this.config = {
33254
- name,
33255
- columns,
33256
- unique: unique2,
33257
- where: undefined
33258
- };
33259
- }
33260
- where(condition) {
33261
- this.config.where = condition;
33262
- return this;
33263
- }
33264
- build(table) {
33265
- return new Index(this.config, table);
33266
- }
33267
- }
33268
-
33269
- class Index {
33270
- static [entityKind] = "SQLiteIndex";
33271
- config;
33272
- constructor(config2, table) {
33273
- this.config = { ...config2, table };
33274
- }
33275
- }
33276
- function index(name) {
33277
- return new IndexBuilderOn(name, false);
33278
- }
33279
-
33280
- // ../runtime/src/drizzle-schema.ts
33281
- var deliveriesTable = sqliteTable("deliveries", {
33282
- id: text("id").primaryKey(),
33283
- messageId: text("message_id"),
33284
- invocationId: text("invocation_id"),
33285
- targetId: text("target_id").notNull(),
33286
- targetNodeId: text("target_node_id"),
33287
- targetKind: text("target_kind").$type().notNull(),
33288
- transport: text("transport").$type().notNull(),
33289
- reason: text("reason").$type().notNull(),
33290
- policy: text("policy").$type().notNull(),
33291
- status: text("status").$type().notNull(),
33292
- bindingId: text("binding_id"),
33293
- leaseOwner: text("lease_owner"),
33294
- leaseExpiresAt: integer2("lease_expires_at"),
33295
- metadataJson: text("metadata_json"),
33296
- createdAt: integer2("created_at").notNull().default(sql`(unixepoch())`)
33297
- }, (table) => [
33298
- index("idx_deliveries_status_transport").on(table.status, table.transport)
33299
- ]);
33300
- var deliveryAttemptsTable = sqliteTable("delivery_attempts", {
33301
- id: text("id").primaryKey(),
33302
- deliveryId: text("delivery_id").notNull(),
33303
- attempt: integer2("attempt").notNull(),
33304
- status: text("status").$type().notNull(),
33305
- error: text("error"),
33306
- externalRef: text("external_ref"),
33307
- metadataJson: text("metadata_json"),
33308
- createdAt: integer2("created_at").notNull()
33309
- });
33310
- // ../runtime/src/broker.ts
33311
- function createRuntimeId(prefix) {
33312
- return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
33313
- }
33314
- function toTargetKind(actor) {
33315
- if (!actor)
33316
- return "participant";
33317
- if (actor.kind === "agent")
33318
- return "agent";
33319
- if (actor.kind === "device")
33320
- return "device";
33321
- if (actor.kind === "bridge")
33322
- return "bridge";
33323
- return "participant";
33324
- }
33325
- function defaultTransportForActor(actor) {
33326
- if (!actor)
33327
- return "local_socket";
33328
- switch (actor.kind) {
33329
- case "bridge":
33330
- return "webhook";
33331
- case "device":
33332
- return "local_socket";
33333
- case "agent":
33334
- return "local_socket";
33335
- default:
33336
- return "local_socket";
33337
- }
33338
- }
33339
- function endpointTransportRank(transport) {
33340
- switch (transport) {
33341
- case "codex_app_server":
33342
- return 0;
33343
- case "claude_stream_json":
33344
- return 1;
33345
- case "tmux":
33346
- return 2;
33347
- case "local_socket":
33348
- return 3;
33349
- default:
33350
- return 4;
33351
- }
33352
- }
33353
- function shouldBridgeMessageToBinding(binding, message) {
33354
- if (binding.platform !== "telegram") {
33355
- return true;
33356
- }
33357
- const source = typeof message.metadata?.source === "string" ? String(message.metadata.source) : "";
33358
- if (source === "telegram") {
33359
- return false;
33360
- }
33361
- const outboundMode = typeof binding.metadata?.outboundMode === "string" ? String(binding.metadata.outboundMode) : "operator_only";
33362
- const operatorId = typeof binding.metadata?.operatorId === "string" ? String(binding.metadata.operatorId) : "operator";
33363
- const allowedActorIds = Array.isArray(binding.metadata?.allowedActorIds) ? binding.metadata.allowedActorIds.map((entry) => String(entry).trim()).filter(Boolean) : [];
33364
- if (outboundMode === "all") {
33365
- return true;
33366
- }
33367
- if (outboundMode === "allowlist") {
33368
- return allowedActorIds.includes(message.actorId);
33369
- }
33370
- return message.actorId === operatorId;
33371
- }
33372
- function resolveBindingRoutes(bindings, message) {
33373
- return bindings.filter((binding) => shouldBridgeMessageToBinding(binding, message)).map((binding) => ({
33374
- targetId: binding.id,
33375
- targetKind: "bridge",
33376
- transport: binding.platform === "telegram" ? "telegram" : binding.platform === "discord" ? "discord" : "webhook",
33377
- bindingId: binding.id
33378
- }));
33379
- }
33380
- function preferredEndpoint(endpoints) {
33381
- let preferred;
33382
- let preferredRank = Number.POSITIVE_INFINITY;
33383
- for (const endpoint of endpoints) {
33384
- const rank = endpointTransportRank(endpoint.transport);
33385
- if (!preferred || rank < preferredRank) {
33386
- preferred = endpoint;
33387
- preferredRank = rank;
33388
- }
33389
- }
33390
- return preferred;
33391
- }
33392
-
33393
- class InMemoryControlRuntime {
33394
- registry;
33395
- listeners = new Set;
33396
- eventBuffer = [];
33397
- localNodeId;
33398
- endpointIdsByAgentId = new Map;
33399
- bindingIdsByConversationId = new Map;
33400
- flightIdByInvocationId = new Map;
33401
- constructor(initial = {}, options = {}) {
33402
- this.registry = createRuntimeRegistrySnapshot(initial);
33403
- this.localNodeId = options.localNodeId;
33404
- this.rebuildIndexes();
33405
- }
33406
- snapshot() {
33407
- return createRuntimeRegistrySnapshot({
33408
- nodes: { ...this.registry.nodes },
33409
- actors: { ...this.registry.actors },
33410
- agents: { ...this.registry.agents },
33411
- endpoints: { ...this.registry.endpoints },
33412
- conversations: { ...this.registry.conversations },
33413
- bindings: { ...this.registry.bindings },
33414
- messages: { ...this.registry.messages },
33415
- flights: { ...this.registry.flights },
33416
- collaborationRecords: { ...this.registry.collaborationRecords }
33417
- });
33418
- }
33419
- peek() {
33420
- return this.registry;
33421
- }
33422
- node(nodeId) {
33423
- return this.registry.nodes[nodeId];
33424
- }
33425
- agent(agentId) {
33426
- return this.registry.agents[agentId];
33427
- }
33428
- conversation(conversationId) {
33429
- return this.registry.conversations[conversationId];
33430
- }
33431
- message(messageId) {
33432
- return this.registry.messages[messageId];
33433
- }
33434
- collaborationRecord(recordId) {
33435
- return this.registry.collaborationRecords[recordId];
33436
- }
33437
- flightForInvocation(invocationId) {
33438
- const flightId = this.flightIdByInvocationId.get(invocationId);
33439
- return flightId ? this.registry.flights[flightId] : undefined;
33440
- }
33441
- bindingsForConversation(conversationId) {
33442
- const bindingIds = this.bindingIdsByConversationId.get(conversationId);
33443
- if (!bindingIds) {
33444
- return [];
33445
- }
33446
- const bindings = [];
33447
- for (const bindingId of bindingIds) {
33448
- const binding = this.registry.bindings[bindingId];
33449
- if (binding) {
33450
- bindings.push(binding);
33451
- }
33452
- }
33453
- return bindings;
33454
- }
33455
- endpointsForAgent(agentId, options = {}) {
33456
- const endpointIds = this.endpointIdsByAgentId.get(agentId);
33457
- if (!endpointIds) {
33458
- return [];
33459
- }
33460
- const endpoints = [];
33461
- for (const endpointId of endpointIds) {
33462
- const endpoint = this.registry.endpoints[endpointId];
33463
- if (!endpoint)
33464
- continue;
33465
- if (!options.includeOffline && endpoint.state === "offline")
33466
- continue;
33467
- if (options.nodeId && endpoint.nodeId !== options.nodeId)
33468
- continue;
33469
- if (options.harness && endpoint.harness !== options.harness)
33470
- continue;
33471
- endpoints.push(endpoint);
33472
- }
33473
- return endpoints;
33474
- }
33475
- recentEvents(limit = 100) {
33476
- return this.eventBuffer.slice(-limit);
33477
- }
33478
- subscribe(listener) {
33479
- this.listeners.add(listener);
33480
- return () => {
33481
- this.listeners.delete(listener);
33482
- };
33483
- }
33484
- async dispatch(command) {
33485
- switch (command.kind) {
33486
- case "node.upsert":
33487
- await this.upsertNode(command.node);
33488
- return;
33489
- case "actor.upsert":
33490
- await this.upsertActor(command.actor);
33491
- return;
33492
- case "agent.upsert":
33493
- await this.upsertAgent(command.agent);
33494
- return;
33495
- case "agent.endpoint.upsert":
33496
- await this.upsertEndpoint(command.endpoint);
33497
- return;
33498
- case "conversation.upsert":
33499
- await this.upsertConversation(command.conversation);
33500
- return;
33501
- case "binding.upsert":
33502
- await this.upsertBinding(command.binding);
33503
- return;
33504
- case "collaboration.upsert":
33505
- await this.upsertCollaboration(command.record);
33506
- return;
33507
- case "collaboration.event.append":
33508
- await this.appendCollaborationEvent(command.event);
33509
- return;
33510
- case "conversation.post":
33511
- await this.postMessage(command.message);
33512
- return;
33513
- case "agent.invoke":
33514
- await this.invokeAgent(command.invocation);
33515
- return;
33516
- case "agent.ensure_awake":
33517
- this.emit({
33518
- id: createRuntimeId("evt"),
33519
- kind: "flight.updated",
33520
- ts: Date.now(),
33521
- actorId: command.requesterId,
33522
- nodeId: this.localNodeId,
33523
- payload: {
33524
- flight: {
33525
- id: createRuntimeId("flt"),
33526
- invocationId: command.agentId,
33527
- requesterId: command.requesterId,
33528
- targetAgentId: command.agentId,
33529
- state: "waking",
33530
- summary: command.reason
33531
- }
33532
- }
33533
- });
33534
- return;
33535
- case "stream.subscribe":
33536
- return;
33537
- default: {
33538
- const exhaustive = command;
33539
- return exhaustive;
33540
- }
33541
- }
33542
- }
33543
- async upsertNode(node) {
33544
- this.registry.nodes[node.id] = node;
33545
- this.emit({
33546
- id: createRuntimeId("evt"),
33547
- kind: "node.upserted",
33548
- ts: Date.now(),
33549
- actorId: node.id,
33550
- nodeId: node.id,
33551
- payload: { node }
33552
- });
33553
- }
33554
- async upsertActor(actor) {
33555
- this.registry.actors[actor.id] = {
33556
- id: actor.id,
33557
- kind: actor.kind,
33558
- displayName: actor.displayName,
33559
- handle: actor.handle,
33560
- labels: actor.labels,
33561
- metadata: actor.metadata
33562
- };
33563
- this.emit({
33564
- id: createRuntimeId("evt"),
33565
- kind: "actor.registered",
33566
- ts: Date.now(),
33567
- actorId: actor.id,
33568
- nodeId: this.localNodeId,
33569
- payload: { actor }
33570
- });
33571
- }
33572
- async upsertAgent(agent) {
33573
- if (!this.registry.actors[agent.id]) {
33574
- this.registry.actors[agent.id] = {
33575
- id: agent.id,
33576
- kind: agent.kind,
33577
- displayName: agent.displayName,
33578
- handle: agent.handle,
33579
- labels: agent.labels,
33580
- metadata: agent.metadata
33581
- };
33582
- }
33583
- this.registry.agents[agent.id] = agent;
33584
- this.emit({
33585
- id: createRuntimeId("evt"),
33586
- kind: "agent.registered",
33587
- ts: Date.now(),
33588
- actorId: agent.id,
33589
- nodeId: agent.authorityNodeId,
33590
- payload: { agent }
33591
- });
33592
- }
33593
- async upsertEndpoint(endpoint) {
33594
- const previous = this.registry.endpoints[endpoint.id];
33595
- if (previous) {
33596
- this.unindexEndpoint(previous);
33597
- }
33598
- this.registry.endpoints[endpoint.id] = endpoint;
33599
- this.indexEndpoint(endpoint);
33600
- this.emit({
33601
- id: createRuntimeId("evt"),
33602
- kind: "agent.endpoint.upserted",
33603
- ts: Date.now(),
33604
- actorId: endpoint.agentId,
33605
- nodeId: endpoint.nodeId,
33606
- payload: { endpoint }
33607
- });
33608
- }
33609
- async upsertConversation(conversation) {
33610
- this.registry.conversations[conversation.id] = conversation;
33611
- this.emit({
33612
- id: createRuntimeId("evt"),
33613
- kind: "conversation.upserted",
33614
- ts: Date.now(),
33615
- actorId: "system",
33616
- nodeId: conversation.authorityNodeId,
33617
- payload: { conversation }
33618
- });
33619
- }
33620
- async upsertBinding(binding) {
33621
- const previous = this.registry.bindings[binding.id];
33622
- if (previous) {
33623
- this.unindexBinding(previous);
33624
- }
33625
- this.registry.bindings[binding.id] = binding;
33626
- this.indexBinding(binding);
33627
- this.emit({
33628
- id: createRuntimeId("evt"),
33629
- kind: "binding.upserted",
33630
- ts: Date.now(),
33631
- actorId: "system",
33632
- nodeId: this.localNodeId,
33633
- payload: { binding }
33634
- });
33635
- }
33636
- async upsertCollaboration(record2) {
33637
- assertValidCollaborationRecord(record2);
33638
- this.registry.collaborationRecords[record2.id] = record2;
33639
- this.emit({
33640
- id: createRuntimeId("evt"),
33641
- kind: "collaboration.upserted",
33642
- ts: Date.now(),
33643
- actorId: record2.createdById,
33644
- nodeId: this.localNodeId,
33645
- payload: { record: record2 }
33646
- });
33647
- }
33648
- async appendCollaborationEvent(event) {
33649
- const record2 = this.registry.collaborationRecords[event.recordId];
33650
- if (!record2) {
33651
- throw new Error(`unknown collaboration record: ${event.recordId}`);
33652
- }
33653
- assertValidCollaborationEvent(event, record2);
33654
- this.emit({
33655
- id: createRuntimeId("evt"),
33656
- kind: "collaboration.event.appended",
33657
- ts: Date.now(),
33658
- actorId: event.actorId,
33659
- nodeId: this.localNodeId,
33660
- payload: { event }
33661
- });
33662
- }
33663
- async upsertFlight(flight) {
33664
- const previous = this.registry.flights[flight.id];
33665
- if (previous && this.flightIdByInvocationId.get(previous.invocationId) === previous.id) {
33666
- this.flightIdByInvocationId.delete(previous.invocationId);
33667
- }
33668
- this.registry.flights[flight.id] = flight;
33669
- this.flightIdByInvocationId.set(flight.invocationId, flight.id);
33670
- this.emit({
33671
- id: createRuntimeId("evt"),
33672
- kind: "flight.updated",
33673
- ts: Date.now(),
33674
- actorId: flight.requesterId,
33675
- nodeId: this.localNodeId,
33676
- payload: { flight }
33677
- });
33678
- }
33679
- async postMessage(message, options = {}) {
33680
- const deliveries2 = this.planMessage(message, options);
33681
- await this.commitMessage(message, deliveries2);
33682
- return deliveries2;
33683
- }
33684
- planMessage(message, options = {}) {
33685
- const conversation = this.registry.conversations[message.conversationId];
33686
- if (!conversation) {
33687
- throw new Error(`unknown conversation: ${message.conversationId}`);
33688
- }
33689
- const bindingRoutes = resolveBindingRoutes(this.bindingsForConversation(conversation.id), message);
33690
- const plannedParticipantRoutes = this.resolveParticipantRoutes(conversation.participantIds);
33691
- const participantRoutes = options.localOnly ? plannedParticipantRoutes.filter((route2) => !route2.nodeId || route2.nodeId === this.localNodeId) : plannedParticipantRoutes;
33692
- const deliveries2 = planMessageDeliveries({
33693
- localNodeId: this.localNodeId,
33694
- message,
33695
- conversation,
33696
- participantRoutes,
33697
- bindingRoutes: options.localOnly ? [] : bindingRoutes
33698
- });
33699
- return deliveries2;
33700
- }
33701
- async commitMessage(message, deliveries2) {
33702
- this.registry.messages[message.id] = message;
33703
- this.emit({
33704
- id: createRuntimeId("evt"),
33705
- kind: "message.posted",
33706
- ts: Date.now(),
33707
- actorId: message.actorId,
33708
- nodeId: message.originNodeId,
33709
- payload: { message }
33710
- });
33711
- for (const delivery of deliveries2) {
33712
- this.emit({
33713
- id: createRuntimeId("evt"),
33714
- kind: "delivery.planned",
33715
- ts: Date.now(),
33716
- actorId: message.actorId,
33717
- nodeId: message.originNodeId,
33718
- payload: { delivery }
33719
- });
33720
- }
33721
- }
33722
- async invokeAgent(invocation) {
33723
- const flight = this.planInvocation(invocation);
33724
- await this.commitInvocation(invocation, flight);
33725
- return flight;
33726
- }
33727
- planInvocation(invocation) {
33728
- const targetAgent = this.registry.agents[invocation.targetAgentId];
33729
- if (!targetAgent) {
33730
- throw new Error(`unknown agent: ${invocation.targetAgentId}`);
33731
- }
33732
- const targetEndpoints = this.endpointsForAgent(invocation.targetAgentId, {
33733
- nodeId: targetAgent.authorityNodeId,
33734
- harness: invocation.execution?.harness
33735
- });
33736
- const isLocalAuthority = !this.localNodeId || targetAgent.authorityNodeId === this.localNodeId;
33737
- const startedAt = Date.now();
33738
- let state = invocation.ensureAwake ? "waking" : "queued";
33739
- let summary;
33740
- let error48;
33741
- let completedAt;
33742
- if (isLocalAuthority) {
33743
- if (targetEndpoints.length == 0) {
33744
- state = invocation.ensureAwake ? "waking" : "queued";
33745
- summary = invocation.ensureAwake ? invocation.execution?.harness ? `${targetAgent.displayName} waking on ${invocation.execution.harness}.` : `${targetAgent.displayName} waking.` : `Message stored for ${targetAgent.displayName}. Will deliver when online.`;
33746
- } else {
33747
- state = "queued";
33748
- summary = `${targetAgent.displayName} queued for local execution.`;
33749
- }
33750
- }
33751
- const flight = {
33752
- id: createRuntimeId("flt"),
33753
- invocationId: invocation.id,
33754
- requesterId: invocation.requesterId,
33755
- targetAgentId: invocation.targetAgentId,
33756
- state,
33757
- summary,
33758
- error: error48,
33759
- startedAt,
33760
- completedAt,
33761
- metadata: invocation.metadata
33762
- };
33763
- return flight;
33764
- }
33765
- async commitInvocation(invocation, flight) {
33766
- const previous = this.registry.flights[flight.id];
33767
- if (previous && this.flightIdByInvocationId.get(previous.invocationId) === previous.id) {
33768
- this.flightIdByInvocationId.delete(previous.invocationId);
33769
- }
33770
- this.registry.flights[flight.id] = flight;
33771
- this.flightIdByInvocationId.set(flight.invocationId, flight.id);
33772
- const targetAgent = this.registry.agents[invocation.targetAgentId];
33773
- this.emit({
33774
- id: createRuntimeId("evt"),
33775
- kind: "invocation.requested",
33776
- ts: Date.now(),
33777
- actorId: invocation.requesterId,
33778
- nodeId: invocation.requesterNodeId,
33779
- payload: { invocation }
33780
- });
33781
- this.emit({
33782
- id: createRuntimeId("evt"),
33783
- kind: "flight.updated",
33784
- ts: Date.now(),
33785
- actorId: invocation.requesterId,
33786
- nodeId: targetAgent?.authorityNodeId,
33787
- payload: { flight }
33788
- });
33789
- }
33790
- rebuildIndexes() {
33791
- for (const endpoint of Object.values(this.registry.endpoints)) {
33792
- this.indexEndpoint(endpoint);
33793
- }
33794
- for (const binding of Object.values(this.registry.bindings)) {
33795
- this.indexBinding(binding);
33796
- }
33797
- for (const flight of Object.values(this.registry.flights)) {
33798
- this.flightIdByInvocationId.set(flight.invocationId, flight.id);
33799
- }
33800
- }
33801
- indexEndpoint(endpoint) {
33802
- this.addIndexedId(this.endpointIdsByAgentId, endpoint.agentId, endpoint.id);
33803
- }
33804
- unindexEndpoint(endpoint) {
33805
- this.removeIndexedId(this.endpointIdsByAgentId, endpoint.agentId, endpoint.id);
33806
- }
33807
- indexBinding(binding) {
33808
- this.addIndexedId(this.bindingIdsByConversationId, binding.conversationId, binding.id);
33809
- }
33810
- unindexBinding(binding) {
33811
- this.removeIndexedId(this.bindingIdsByConversationId, binding.conversationId, binding.id);
33812
- }
33813
- addIndexedId(index2, key, value) {
33814
- const ids = index2.get(key) ?? new Set;
33815
- ids.add(value);
33816
- index2.set(key, ids);
33817
- }
33818
- removeIndexedId(index2, key, value) {
33819
- const ids = index2.get(key);
33820
- if (!ids) {
33821
- return;
33822
- }
33823
- ids.delete(value);
33824
- if (ids.size === 0) {
33825
- index2.delete(key);
33826
- }
33827
- }
33828
- resolveParticipantRoutes(participantIds) {
33829
- const routes = [];
33830
- for (const participantId of participantIds) {
33831
- const actor = this.registry.actors[participantId];
33832
- const agent = this.registry.agents[participantId];
33833
- const targetIdentity = actor ?? agent;
33834
- const endpoints = this.endpointsForAgent(participantId);
33835
- const endpoint = preferredEndpoint(endpoints);
33836
- if (!endpoint) {
33837
- if (agent?.authorityNodeId && agent.authorityNodeId !== this.localNodeId) {
33838
- routes.push({
33839
- targetId: participantId,
33840
- nodeId: agent.authorityNodeId,
33841
- targetKind: toTargetKind(targetIdentity),
33842
- transport: defaultTransportForActor(targetIdentity),
33843
- speechEnabled: false
33844
- });
33845
- } else if (agent) {
33846
- routes.push({
33847
- targetId: participantId,
33848
- nodeId: agent.authorityNodeId ?? this.localNodeId,
33849
- targetKind: toTargetKind(targetIdentity),
33850
- transport: defaultTransportForActor(targetIdentity),
33851
- speechEnabled: false
33852
- });
33853
- }
33854
- continue;
33855
- }
33856
- routes.push({
33857
- targetId: participantId,
33858
- nodeId: endpoint.nodeId ?? agent?.authorityNodeId,
33859
- targetKind: toTargetKind(targetIdentity),
33860
- transport: endpoint.transport ?? defaultTransportForActor(targetIdentity),
33861
- speechEnabled: Boolean(actor?.kind === "device" || endpoints.some((candidate) => candidate.transport === "local_socket" || candidate.transport === "websocket"))
33862
- });
33863
- }
33864
- return routes;
33865
- }
33866
- emit(event) {
33867
- this.eventBuffer.push(event);
33868
- if (this.eventBuffer.length > 500) {
33869
- this.eventBuffer.shift();
33870
- }
33871
- for (const listener of this.listeners) {
33872
- listener(event);
33873
- }
33874
- }
33875
- }
33876
- // ../runtime/src/tailscale.ts
33877
- import { execFile } from "child_process";
33878
- import { promisify } from "util";
33879
- var execFileAsync = promisify(execFile);
33880
- // ../runtime/src/thread-events.ts
33881
- class ThreadWatchProtocolError extends Error {
33882
- status;
33883
- body;
33884
- constructor(status, body) {
33885
- super(body.message);
33886
- this.status = status;
33887
- this.body = body;
33888
- }
33889
- }
33890
- function watchKey(conversationId, watcherNodeId, watcherId) {
33891
- return `${conversationId}:${watcherNodeId}:${watcherId}`;
33892
- }
33893
- function writeSse(response, eventName, payload) {
33894
- response.write(`event: ${eventName}
33895
- data: ${JSON.stringify(payload)}
33896
-
33897
- `);
33898
- }
33899
-
33900
- class ThreadEventPlane {
33901
- options;
33902
- watches = new Map;
33903
- watchIdsByKey = new Map;
33904
- watchIdsByConversation = new Map;
33905
- constructor(options) {
33906
- this.options = options;
33907
- }
33908
- async openWatch(request) {
33909
- const conversation = this.requireConversationAuthority(request.conversationId);
33910
- this.requireRemoteWatchAllowed(conversation);
33911
- const afterSeq = Math.max(0, request.afterSeq ?? 0);
33912
- const oldestSeq = await this.options.projection.oldestThreadSeq(conversation.id);
33913
- const latestSeq = await this.options.projection.latestThreadSeq(conversation.id);
33914
- if (latestSeq > 0 && oldestSeq > 0 && afterSeq < oldestSeq - 1) {
33915
- throw new ThreadWatchProtocolError(409, {
33916
- code: "cursor_out_of_range",
33917
- message: `thread cursor ${afterSeq} is older than retained seq ${oldestSeq}`
33918
- });
33919
- }
33920
- const key = watchKey(conversation.id, request.watcherNodeId, request.watcherId);
33921
- const existingWatchId = this.watchIdsByKey.get(key);
33922
- if (existingWatchId) {
33923
- this.closeWatchInternal(existingWatchId);
33924
- }
33925
- const watchId = `thread-watch:${conversation.id}:${request.watcherNodeId}:${request.watcherId}`;
33926
- const leaseExpiresAt = Date.now() + this.normalizeLeaseMs(request.leaseMs);
33927
- const watch = {
33928
- watchId,
33929
- conversationId: conversation.id,
33930
- watcherNodeId: request.watcherNodeId,
33931
- watcherId: request.watcherId,
33932
- acceptedAfterSeq: afterSeq,
33933
- leaseExpiresAt,
33934
- mode: conversation.shareMode === "summary" ? "summary" : "shared",
33935
- clients: new Set
33936
- };
33937
- this.watches.set(watchId, watch);
33938
- this.watchIdsByKey.set(key, watchId);
33939
- this.indexWatch(watch);
33940
- return {
33941
- watchId,
33942
- conversationId: conversation.id,
33943
- authorityNodeId: conversation.authorityNodeId,
33944
- acceptedAfterSeq: afterSeq,
33945
- latestSeq,
33946
- leaseExpiresAt,
33947
- mode: watch.mode
33948
- };
33949
- }
33950
- async renewWatch(request) {
33951
- const watch = this.requireLiveWatch(request.watchId);
33952
- watch.leaseExpiresAt = Date.now() + this.normalizeLeaseMs(request.leaseMs);
33953
- return {
33954
- watchId: watch.watchId,
33955
- leaseExpiresAt: watch.leaseExpiresAt
33956
- };
33957
- }
33958
- async closeWatch(request) {
33959
- this.closeWatchInternal(request.watchId);
33960
- }
33961
- async replay(options) {
33962
- const conversation = this.requireConversationAuthority(options.conversationId);
33963
- this.requireRemoteWatchAllowed(conversation);
33964
- const oldestSeq = await this.options.projection.oldestThreadSeq(conversation.id);
33965
- const latestSeq = await this.options.projection.latestThreadSeq(conversation.id);
33966
- if (latestSeq > 0 && oldestSeq > 0 && options.afterSeq < oldestSeq - 1) {
33967
- throw new ThreadWatchProtocolError(409, {
33968
- code: "cursor_out_of_range",
33969
- message: `thread cursor ${options.afterSeq} is older than retained seq ${oldestSeq}`
33970
- });
33971
- }
33972
- return this.options.projection.listThreadEvents({
33973
- conversationId: conversation.id,
33974
- afterSeq: options.afterSeq,
33975
- limit: Math.min(options.limit ?? 500, this.options.maxReplayLimit ?? 2000)
33976
- });
33977
- }
33978
- async snapshot(conversationId) {
33979
- const conversation = this.requireConversationAuthority(conversationId);
33980
- this.requireRemoteWatchAllowed(conversation);
33981
- const snapshot = await this.options.projection.getThreadSnapshot(conversation.id);
33982
- if (!snapshot) {
33983
- throw new ThreadWatchProtocolError(404, {
33984
- code: "unknown_conversation",
33985
- message: `unknown conversation ${conversation.id}`
33986
- });
33987
- }
33988
- return snapshot;
33989
- }
33990
- async streamWatch(watchId, request, response) {
33991
- const watch = this.requireLiveWatch(watchId);
33992
- const backlog = await this.options.projection.listThreadEvents({
33993
- conversationId: watch.conversationId,
33994
- afterSeq: watch.acceptedAfterSeq,
33995
- limit: this.options.maxReplayLimit ?? 2000
33996
- });
33997
- response.writeHead(200, {
33998
- "content-type": "text/event-stream",
33999
- "cache-control": "no-cache, no-transform",
34000
- connection: "keep-alive"
34001
- });
34002
- writeSse(response, "hello", {
34003
- watchId: watch.watchId,
34004
- conversationId: watch.conversationId,
34005
- leaseExpiresAt: watch.leaseExpiresAt
34006
- });
34007
- for (const event of backlog) {
34008
- writeSse(response, "thread.event", event);
34009
- }
34010
- watch.clients.add(response);
34011
- request.on("close", () => {
34012
- watch.clients.delete(response);
34013
- response.end();
34014
- });
34015
- }
34016
- publish(events2) {
34017
- for (const event of events2) {
34018
- const watchIds = this.watchIdsByConversation.get(event.conversationId);
34019
- if (!watchIds || watchIds.size === 0) {
34020
- continue;
34021
- }
34022
- for (const watchId of [...watchIds]) {
34023
- const watch = this.watches.get(watchId);
34024
- if (!watch) {
34025
- watchIds.delete(watchId);
34026
- continue;
34027
- }
34028
- if (watch.leaseExpiresAt <= Date.now()) {
34029
- this.closeWatchInternal(watchId);
34030
- continue;
34031
- }
34032
- for (const client of watch.clients) {
34033
- writeSse(client, "thread.event", event);
34034
- }
34035
- }
34036
- }
34037
- }
34038
- normalizeLeaseMs(requestedLeaseMs) {
34039
- const defaultLeaseMs = this.options.defaultLeaseMs ?? 30000;
34040
- const maxLeaseMs = this.options.maxLeaseMs ?? 300000;
34041
- if (!requestedLeaseMs || !Number.isFinite(requestedLeaseMs) || requestedLeaseMs <= 0) {
34042
- return defaultLeaseMs;
34043
- }
34044
- return Math.min(Math.max(requestedLeaseMs, 5000), maxLeaseMs);
34045
- }
34046
- requireConversationAuthority(conversationId) {
34047
- const conversation = this.options.runtime.conversation(conversationId);
34048
- if (!conversation) {
34049
- throw new ThreadWatchProtocolError(404, {
34050
- code: "unknown_conversation",
34051
- message: `unknown conversation ${conversationId}`
34052
- });
34053
- }
34054
- if (conversation.authorityNodeId !== this.options.nodeId) {
34055
- throw new ThreadWatchProtocolError(409, {
34056
- code: "no_responder",
34057
- message: `conversation ${conversationId} is owned by ${conversation.authorityNodeId}`
34058
- });
34059
- }
34060
- return conversation;
34061
- }
34062
- requireRemoteWatchAllowed(conversation) {
34063
- if (conversation.shareMode === "local") {
34064
- throw new ThreadWatchProtocolError(403, {
34065
- code: "forbidden",
34066
- message: `conversation ${conversation.id} does not allow remote watches`
34067
- });
34068
- }
34069
- }
34070
- requireLiveWatch(watchId) {
34071
- const watch = this.watches.get(watchId);
34072
- if (!watch) {
34073
- throw new ThreadWatchProtocolError(404, {
34074
- code: "invalid_request",
34075
- message: `unknown watch ${watchId}`
34076
- });
34077
- }
34078
- if (watch.leaseExpiresAt <= Date.now()) {
34079
- this.closeWatchInternal(watchId);
34080
- throw new ThreadWatchProtocolError(410, {
34081
- code: "lease_expired",
34082
- message: `watch ${watchId} lease expired`
34083
- });
34084
- }
34085
- return watch;
34086
- }
34087
- indexWatch(watch) {
34088
- const ids = this.watchIdsByConversation.get(watch.conversationId) ?? new Set;
34089
- ids.add(watch.watchId);
34090
- this.watchIdsByConversation.set(watch.conversationId, ids);
34091
- }
34092
- closeWatchInternal(watchId) {
34093
- const watch = this.watches.get(watchId);
34094
- if (!watch) {
34095
- return;
34096
- }
34097
- this.watches.delete(watchId);
34098
- this.watchIdsByKey.delete(watchKey(watch.conversationId, watch.watcherNodeId, watch.watcherId));
34099
- const ids = this.watchIdsByConversation.get(watch.conversationId);
34100
- if (ids) {
34101
- ids.delete(watchId);
34102
- if (ids.size === 0) {
34103
- this.watchIdsByConversation.delete(watch.conversationId);
34104
- }
34105
- }
34106
- for (const client of watch.clients) {
34107
- client.end();
34108
- }
34109
- watch.clients.clear();
34110
- }
34111
- }
34112
- // ../runtime/src/mobile-push.ts
34113
- import { Database as Database2 } from "bun:sqlite";
34114
- import { mkdirSync as mkdirSync9, readFileSync as readFileSync10 } from "fs";
34115
- import { connect as connectHttp2 } from "http2";
34116
- import { createPrivateKey, sign as signWithKey } from "crypto";
34117
- import { dirname as dirname7, join as join18 } from "path";
34118
- var MOBILE_PUSH_SCHEMA = `
34119
- CREATE TABLE IF NOT EXISTS mobile_push_registrations (
34120
- id TEXT PRIMARY KEY,
34121
- device_id TEXT NOT NULL,
34122
- platform TEXT NOT NULL,
34123
- app_bundle_id TEXT NOT NULL,
34124
- apns_environment TEXT NOT NULL,
34125
- push_token TEXT NOT NULL,
34126
- authorization_status TEXT NOT NULL,
34127
- app_version TEXT,
34128
- build_number TEXT,
34129
- device_model TEXT,
34130
- system_version TEXT,
34131
- created_at INTEGER NOT NULL,
34132
- updated_at INTEGER NOT NULL
34133
- );
34134
- CREATE UNIQUE INDEX IF NOT EXISTS idx_mobile_push_registrations_device_bundle_env
34135
- ON mobile_push_registrations (device_id, platform, app_bundle_id, apns_environment);
34136
- CREATE UNIQUE INDEX IF NOT EXISTS idx_mobile_push_registrations_push_token
34137
- ON mobile_push_registrations (push_token);
34138
- CREATE INDEX IF NOT EXISTS idx_mobile_push_registrations_device_updated_at
34139
- ON mobile_push_registrations (device_id, updated_at DESC);
34140
- `;
34141
- var dbHandle = null;
34142
- var dbPath = null;
34143
- var cachedApnsJwt = null;
34144
- function resolveControlPlaneDbPath() {
34145
- return join18(resolveOpenScoutSupportPaths().controlHome, "control-plane.sqlite");
34146
- }
34147
- function ensureMobilePushSchema(database) {
34148
- database.exec("PRAGMA busy_timeout = 5000;");
34149
- database.exec("PRAGMA journal_mode = WAL;");
34150
- database.exec(MOBILE_PUSH_SCHEMA);
34151
- }
34152
- function writeDb() {
34153
- const nextPath = resolveControlPlaneDbPath();
34154
- if (dbHandle && dbPath !== nextPath) {
34155
- dbHandle.close();
34156
- dbHandle = null;
34157
- }
34158
- if (!dbHandle) {
34159
- mkdirSync9(dirname7(nextPath), { recursive: true });
34160
- dbHandle = new Database2(nextPath, { create: true });
34161
- dbPath = nextPath;
34162
- ensureMobilePushSchema(dbHandle);
34163
- }
34164
- return dbHandle;
34165
- }
34166
- function normalizeToken(token) {
34167
- return token.trim().replace(/[<>\s]/g, "").toLowerCase();
34168
- }
34169
- function pushAllowed(status) {
34170
- switch (status) {
34171
- case "authorized":
34172
- case "provisional":
34173
- case "ephemeral":
34174
- return true;
34175
- case "denied":
34176
- case "notDetermined":
34177
- return false;
34178
- }
34179
- }
34180
- function tokenSuffix(token) {
34181
- return token.length <= 8 ? token : token.slice(-8);
34182
- }
34183
- function rowToRegistration(row) {
34184
- return {
34185
- id: row.id,
34186
- deviceId: row.device_id,
34187
- platform: row.platform,
34188
- appBundleId: row.app_bundle_id,
34189
- apnsEnvironment: row.apns_environment,
34190
- pushToken: row.push_token,
34191
- authorizationStatus: row.authorization_status,
34192
- appVersion: row.app_version,
34193
- buildNumber: row.build_number,
34194
- deviceModel: row.device_model,
34195
- systemVersion: row.system_version,
34196
- createdAt: row.created_at,
34197
- updatedAt: row.updated_at
34198
- };
34199
- }
34200
- function syncMobilePushRegistration(input) {
34201
- const database = writeDb();
34202
- const now = Date.now();
34203
- const deviceId = input.deviceId.trim();
34204
- const platform = input.platform;
34205
- const appBundleId = input.appBundleId.trim();
34206
- const apnsEnvironment = input.apnsEnvironment;
34207
- const authorizationStatus = input.authorizationStatus;
34208
- const pushToken = input.pushToken?.trim() ? normalizeToken(input.pushToken) : null;
34209
- if (!deviceId || !appBundleId) {
34210
- throw new Error("deviceId and appBundleId are required");
34211
- }
34212
- if (!pushAllowed(authorizationStatus)) {
34213
- database.query(`DELETE FROM mobile_push_registrations
34214
- WHERE device_id = ?1
34215
- AND platform = ?2
34216
- AND app_bundle_id = ?3
34217
- AND apns_environment = ?4`).run(deviceId, platform, appBundleId, apnsEnvironment);
34218
- return { ok: true, registered: false, removed: true, token: null };
34219
- }
34220
- if (!pushToken) {
34221
- return { ok: true, registered: false, removed: false, token: null };
34222
- }
34223
- database.query(`DELETE FROM mobile_push_registrations
34224
- WHERE push_token = ?1
34225
- AND NOT (
34226
- device_id = ?2
34227
- AND platform = ?3
34228
- AND app_bundle_id = ?4
34229
- AND apns_environment = ?5
34230
- )`).run(pushToken, deviceId, platform, appBundleId, apnsEnvironment);
34231
- const existing = database.query(`SELECT id, created_at
34232
- FROM mobile_push_registrations
34233
- WHERE device_id = ?1
34234
- AND platform = ?2
34235
- AND app_bundle_id = ?3
34236
- AND apns_environment = ?4
34237
- LIMIT 1`).get(deviceId, platform, appBundleId, apnsEnvironment);
34238
- const id = existing?.id ?? `push-${deviceId}-${platform}-${appBundleId}-${apnsEnvironment}`.replace(/[^a-zA-Z0-9._-]+/g, "-");
34239
- database.query(`INSERT INTO mobile_push_registrations (
34240
- id,
34241
- device_id,
34242
- platform,
34243
- app_bundle_id,
34244
- apns_environment,
34245
- push_token,
34246
- authorization_status,
34247
- app_version,
34248
- build_number,
34249
- device_model,
34250
- system_version,
34251
- created_at,
34252
- updated_at
34253
- ) VALUES (
34254
- ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13
34255
- )
34256
- ON CONFLICT(device_id, platform, app_bundle_id, apns_environment)
34257
- DO UPDATE SET
34258
- push_token = excluded.push_token,
34259
- authorization_status = excluded.authorization_status,
34260
- app_version = excluded.app_version,
34261
- build_number = excluded.build_number,
34262
- device_model = excluded.device_model,
34263
- system_version = excluded.system_version,
34264
- updated_at = excluded.updated_at`).run(id, deviceId, platform, appBundleId, apnsEnvironment, pushToken, authorizationStatus, input.appVersion?.trim() || null, input.buildNumber?.trim() || null, input.deviceModel?.trim() || null, input.systemVersion?.trim() || null, existing?.created_at ?? now, now);
34265
- return { ok: true, registered: true, removed: false, token: pushToken };
34266
- }
34267
- function listMobilePushRegistrations(filters) {
34268
- const database = writeDb();
34269
- const where = [];
34270
- const params = [];
34271
- if (filters?.deviceId?.trim()) {
34272
- where.push(`device_id = ?${params.length + 1}`);
34273
- params.push(filters.deviceId.trim());
34274
- }
34275
- if (filters?.platform?.trim()) {
34276
- where.push(`platform = ?${params.length + 1}`);
34277
- params.push(filters.platform.trim());
34278
- }
34279
- const clause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
34280
- const rows = database.query(`SELECT *
34281
- FROM mobile_push_registrations
34282
- ${clause}
34283
- ORDER BY updated_at DESC, id ASC`).all(...params);
34284
- return rows.map(rowToRegistration);
34285
- }
34286
- function listActiveMobilePushRegistrations() {
34287
- return listMobilePushRegistrations().filter((registration) => pushAllowed(registration.authorizationStatus) && registration.pushToken.trim().length > 0);
34288
- }
34289
- function deleteMobilePushRegistrationByToken(pushToken) {
34290
- const token = normalizeToken(pushToken);
34291
- if (!token) {
34292
- return;
32004
+ function deleteMobilePushRegistrationByToken(pushToken) {
32005
+ const token = normalizeToken(pushToken);
32006
+ if (!token) {
32007
+ return;
34293
32008
  }
34294
32009
  writeDb().query(`DELETE FROM mobile_push_registrations WHERE push_token = ?1`).run(token);
34295
32010
  }
@@ -34481,6 +32196,7 @@ async function broadcastApnsAlertToActiveMobileDevices(alert) {
34481
32196
  failures
34482
32197
  };
34483
32198
  }
32199
+
34484
32200
  // ../../apps/desktop/src/core/pairing/runtime/bridge/router.ts
34485
32201
  import { readFileSync as readFileSync11, readdirSync as readdirSync4, realpathSync as realpathSync2, statSync as statSync4 } from "fs";
34486
32202
  import { execSync as execSync4 } from "child_process";
@@ -34717,8 +32433,8 @@ function getEventSessionId(event) {
34717
32433
  function trackedSequencedEventId(event) {
34718
32434
  return `${getEventSessionId(event) ?? "unknown"}:${event.seq}`;
34719
32435
  }
34720
- function approvalInboxItemId(sessionId, turnId, blockId, version3) {
34721
- return `approval:${sessionId}:${turnId}:${blockId}:v${version3}`;
32436
+ function approvalInboxItemId(sessionId, turnId, blockId, version2) {
32437
+ return `approval:${sessionId}:${turnId}:${blockId}:v${version2}`;
34722
32438
  }
34723
32439
  function projectApprovalInboxItem(snapshot, turn, block) {
34724
32440
  const normalized = normalizeApprovalRequest(snapshot.session, turn.id, block);
@@ -35772,13 +33488,13 @@ function asStringPayload(raw) {
35772
33488
  // ../../node_modules/.bun/hono@4.12.10/node_modules/hono/dist/compose.js
35773
33489
  var compose = (middleware, onError, onNotFound) => {
35774
33490
  return (context, next) => {
35775
- let index2 = -1;
33491
+ let index = -1;
35776
33492
  return dispatch(0);
35777
33493
  async function dispatch(i) {
35778
- if (i <= index2) {
33494
+ if (i <= index) {
35779
33495
  throw new Error("next() called multiple times");
35780
33496
  }
35781
- index2 = i;
33497
+ index = i;
35782
33498
  let res;
35783
33499
  let isError = false;
35784
33500
  let handler;
@@ -35875,8 +33591,8 @@ var handleParsingNestedValues = (form, key, value) => {
35875
33591
  }
35876
33592
  let nestedForm = form;
35877
33593
  const keys = key.split(".");
35878
- keys.forEach((key2, index2) => {
35879
- if (index2 === keys.length - 1) {
33594
+ keys.forEach((key2, index) => {
33595
+ if (index === keys.length - 1) {
35880
33596
  nestedForm[key2] = value;
35881
33597
  } else {
35882
33598
  if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
@@ -35902,8 +33618,8 @@ var splitRoutingPath = (routePath) => {
35902
33618
  };
35903
33619
  var extractGroupsFromPath = (path2) => {
35904
33620
  const groups = [];
35905
- path2 = path2.replace(/\{[^}]+\}/g, (match, index2) => {
35906
- const mark = `@${index2}`;
33621
+ path2 = path2.replace(/\{[^}]+\}/g, (match, index) => {
33622
+ const mark = `@${index}`;
35907
33623
  groups.push([mark, match]);
35908
33624
  return mark;
35909
33625
  });
@@ -36161,7 +33877,7 @@ var HonoRequest = class {
36161
33877
  return bodyCache[key] = raw[key]();
36162
33878
  };
36163
33879
  json() {
36164
- return this.#cachedBody("text").then((text2) => JSON.parse(text2));
33880
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
36165
33881
  }
36166
33882
  text() {
36167
33883
  return this.#cachedBody("text");
@@ -36382,8 +34098,8 @@ var Context = class {
36382
34098
  }
36383
34099
  newResponse = (...args) => this.#newResponse(...args);
36384
34100
  body = (data, arg, headers) => this.#newResponse(data, arg, headers);
36385
- text = (text2, arg, headers) => {
36386
- return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text2) : this.#newResponse(text2, arg, setDefaultContentType(TEXT_PLAIN, headers));
34101
+ text = (text, arg, headers) => {
34102
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
36387
34103
  };
36388
34104
  json = (object2, arg, headers) => {
36389
34105
  return this.#newResponse(JSON.stringify(object2), arg, setDefaultContentType("application/json", headers));
@@ -36647,8 +34363,8 @@ function match(method, path2) {
36647
34363
  if (!match3) {
36648
34364
  return [[], emptyParam];
36649
34365
  }
36650
- const index2 = match3.indexOf("", 1);
36651
- return [matcher[1][index2], match3];
34366
+ const index = match3.indexOf("", 1);
34367
+ return [matcher[1][index], match3];
36652
34368
  };
36653
34369
  this.match = match2;
36654
34370
  return match2(method, path2);
@@ -36683,7 +34399,7 @@ var Node = class _Node {
36683
34399
  #index;
36684
34400
  #varIndex;
36685
34401
  #children = /* @__PURE__ */ Object.create(null);
36686
- insert(tokens, index2, paramMap, context, pathErrorCheckOnly) {
34402
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
36687
34403
  if (tokens.length === 0) {
36688
34404
  if (this.#index !== undefined) {
36689
34405
  throw PATH_ERROR;
@@ -36691,7 +34407,7 @@ var Node = class _Node {
36691
34407
  if (pathErrorCheckOnly) {
36692
34408
  return;
36693
34409
  }
36694
- this.#index = index2;
34410
+ this.#index = index;
36695
34411
  return;
36696
34412
  }
36697
34413
  const [token, ...restTokens] = tokens;
@@ -36737,7 +34453,7 @@ var Node = class _Node {
36737
34453
  node = this.#children[token] = new _Node;
36738
34454
  }
36739
34455
  }
36740
- node.insert(restTokens, index2, paramMap, context, pathErrorCheckOnly);
34456
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
36741
34457
  }
36742
34458
  buildRegExpStr() {
36743
34459
  const childKeys = Object.keys(this.#children).sort(compareKey);
@@ -36762,7 +34478,7 @@ var Node = class _Node {
36762
34478
  var Trie = class {
36763
34479
  #context = { varIndex: 0 };
36764
34480
  #root = new Node;
36765
- insert(path2, index2, pathErrorCheckOnly) {
34481
+ insert(path2, index, pathErrorCheckOnly) {
36766
34482
  const paramAssoc = [];
36767
34483
  const groups = [];
36768
34484
  for (let i = 0;; ) {
@@ -36788,7 +34504,7 @@ var Trie = class {
36788
34504
  }
36789
34505
  }
36790
34506
  }
36791
- this.#root.insert(tokens, index2, paramAssoc, this.#context, pathErrorCheckOnly);
34507
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
36792
34508
  return paramAssoc;
36793
34509
  }
36794
34510
  buildRegExp() {
@@ -36998,11 +34714,11 @@ var PreparedRegExpRouter = class {
36998
34714
  if (!map2) {
36999
34715
  matcher[2][path2][0].push([handler, {}]);
37000
34716
  } else {
37001
- indexes.forEach((index2) => {
37002
- if (typeof index2 === "number") {
37003
- matcher[1][index2].push([handler, map2]);
34717
+ indexes.forEach((index) => {
34718
+ if (typeof index === "number") {
34719
+ matcher[1][index].push([handler, map2]);
37004
34720
  } else {
37005
- matcher[2][index2 || path2][0].push([handler, map2]);
34721
+ matcher[2][index || path2][0].push([handler, map2]);
37006
34722
  }
37007
34723
  });
37008
34724
  }
@@ -37481,22 +35197,22 @@ var jsonContentTypeHandler = {
37481
35197
  message: '"input" needs to be an object when doing a batch call'
37482
35198
  });
37483
35199
  const acc = emptyObject();
37484
- for (const index2 of paths.keys()) {
37485
- const input = inputs[index2];
35200
+ for (const index of paths.keys()) {
35201
+ const input = inputs[index];
37486
35202
  if (input !== undefined)
37487
- acc[index2] = opts.router._def._config.transformer.input.deserialize(input);
35203
+ acc[index] = opts.router._def._config.transformer.input.deserialize(input);
37488
35204
  }
37489
35205
  return acc;
37490
35206
  });
37491
- const calls = await Promise.all(paths.map(async (path2, index2) => {
35207
+ const calls = await Promise.all(paths.map(async (path2, index) => {
37492
35208
  const procedure2 = await getProcedureAtPath(opts.router, path2);
37493
35209
  return {
37494
- batchIndex: index2,
35210
+ batchIndex: index,
37495
35211
  path: path2,
37496
35212
  procedure: procedure2,
37497
35213
  getRawInput: async () => {
37498
35214
  const inputs = await getInputs.read();
37499
- let input = inputs[index2];
35215
+ let input = inputs[index];
37500
35216
  if ((procedure2 === null || procedure2 === undefined ? undefined : procedure2._def.type) === "subscription") {
37501
35217
  var _ref2, _opts$headers$get;
37502
35218
  const lastEventId = (_ref2 = (_opts$headers$get = opts.headers.get("last-event-id")) !== null && _opts$headers$get !== undefined ? _opts$headers$get : opts.searchParams.get("lastEventId")) !== null && _ref2 !== undefined ? _ref2 : opts.searchParams.get("Last-Event-Id");
@@ -37512,7 +35228,7 @@ var jsonContentTypeHandler = {
37512
35228
  },
37513
35229
  result: () => {
37514
35230
  var _getInputs$result;
37515
- return (_getInputs$result = getInputs.result()) === null || _getInputs$result === undefined ? undefined : _getInputs$result[index2];
35231
+ return (_getInputs$result = getInputs.result()) === null || _getInputs$result === undefined ? undefined : _getInputs$result[index];
37516
35232
  }
37517
35233
  };
37518
35234
  }));
@@ -37800,13 +35516,13 @@ function withResolvers() {
37800
35516
  function listWithMember(arr, member) {
37801
35517
  return [...arr, member];
37802
35518
  }
37803
- function listWithoutIndex(arr, index2) {
37804
- return [...arr.slice(0, index2), ...arr.slice(index2 + 1)];
35519
+ function listWithoutIndex(arr, index) {
35520
+ return [...arr.slice(0, index), ...arr.slice(index + 1)];
37805
35521
  }
37806
35522
  function listWithoutMember(arr, member) {
37807
- const index2 = arr.indexOf(member);
37808
- if (index2 !== -1)
37809
- return listWithoutIndex(arr, index2);
35523
+ const index = arr.indexOf(member);
35524
+ if (index !== -1)
35525
+ return listWithoutIndex(arr, index);
37810
35526
  return arr;
37811
35527
  }
37812
35528
  var _Symbol;
@@ -39019,9 +36735,9 @@ async function resolveResponse(opts) {
39019
36735
  });
39020
36736
  const stream = jsonlStreamProducer((0, import_objectSpread24.default)((0, import_objectSpread24.default)({}, config2.jsonl), {}, {
39021
36737
  maxDepth: Infinity,
39022
- data: rpcCalls.map(async (res, index2) => {
36738
+ data: rpcCalls.map(async (res, index) => {
39023
36739
  const [error48, result] = await res;
39024
- const call = info.calls[index2];
36740
+ const call = info.calls[index];
39025
36741
  if (error48) {
39026
36742
  var _procedure$_def$type, _procedure;
39027
36743
  return { error: getErrorShape({
@@ -39083,8 +36799,8 @@ async function resolveResponse(opts) {
39083
36799
  }), undefined];
39084
36800
  return res;
39085
36801
  });
39086
- const resultAsRPCResponse = results.map(([error48, result], index2) => {
39087
- const call = info.calls[index2];
36802
+ const resultAsRPCResponse = results.map(([error48, result], index) => {
36803
+ const call = info.calls[index];
39088
36804
  if (error48) {
39089
36805
  var _call$procedure$_def$4, _call$procedure5;
39090
36806
  return { error: getErrorShape({
@@ -39189,7 +36905,7 @@ async function fetchRequestHandler(opts) {
39189
36905
 
39190
36906
  // ../../node_modules/.bun/hono@4.12.10/node_modules/hono/dist/helper/route/index.js
39191
36907
  var matchedRoutes = (c) => c.req[GET_MATCH_RESULT][0].map(([[, route2]]) => route2);
39192
- var routePath = (c, index2) => matchedRoutes(c).at(index2 ?? c.req.routeIndex)?.path ?? "";
36908
+ var routePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.path ?? "";
39193
36909
 
39194
36910
  // ../../node_modules/.bun/@hono+trpc-server@0.4.2+2b2485a92adeb0d0/node_modules/@hono/trpc-server/dist/index.js
39195
36911
  var trpcServer = ({ endpoint, createContext, ...rest }) => {
@@ -39352,14 +37068,14 @@ function startBridgeServerTRPC(options) {
39352
37068
  }
39353
37069
  };
39354
37070
  }
39355
- async function handleTRPCMessage(ws, state, text2) {
37071
+ async function handleTRPCMessage(ws, state, text) {
39356
37072
  const send = createSender(ws, state);
39357
37073
  if (!bridgeRouter) {
39358
- await handleLegacyFallback(ws, state, text2);
37074
+ await handleLegacyFallback(ws, state, text);
39359
37075
  return;
39360
37076
  }
39361
37077
  try {
39362
- const msgJSON = JSON.parse(text2);
37078
+ const msgJSON = JSON.parse(text);
39363
37079
  const msgs = Array.isArray(msgJSON) ? msgJSON : [msgJSON];
39364
37080
  for (const raw2 of msgs) {
39365
37081
  log.info("rpc:req", `\u2192 ${raw2.params?.path ?? raw2.method ?? "?"}`);
@@ -39548,7 +37264,7 @@ function startBridgeServerTRPC(options) {
39548
37264
  });
39549
37265
  }
39550
37266
  }
39551
- async function handleLegacyFallback(ws, state, text2) {
37267
+ async function handleLegacyFallback(ws, state, text) {
39552
37268
  const sendRaw = (json2) => {
39553
37269
  if (state.transport) {
39554
37270
  state.transport.send(json2);
@@ -39558,7 +37274,7 @@ function startBridgeServerTRPC(options) {
39558
37274
  };
39559
37275
  let req;
39560
37276
  try {
39561
- req = JSON.parse(text2);
37277
+ req = JSON.parse(text);
39562
37278
  } catch {
39563
37279
  sendRaw(JSON.stringify({ id: null, error: { code: -32700, message: "Parse error" } }));
39564
37280
  return;
@@ -39672,8 +37388,8 @@ function startBridgeServerTRPC(options) {
39672
37388
  const data = typeof raw2 === "string" ? raw2 : new Uint8Array(raw2);
39673
37389
  state.transport.receive(data);
39674
37390
  } else {
39675
- const text2 = typeof raw2 === "string" ? raw2 : new TextDecoder().decode(raw2);
39676
- handleTRPCMessage(ws, state, text2);
37391
+ const text = typeof raw2 === "string" ? raw2 : new TextDecoder().decode(raw2);
37392
+ handleTRPCMessage(ws, state, text);
39677
37393
  }
39678
37394
  },
39679
37395
  close(ws) {