-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
2943 lines (2581 loc) · 111 KB
/
Copy pathserver.ts
File metadata and controls
2943 lines (2581 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
backgroundFunction,
EmailTriggerParamsSchema,
type EmailTriggerParams,
type ServerSdk,
serverFunction,
} from "@dev-agents/sdk-server";
import { getUserTimeZone, Type } from "@dev-agents/sdk-shared";
import dayjs from "dayjs";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import { and, desc, eq, inArray, lte, isNotNull } from "drizzle-orm";
import Handlebars from "handlebars";
import { create_agent_post } from "../tools/posts";
import { headlines, searchNews } from "../tools/news";
import { crawlUrlMarkdown } from "../tools/webcrawl";
// Gemini removed — Perplexity is the sole supplemental search source
import { sonarSearch } from "../tools/perplexity";
import { getFlightStatus } from "../tools/flightaware";
import { exaWebSearch } from "../tools/exa";
import { listAccounts as calListAccounts, getEventsForDay } from "../tools/calendar";
// contacts and slack tools are not connected yet
// import { contactsListAccounts, searchContacts } from "../tools/contacts";
// import { listWorkspaces, listChannels, slackListMessages } from "../tools/slack";
import { listAccounts as listMailAccounts, searchMessages as searchMailMessages } from "../tools/mail";
import { create_sidekick_task, query_running_sidekick_tasks } from "../tools/sidekicktasks";
import parseWatchSource from "./prompts/parse-watch.handlebars";
import matchEmailSource from "./prompts/match-email-to-watches.handlebars";
import matchNewsSource from "./prompts/match-news-to-watch.handlebars";
import matchWebSource from "./prompts/match-web-to-watch.handlebars";
import learnDismissalSource from "./prompts/learn-from-dismissal.handlebars";
import generateQueriesSource from "./prompts/generate-search-queries.handlebars";
import profileSource from "./prompts/get-user-profile-sidekick.handlebars";
import digestSource from "./prompts/digest-summary.handlebars";
import enrichArticleSource from "./prompts/enrich-article.handlebars";
import combineReportSource from "./prompts/combine-watch-report.handlebars";
import checkExpirySource from "./prompts/check-watch-expiry.handlebars";
import checkExpiryBatchSource from "./prompts/check-watches-expiry-batch.handlebars";
import matchCalendarSource from "./prompts/match-calendar-to-watch.handlebars";
import matchFlightSource from "./prompts/match-flight-to-watch.handlebars";
import matchContactsSource from "./prompts/match-contacts-to-watch.handlebars";
import matchSlackSource from "./prompts/match-slack-to-watch.handlebars";
import extractPriceSource from "./prompts/extract-price.handlebars";
import personalizedExamplesSource from "./prompts/personalized-watch-examples.handlebars";
import checkWatchesTaskSource from "./prompts/check-watches-task.handlebars";
import type * as schema from "./schema";
import {
alerts,
dismissalPatterns,
processedItems,
staleProcessedItems,
userProfile,
watches,
} from "./schema";
dayjs.extend(utc);
dayjs.extend(timezone);
const parseWatchTemplate = Handlebars.compile(parseWatchSource);
const matchEmailTemplate = Handlebars.compile(matchEmailSource);
const matchNewsTemplate = Handlebars.compile(matchNewsSource);
const matchWebTemplate = Handlebars.compile(matchWebSource);
const learnDismissalTemplate = Handlebars.compile(learnDismissalSource);
const generateQueriesTemplate = Handlebars.compile(generateQueriesSource);
const profileTemplate = Handlebars.compile(profileSource);
const digestTemplate = Handlebars.compile(digestSource);
const enrichArticleTemplate = Handlebars.compile(enrichArticleSource);
const combineReportTemplate = Handlebars.compile(combineReportSource);
const checkExpiryTemplate = Handlebars.compile(checkExpirySource);
const checkExpiryBatchTemplate = Handlebars.compile(checkExpiryBatchSource);
const matchCalendarTemplate = Handlebars.compile(matchCalendarSource);
const matchFlightTemplate = Handlebars.compile(matchFlightSource);
const matchContactsTemplate = Handlebars.compile(matchContactsSource);
const matchSlackTemplate = Handlebars.compile(matchSlackSource);
const extractPriceTemplate = Handlebars.compile(extractPriceSource);
const personalizedExamplesTemplate = Handlebars.compile(personalizedExamplesSource);
const checkWatchesTaskTemplate = Handlebars.compile(checkWatchesTaskSource);
const MAX_CRAWL_CONTENT_LENGTH = 8000;
const MAX_ENRICHMENTS_PER_QUERY = 2;
const CRAWL_TIMEOUT_MS = 30_000; // 30 second timeout for crawling
const PER_WATCH_TIMEOUT_MS = 180_000; // 3 minute timeout per watch
const OVERALL_BUDGET_MS = 540_000; // 9 minute total budget for all watches
const WATCH_CONCURRENCY = 3; // Process up to 3 watches in parallel
const WATCH_CHECK_INTERVAL_MS = 2 * 60 * 60 * 1000; // 2 hours between checks per watch
/** Wraps a promise with a timeout — rejects if it takes too long */
function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
return Promise.race([
promise,
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error(`Timeout after ${ms}ms: ${label}`)), ms)
),
]);
}
// ─── USER PROFILE ──────────────────────────────────────────────
export const getUserProfile = serverFunction({
description: "Get the current user's profile",
params: Type.Object({}),
exported: true,
execute: async (sdk: ServerSdk) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const results = await db.select().from(userProfile).where(eq(userProfile.owner, owner)).limit(1);
console.log("getUserProfile: found", results.length, "profiles");
return results[0] || null;
},
});
export const initializeProfile = serverFunction({
description: "Initialize user profile from Sidekick knowledge (call once)",
params: Type.Object({}),
execute: async (sdk: ServerSdk) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const existing = await db.select().from(userProfile).where(eq(userProfile.owner, owner)).limit(1);
if (existing[0]) {
console.log("initializeProfile: profile already exists");
return { profile: existing[0], alreadyInitialized: true };
}
console.log("initializeProfile: asking Sidekick for profile data");
const sidekickData = await sdk.sidekickWithSchema(
profileTemplate({}),
Type.Object({
location: Type.Optional(Type.String()),
interests: Type.Optional(Type.Array(Type.String())),
})
);
console.log("initializeProfile: got Sidekick data", JSON.stringify(sidekickData));
return { profile: sidekickData, alreadyInitialized: false };
},
});
export const saveProfile = serverFunction({
description: "Save or update user profile",
params: Type.Object({
location: Type.Optional(Type.String()),
interests: Type.Optional(Type.Array(Type.String())),
}),
exported: true,
execute: async (sdk: ServerSdk, { location, interests }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const now = dayjs().tz(getUserTimeZone()).toDate();
const existing = await db.select().from(userProfile).where(eq(userProfile.owner, owner)).limit(1);
if (existing[0]) {
await db.update(userProfile)
.set({
location: location || existing[0].location,
interests: interests ? JSON.stringify(interests) : existing[0].interests,
updatedAt: now,
})
.where(eq(userProfile.id, existing[0].id));
console.log("saveProfile: updated profile");
} else {
await db.insert(userProfile).values({
owner,
location: location || null,
interests: interests ? JSON.stringify(interests) : null,
createdAt: now,
updatedAt: now,
});
console.log("saveProfile: created profile");
}
return { success: true };
},
});
export const syncProfileToSidekick = backgroundFunction({
description: "Sync profile changes to Sidekick memory",
params: Type.Object({
location: Type.Optional(Type.String()),
interests: Type.Optional(Type.Array(Type.String())),
}),
execute: async (sdk: ServerSdk, profileData) => {
await sdk.sidekickWithSchema(
`The user just updated their profile for the Radar monitoring agent: ${JSON.stringify(profileData)}. Update your memory about the user's interests and location.`,
Type.Object({ success: Type.Boolean() })
);
console.log("syncProfileToSidekick: synced");
},
});
// ─── WATCH MANAGEMENT ──────────────────────────────────────────
export const createWatch = serverFunction({
description: "Create a new watch from natural language description",
params: Type.Object({
description: Type.String({ minLength: 1, description: "Natural language description of what to monitor" }),
urgency: Type.Optional(Type.String({ description: "Legacy: 'instant' or 'digest'. Prefer checkInterval instead." })),
checkInterval: Type.Optional(Type.Number({ description: "Minutes between checks: 15, 30, 60, 120, 240, 1440 (daily), 10080 (weekly)" })),
preferredTime: Type.Optional(Type.String({ description: "HH:mm for daily/weekly watches (user's timezone)" })),
preferredDay: Type.Optional(Type.String({ description: "Day of week for weekly watches: monday, tuesday, etc." })),
webUrl: Type.Optional(Type.String({ description: "Optional URL to monitor" })),
targetPrice: Type.Optional(Type.String({ description: "Target price threshold for price tracking" })),
flightNumber: Type.Optional(Type.String({ description: "Flight number to track (e.g., UA123)" })),
slackChannels: Type.Optional(Type.Array(Type.String(), { description: "Slack channel names to monitor" })),
contactEmails: Type.Optional(Type.Array(Type.String(), { description: "Contact emails for relationship nudges" })),
digestTime: Type.Optional(Type.String({ description: "Legacy: Preferred daily digest time in HH:mm format" })),
}),
exported: true,
execute: async (sdk: ServerSdk, { description, urgency, checkInterval, preferredTime, preferredDay, webUrl, targetPrice, flightNumber, slackChannels, contactEmails, digestTime }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const now = dayjs().tz(getUserTimeZone()).toDate();
// Get user profile for context
const profile = await db.select().from(userProfile).where(eq(userProfile.owner, owner)).limit(1);
const userLocation = profile[0]?.location || undefined;
const userInterests = profile[0]?.interests || undefined;
console.log("createWatch: parsing description:", description);
const parsed = await sdk.callLLM(
parseWatchTemplate({ description, userLocation, userInterests }),
Type.Object({
topics: Type.Array(Type.String()),
sourceTypes: Type.Array(Type.String()),
suggestedUrgency: Type.String(),
suggestedCheckInterval: Type.Optional(Type.Number()),
needsClarification: Type.Boolean(),
clarifyingQuestions: Type.Optional(Type.Array(Type.String())),
webUrl: Type.Optional(Type.String()),
flightNumber: Type.Optional(Type.String()),
targetPrice: Type.Optional(Type.String()),
contactEmails: Type.Optional(Type.Array(Type.String())),
slackChannels: Type.Optional(Type.Array(Type.String())),
}),
{ modelVariant: "STANDARD" }
);
console.log("createWatch: parsed result", JSON.stringify(parsed));
if (!parsed) {
return { needsClarification: false, watch: null, error: "Failed to parse watch" };
}
if (parsed.needsClarification && parsed.clarifyingQuestions && parsed.clarifyingQuestions.length > 0) {
return {
needsClarification: true,
clarifyingQuestions: parsed.clarifyingQuestions,
parsedTopics: parsed.topics,
suggestedUrgency: parsed.suggestedUrgency,
suggestedCheckInterval: parsed.suggestedCheckInterval,
sourceTypes: parsed.sourceTypes,
};
}
const finalUrl = webUrl || parsed.webUrl || null;
const finalSourceTypes = parsed.sourceTypes;
if (finalUrl && !finalSourceTypes.includes("web")) {
finalSourceTypes.push("web");
}
// Resolve extra fields from explicit params or LLM-parsed values
const finalFlightNumber = flightNumber || parsed.flightNumber || null;
const finalTargetPrice = targetPrice || parsed.targetPrice || null;
const finalContactEmails = contactEmails || parsed.contactEmails || null;
const finalSlackChannels = slackChannels || parsed.slackChannels || null;
// Auto-add source types based on resolved fields
if (finalFlightNumber && !finalSourceTypes.includes("flight")) {
finalSourceTypes.push("flight");
}
if (finalContactEmails && finalContactEmails.length > 0 && !finalSourceTypes.includes("contacts")) {
finalSourceTypes.push("contacts");
}
// Determine check interval: explicit param > LLM suggestion > derive from urgency > default 120
const finalCheckInterval = checkInterval
|| parsed.suggestedCheckInterval
|| (urgency === "digest" || parsed.suggestedUrgency === "digest" ? 1440 : 120);
// Derive urgency for backward compatibility
const finalUrgency = finalCheckInterval >= 1440 ? "digest" : "instant";
const inserted = await db.insert(watches).values({
owner,
description,
parsedTopics: JSON.stringify(parsed.topics),
sourceTypes: JSON.stringify(finalSourceTypes),
urgency: finalUrgency,
checkInterval: finalCheckInterval,
preferredTime: preferredTime || (finalCheckInterval >= 1440 ? (digestTime || "08:00") : null),
preferredDay: preferredDay || null,
status: "active",
webUrl: finalUrl,
targetPrice: finalTargetPrice,
flightNumber: finalFlightNumber,
slackChannels: finalSlackChannels ? JSON.stringify(finalSlackChannels) : null,
contactEmails: finalContactEmails ? JSON.stringify(finalContactEmails) : null,
digestTime: digestTime || null,
createdAt: now,
updatedAt: now,
}).returning();
console.log("createWatch: created watch", inserted[0]?.id);
return {
needsClarification: false,
watch: inserted[0],
};
},
});
export const getWatches = serverFunction({
description: "Get all watches for the current user",
params: Type.Object({}),
exported: true,
execute: async (sdk: ServerSdk) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const results = await db.select().from(watches)
.where(eq(watches.owner, owner))
.orderBy(desc(watches.createdAt));
console.log("getWatches: returning", results.length, "watches");
return results;
},
});
export const getPersonalizedExamples = serverFunction({
description: "Get personalized watch examples based on Sidekick's knowledge of the user",
params: Type.Object({}),
execute: async (sdk: ServerSdk) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
// Get existing watches so we don't suggest duplicates
const existingWatches = await db.select({ description: watches.description })
.from(watches)
.where(eq(watches.owner, owner));
try {
const result = await sdk.sidekickWithSchema(
personalizedExamplesTemplate({
existingWatches: existingWatches.length > 0
? existingWatches.map(w => w.description)
: null,
}),
Type.Object({
suggestions: Type.Array(Type.String(), { minItems: 1, maxItems: 3 }),
})
);
console.log("getPersonalizedExamples: got", result?.suggestions?.length || 0, "suggestions");
return { suggestions: result?.suggestions || [] };
} catch (error) {
console.error("getPersonalizedExamples: failed", error);
return { suggestions: [] };
}
},
});
export const updateWatch = serverFunction({
description: "Update a watch's settings",
params: Type.Object({
id: Type.Number({ description: "Watch ID" }),
urgency: Type.Optional(Type.String()),
checkInterval: Type.Optional(Type.Number({ description: "Minutes between checks: 15, 30, 60, 120, 240, 1440, 10080" })),
preferredTime: Type.Optional(Type.String({ description: "HH:mm for daily/weekly watches" })),
preferredDay: Type.Optional(Type.String({ description: "Day of week for weekly watches" })),
status: Type.Optional(Type.String()),
description: Type.Optional(Type.String()),
webUrl: Type.Optional(Type.String()),
snoozeUntil: Type.Optional(Type.String({ description: "ISO date string for snooze end, or null to clear" })),
targetPrice: Type.Optional(Type.String({ description: "Target price threshold for price tracking" })),
flightNumber: Type.Optional(Type.String({ description: "Flight number to track (e.g., UA123)" })),
slackChannels: Type.Optional(Type.Array(Type.String(), { description: "Slack channel names to monitor" })),
contactEmails: Type.Optional(Type.Array(Type.String(), { description: "Contact emails for relationship nudges" })),
digestTime: Type.Optional(Type.String({ description: "Legacy: Preferred daily digest time in HH:mm format" })),
}),
exported: true,
execute: async (sdk: ServerSdk, { id, urgency, checkInterval, preferredTime, preferredDay, status, description, webUrl, snoozeUntil, targetPrice, flightNumber, slackChannels, contactEmails, digestTime }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const now = dayjs().tz(getUserTimeZone()).toDate();
const existing = await db.select().from(watches)
.where(and(eq(watches.id, id), eq(watches.owner, owner)))
.limit(1);
if (!existing[0]) {
return { success: false, error: "Watch not found" };
}
const updates: Record<string, unknown> = { updatedAt: now };
if (checkInterval !== undefined) {
updates.checkInterval = checkInterval;
// Derive urgency for backward compatibility
updates.urgency = checkInterval >= 1440 ? "digest" : "instant";
} else if (urgency) {
updates.urgency = urgency;
}
if (preferredTime !== undefined) updates.preferredTime = preferredTime || null;
if (preferredDay !== undefined) updates.preferredDay = preferredDay || null;
if (status) updates.status = status;
if (webUrl !== undefined) updates.webUrl = webUrl || null;
if (targetPrice !== undefined) updates.targetPrice = targetPrice || null;
if (flightNumber !== undefined) updates.flightNumber = flightNumber || null;
if (slackChannels !== undefined) updates.slackChannels = slackChannels.length > 0 ? JSON.stringify(slackChannels) : null;
if (contactEmails !== undefined) updates.contactEmails = contactEmails.length > 0 ? JSON.stringify(contactEmails) : null;
if (digestTime !== undefined) updates.digestTime = digestTime || null;
// Handle snooze
if (snoozeUntil === "null" || snoozeUntil === "") {
updates.snoozeUntil = null;
// If clearing snooze, also resume watch
if (!status) updates.status = "active";
} else if (snoozeUntil) {
updates.snoozeUntil = dayjs(snoozeUntil).tz(getUserTimeZone()).toDate();
updates.status = "paused";
}
// If description changed, re-parse topics
if (description && description !== existing[0].description) {
updates.description = description;
// Get user profile for context
const profile = await db.select().from(userProfile).where(eq(userProfile.owner, owner)).limit(1);
const userLocation = profile[0]?.location || undefined;
const userInterests = profile[0]?.interests || undefined;
try {
const parsed = await sdk.callLLM(
parseWatchTemplate({ description, userLocation, userInterests }),
Type.Object({
topics: Type.Array(Type.String()),
sourceTypes: Type.Array(Type.String()),
suggestedUrgency: Type.String(),
needsClarification: Type.Boolean(),
clarifyingQuestions: Type.Optional(Type.Array(Type.String())),
webUrl: Type.Optional(Type.String()),
}),
{ modelVariant: "STANDARD" }
);
if (parsed) {
updates.parsedTopics = JSON.stringify(parsed.topics);
updates.sourceTypes = JSON.stringify(parsed.sourceTypes);
if (!urgency) updates.urgency = parsed.suggestedUrgency;
if (parsed.webUrl && !webUrl) updates.webUrl = parsed.webUrl;
}
} catch (error) {
console.error("updateWatch: failed to re-parse description", error);
// Keep old topics if re-parse fails
}
}
await db.update(watches).set(updates).where(eq(watches.id, id));
console.log("updateWatch: updated watch", id, "fields:", Object.keys(updates).join(", "));
return { success: true };
},
});
export const deleteWatch = serverFunction({
description: "Delete a watch",
params: Type.Object({
id: Type.Number({ description: "Watch ID" }),
}),
exported: true,
execute: async (sdk: ServerSdk, { id }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
await db.delete(watches).where(and(eq(watches.id, id), eq(watches.owner, owner)));
await db.delete(alerts).where(and(eq(alerts.watchId, id), eq(alerts.owner, owner)));
await db.delete(dismissalPatterns).where(and(eq(dismissalPatterns.watchId, id), eq(dismissalPatterns.owner, owner)));
// Archive processedItems to stale table before deleting
const itemsToArchive = await db.select().from(processedItems)
.where(and(eq(processedItems.watchId, id), eq(processedItems.owner, owner)));
if (itemsToArchive.length > 0) {
await db.insert(staleProcessedItems).values(itemsToArchive.map(item => ({
owner: item.owner,
uniqueId: item.uniqueId,
sourceType: item.sourceType,
watchId: item.watchId,
processedAt: item.processedAt,
})));
await db.delete(processedItems).where(and(eq(processedItems.watchId, id), eq(processedItems.owner, owner)));
}
console.log("deleteWatch: deleted watch", id, "and related data");
return { success: true };
},
});
// ─── ALERT MANAGEMENT ──────────────────────────────────────────
export const getAlerts = serverFunction({
description: "Get alerts for the current user",
params: Type.Object({
watchId: Type.Optional(Type.Number({ description: "Filter by watch ID" })),
includeRead: Type.Optional(Type.Boolean({ description: "Include read alerts" })),
limit: Type.Optional(Type.Number({ description: "Max alerts to return" })),
}),
exported: true,
execute: async (sdk: ServerSdk, { watchId, includeRead, limit }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const conditions = [eq(alerts.owner, owner), eq(alerts.dismissed, false)];
if (watchId) conditions.push(eq(alerts.watchId, watchId));
if (!includeRead) conditions.push(eq(alerts.read, false));
const results = await db.select().from(alerts)
.where(and(...conditions))
.orderBy(desc(alerts.createdAt))
.limit(limit || 50);
console.log("getAlerts: returning", results.length, "alerts");
return results;
},
});
export const getAlertCounts = serverFunction({
description: "Get count of unread alerts, both total and per watch",
params: Type.Object({}),
exported: true,
execute: async (sdk: ServerSdk) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const unread = await db.select({ watchId: alerts.watchId }).from(alerts)
.where(and(eq(alerts.owner, owner), eq(alerts.dismissed, false), eq(alerts.read, false)));
// Build per-watch counts
const perWatch: Record<number, number> = {};
for (const a of unread) {
perWatch[a.watchId] = (perWatch[a.watchId] || 0) + 1;
}
return { unreadCount: unread.length, perWatch };
},
});
export const markAlertRead = serverFunction({
description: "Mark an alert as read",
params: Type.Object({
id: Type.Number({ description: "Alert ID" }),
}),
exported: true,
execute: async (sdk: ServerSdk, { id }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
await db.update(alerts)
.set({ read: true })
.where(and(eq(alerts.id, id), eq(alerts.owner, owner)));
console.log("markAlertRead: marked alert", id, "as read");
return { success: true };
},
});
export const dismissAlert = serverFunction({
description: "Dismiss an alert and optionally learn from it",
params: Type.Object({
id: Type.Number({ description: "Alert ID" }),
feedback: Type.Optional(Type.String({ description: "Why the alert was irrelevant" })),
}),
exported: true,
execute: async (sdk: ServerSdk, { id, feedback }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const alertResults = await db.select().from(alerts)
.where(and(eq(alerts.id, id), eq(alerts.owner, owner)))
.limit(1);
if (!alertResults[0]) {
return { success: false, error: "Alert not found" };
}
const alert = alertResults[0];
await db.update(alerts)
.set({ dismissed: true, dismissFeedback: feedback || null })
.where(eq(alerts.id, id));
// Learn from dismissal
const watchResults = await db.select().from(watches)
.where(eq(watches.id, alert.watchId))
.limit(1);
if (watchResults[0]) {
const existingDismissals = await db.select().from(dismissalPatterns)
.where(and(eq(dismissalPatterns.watchId, alert.watchId), eq(dismissalPatterns.owner, owner)));
try {
const learned = await sdk.callLLM(
learnDismissalTemplate({
watchDescription: watchResults[0].description,
alertTitle: alert.title,
alertSnippet: alert.snippet,
alertSource: alert.sourceName,
feedback,
existingPatterns: existingDismissals.map(d => d.pattern),
}),
Type.Object({
pattern: Type.String(),
}),
{ modelVariant: "FAST" }
);
if (learned) {
await db.insert(dismissalPatterns).values({
owner,
watchId: alert.watchId,
pattern: learned.pattern,
createdAt: dayjs().tz(getUserTimeZone()).toDate(),
});
console.log("dismissAlert: learned pattern:", learned.pattern);
}
} catch (error) {
console.error("dismissAlert: failed to learn from dismissal", error);
}
}
return { success: true };
},
});
export const markAllAlertsRead = serverFunction({
description: "Mark all alerts as read for a watch (or all watches)",
params: Type.Object({
watchId: Type.Optional(Type.Number({ description: "Specific watch ID, or omit for all" })),
}),
exported: true,
execute: async (sdk: ServerSdk, { watchId }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const conditions = [eq(alerts.owner, owner), eq(alerts.dismissed, false), eq(alerts.read, false)];
if (watchId) conditions.push(eq(alerts.watchId, watchId));
const unread = await db.select({ id: alerts.id }).from(alerts)
.where(and(...conditions));
for (const a of unread) {
await db.update(alerts).set({ read: true }).where(eq(alerts.id, a.id));
}
console.log("markAllAlertsRead: marked", unread.length, "alerts as read", watchId ? `for watch ${watchId}` : "for all watches");
return { success: true, count: unread.length };
},
});
export const dismissAllAlerts = serverFunction({
description: "Dismiss all alerts for a watch",
params: Type.Object({
watchId: Type.Number({ description: "Watch ID" }),
}),
exported: true,
execute: async (sdk: ServerSdk, { watchId }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const toDismiss = await db.select({ id: alerts.id }).from(alerts)
.where(and(eq(alerts.owner, owner), eq(alerts.watchId, watchId), eq(alerts.dismissed, false)));
for (const a of toDismiss) {
await db.update(alerts).set({ dismissed: true }).where(eq(alerts.id, a.id));
}
console.log("dismissAllAlerts: dismissed", toDismiss.length, "alerts for watch", watchId);
return { success: true, count: toDismiss.length };
},
});
// ─── SIDEKICK TASK HELPER FUNCTIONS (callable mid-execution) ────
export const checkProcessedUrls = serverFunction({
description: "Check which URLs have already been processed for a watch. Returns new (not yet processed) and already-processed URLs. Call this after searching to filter out already-seen articles before crawling.",
params: Type.Object({
watchId: Type.Number({ description: "The watch ID to check against" }),
urls: Type.Array(Type.String(), { description: "URLs from search results to check" }),
}),
exported: true,
execute: async (sdk: ServerSdk, { watchId, urls }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
if (urls.length === 0) {
return { newUrls: [], alreadyProcessedUrls: [] };
}
const [processed, staleProcessed] = await Promise.all([
db.select({ uniqueId: processedItems.uniqueId })
.from(processedItems)
.where(and(
eq(processedItems.owner, owner),
eq(processedItems.watchId, watchId),
inArray(processedItems.uniqueId, urls),
)),
db.select({ uniqueId: staleProcessedItems.uniqueId })
.from(staleProcessedItems)
.where(and(
eq(staleProcessedItems.owner, owner),
inArray(staleProcessedItems.uniqueId, urls),
)),
]);
const processedSet = new Set([
...processed.map(p => p.uniqueId),
...staleProcessed.map(p => p.uniqueId),
]);
const newUrls = urls.filter(url => !processedSet.has(url));
const alreadyProcessedUrls = urls.filter(url => processedSet.has(url));
console.log("checkProcessedUrls: watch", watchId, "checked", urls.length, "URLs,", newUrls.length, "new,", alreadyProcessedUrls.length, "already processed");
return { newUrls, alreadyProcessedUrls };
},
});
export const markUrlsProcessed = serverFunction({
description: "Mark URLs as processed for a watch so they won't be re-checked in future runs. Call this after filtering out non-matching articles (Step 5) and after crawling matched articles (Step 9).",
params: Type.Object({
watchId: Type.Number({ description: "The watch ID" }),
urls: Type.Array(Type.String(), { description: "URLs to mark as processed" }),
}),
exported: true,
execute: async (sdk: ServerSdk, { watchId, urls }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const now = dayjs().tz(getUserTimeZone()).toDate();
let marked = 0;
for (const url of urls) {
try {
await db.insert(processedItems).values({
owner,
uniqueId: url,
sourceType: "news",
watchId,
processedAt: now,
});
marked++;
} catch {
// Unique constraint — already processed, skip
}
}
console.log("markUrlsProcessed: watch", watchId, "marked", marked, "of", urls.length, "URLs as processed");
return { marked };
},
});
export const getDismissalPatterns = serverFunction({
description: "Get dismissal patterns for a watch. These are patterns learned from the user's previous alert dismissals — content matching these patterns should be filtered out as irrelevant.",
params: Type.Object({
watchId: Type.Number({ description: "The watch ID" }),
}),
exported: true,
execute: async (sdk: ServerSdk, { watchId }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const patterns = await db.select().from(dismissalPatterns)
.where(and(
eq(dismissalPatterns.owner, owner),
eq(dismissalPatterns.watchId, watchId),
));
console.log("getDismissalPatterns: watch", watchId, "returning", patterns.length, "patterns");
return { patterns: patterns.map(p => p.pattern) };
},
});
export const getPastReports = serverFunction({
description: "Get recent reports with full content for a watch. Use during the synthesis step to compare new articles against past reports and produce only incremental updates — never repeat information already reported.",
params: Type.Object({
watchId: Type.Number({ description: "The watch ID" }),
limit: Type.Optional(Type.Number({ description: "Max number of reports to return. Defaults to 5." })),
}),
exported: true,
execute: async (sdk: ServerSdk, { watchId, limit }) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const maxReports = limit || 5;
const recentAlerts = await db.select().from(alerts)
.where(and(
eq(alerts.watchId, watchId),
eq(alerts.owner, owner),
eq(alerts.dismissed, false),
isNotNull(alerts.fullContent),
))
.orderBy(desc(alerts.createdAt))
.limit(maxReports);
const reports = recentAlerts.map(a => ({
title: a.title,
fullContent: a.fullContent!.substring(0, 2000),
sourceUrl: a.sourceUrl,
sourceName: a.sourceName,
createdAt: dayjs(a.createdAt).tz(getUserTimeZone()).format("YYYY-MM-DD HH:mm"),
}));
console.log("getPastReports: watch", watchId, "returning", reports.length, "reports");
return { reports };
},
});
// ─── MONITORING: EMAIL ──────────────────────────────────────────
export const handleIncomingEmail = backgroundFunction({
description: "Process incoming emails and match against active watches",
params: EmailTriggerParamsSchema,
exported: true,
execute: async (sdk: ServerSdk, params: EmailTriggerParams) => {
const db = sdk.db<typeof schema>();
const owner = sdk.getUser().email;
const now = dayjs().tz(getUserTimeZone()).toDate();
// Get active watches that monitor email
const activeWatches = await db.select().from(watches)
.where(and(eq(watches.owner, owner), eq(watches.status, "active")));
const emailWatches = activeWatches.filter(w => {
const sources: string[] = JSON.parse(w.sourceTypes);
return sources.includes("email");
});
if (emailWatches.length === 0) {
console.log("handleIncomingEmail: no email watches active, skipping");
return;
}
// Get dismissal patterns for context
const watchIds = emailWatches.map(w => w.id);
const patterns = await db.select().from(dismissalPatterns)
.where(and(eq(dismissalPatterns.owner, owner), inArray(dismissalPatterns.watchId, watchIds)));
for (const email of params.messages) {
try {
// Deduplicate
const existing = await db.select().from(processedItems)
.where(and(eq(processedItems.owner, owner), eq(processedItems.uniqueId, email.messageId)))
.limit(1);
if (existing.length > 0) {
console.log("handleIncomingEmail: already processed", email.messageId);
continue;
}
console.log("handleIncomingEmail: processing email from", email.from, "subject:", email.subject);
const result = await sdk.callLLM(
matchEmailTemplate({
from: email.from,
subject: email.subject,
body: email.body || "(no body available)",
watches: emailWatches.map(w => ({
id: w.id,
description: w.description,
parsedTopics: w.parsedTopics,
})),
dismissalPatterns: patterns.length > 0
? patterns.map(p => ({ watchId: p.watchId, pattern: p.pattern }))
: null,
}),
Type.Object({
matches: Type.Array(Type.Object({
watchId: Type.Number(),
title: Type.String(),
snippet: Type.String(),
explanation: Type.String(),
confidence: Type.Optional(Type.String()),
fullContent: Type.Optional(Type.String()),
})),
}),
{ modelVariant: "STANDARD" }
);
// Record as processed (watchId set to null — email is checked against all watches)
await db.insert(processedItems).values({
owner,
uniqueId: email.messageId,
sourceType: "email",
watchId: null,
processedAt: now,
});
if (!result) {
console.log("handleIncomingEmail: LLM returned null for email", email.messageId);
continue;
}
// Create alerts for matches
for (const match of result.matches) {
const watchExists = emailWatches.find(w => w.id === match.watchId);
if (!watchExists) continue;
await db.insert(alerts).values({
owner,
watchId: match.watchId,
sourceType: "email",
title: match.title,
snippet: match.snippet,
explanation: match.explanation,
confidence: match.confidence || "medium",
sourceName: email.from,
fullContent: match.fullContent || null,
dismissed: false,
read: false,
createdAt: now,
});
console.log("handleIncomingEmail: created alert for watch", match.watchId, `(confidence: ${match.confidence || "medium"})`);
// Instant notification for urgent watches
if (watchExists.urgency === "instant") {
try {
await create_agent_post(sdk, {
shortMessage: match.title,
attachments: [{ type: "markdown", content: match.fullContent || `**${match.title}**\n\n${match.snippet}\n\n*Why:* ${match.explanation}\n\n*From:* ${email.from}` }],
duration: "read_once",
priority: "urgent",
});
} catch (err) {
console.error("handleIncomingEmail: failed to create post", err);
}
}
}
} catch (error) {
console.error("handleIncomingEmail: failed to process email", email.messageId, error);
continue;
}
}
},
});
// ─── MONITORING: NEWS & WEB (CRON) ─────────────────────────────
/** Shared type for matched articles returned by news/perplexity checks */
interface MatchedArticle {
title: string;
snippet: string;
explanation: string;
confidence: string;
url: string;
source: string;
enrichedContent: string | null;
}
interface NewsCheckResult {
matchedArticles: MatchedArticle[];
/** URLs of matched articles — only mark as processed after alert creation succeeds */
pendingProcessedUrls: string[];
}
async function checkNewsForWatch(
sdk: ServerSdk,
db: ReturnType<ServerSdk["db"]>,
watch: typeof watches.$inferSelect,
owner: string,
now: Date
): Promise<NewsCheckResult> {
const topics: string[] = JSON.parse(watch.parsedTopics);
if (topics.length === 0) return { matchedArticles: [], pendingProcessedUrls: [] };
// Get dismissal patterns and recent alerts for semantic dedup
const [patterns, recentAlertsList] = await Promise.all([
db.select().from(dismissalPatterns)
.where(and(eq(dismissalPatterns.owner, owner), eq(dismissalPatterns.watchId, watch.id))),
db.select().from(alerts)
.where(and(eq(alerts.watchId, watch.id), eq(alerts.owner, owner)))
.orderBy(desc(alerts.createdAt))
.limit(10),
]);
const recentAlertsForPrompt = recentAlertsList.length > 0
? recentAlertsList.map(a => ({
title: a.title,
snippet: a.snippet,
createdAt: dayjs(a.createdAt).tz(getUserTimeZone()).format("YYYY-MM-DD HH:mm"),
}))
: null;
// Generate search queries
let queries: string[];
try {
const queryResult = await sdk.callLLM(
generateQueriesTemplate({
watchDescription: watch.description,
watchTopics: JSON.stringify(topics),
}),
Type.Object({