-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.ts
More file actions
1641 lines (1505 loc) · 63.5 KB
/
Copy pathagent.ts
File metadata and controls
1641 lines (1505 loc) · 63.5 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
/**
* hn-monitor handler.
*
* cron tick
* → fetch Front Page, Show HN, and the last 24h of New HN
* → score stories against an agent-infrastructure interest profile
* → drop ones already posted (durable memory)
* → add concise "why it matters" notes with ctx.llm
* → post digest to Slack, Telegram, or both
*
* Slack mention / Telegram message / relay inbox DM
* → answer questions about recent findings, hydrating the matching HN
* story and top comments when the user asks for more detail
*
* Transport is configuration-driven. Set SLACK_CHANNEL, TELEGRAM_CHAT, or
* both — the handler delivers to whichever targets are configured. Uses
* @agentworkforce/delivery for unified messaging under the hood.
*/
import {
defineAgent,
isCronTickEvent,
isRelaycastMessageEvent,
type AgentEvent,
type WorkforceCtx
} from '@agentworkforce/runtime';
import {
createDelivery,
input,
list,
withTimeout,
fetchWithTimeout,
type DeliveryClient,
type DeliveryResult
} from '@agentworkforce/delivery';
import { slackClient } from '@relayfile/relay-helpers';
import {
readTelegramMessage,
skipReason as telegramSkipReason
} from '../shared/telegram.js';
export type HnFeed = 'front_page' | 'show_hn' | 'new';
export interface Story {
id: number;
title: string;
url: string;
points: number;
comments?: number;
author?: string;
createdAt?: string;
domain?: string;
feeds?: HnFeed[];
hnUrl?: string;
category?: string;
signals?: string[];
relevanceScore?: number;
}
export interface PostedStory extends Story {
rank: number;
why: string;
}
export interface PostRecord {
kind?: 'hn-monitor posted digest';
postedAt: string;
digest: string;
stories: PostedStory[];
threadRefs?: Array<{
provider: 'slack' | 'telegram';
draftRef: string;
channel?: string;
chatId?: string;
threadTs?: string;
}>;
}
interface RecentDigestState {
kind: 'hn-monitor exact recent digests';
version: 1;
updatedAt: string;
posts: PostRecord[];
}
interface ExactPostSaveResult {
applicable: boolean;
saved: boolean;
threadShardSaved: boolean;
indexSaved: boolean;
}
class ExactPostPersistenceError extends Error {
constructor() {
super('Slack digest posted, but deterministic HN grounding state could not be persisted');
this.name = 'ExactPostPersistenceError';
}
}
type QaGroundingSource = 'exact_state' | 'memory' | 'thread_context' | 'algolia' | 'none';
interface PendingThreadBody {
kind?: 'hn-monitor pending thread body';
cleared?: boolean;
/** Sorted, comma-separated targets for order-independent comparison. */
targets: string;
header: string;
body: string;
createdAt: string;
stories: PostedStory[];
/** Serialized DeliveryResult.refs from the header publish, for recovery.
* The `draftRef` field holds the relay path for Slack refs and the messageId
* for Telegram refs — see saveHeaderRefs() / rebuildHeaderRefs(). */
headerRefs: Array<{ provider: 'slack' | 'telegram'; draftRef: string; channel?: string; chatId?: string; threadTs?: string }>;
}
// ── message parsing ──────────────────────────────────────────────────────
interface ParsedMessage {
text: string;
provider: 'relay';
}
interface SlackMessage {
text: string;
channel?: string;
ts?: string;
threadTs?: string;
isBot: boolean;
}
function asRecord(v: unknown): Record<string, unknown> | null {
return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
}
function str(v: unknown): string | undefined {
if (typeof v === 'string' && v.length > 0) return v;
if (typeof v === 'number') return String(v);
return undefined;
}
function parseRelayMessage(event: { data?: unknown }): ParsedMessage | null {
const data = asRecord(event.data);
if (!data) return null;
const nested = (data.message && typeof data.message === 'object' ? data.message : {}) as Record<string, unknown>;
const text = str(data.text) ?? str(nested.text) ?? '';
if (!text.trim()) return null;
return { text: text.trim(), provider: 'relay' };
}
function parseSlackMessage(expanded: unknown): SlackMessage {
const root = asRecord(expanded);
const data = asRecord(root?.data) ?? root ?? {};
const nested = asRecord(data.message) ?? asRecord(data.event) ?? data;
return {
text: (str(nested.text) ?? str(data.text) ?? '').replace(/<@[A-Z0-9]+(?:\|[^>]+)?>/giu, ' ').replace(/\s+/gu, ' ').trim(),
channel: str(nested.channel) ?? str(nested.channel_id) ?? str(data.channel),
ts: str(nested.ts) ?? str(nested.event_ts) ?? str(data.ts),
threadTs: str(nested.thread_ts) ?? str(data.thread_ts),
isBot: Boolean(nested.bot_id) || nested.subtype === 'bot_message'
};
}
/**
* Best-effort: resolve the agent that sent an inbound relay DM, so we can reply
* to them over the relay. The sender rides on the event's summary `actor` (cloud
* envelope-builder normalizes relaycast `from` → `summary.actor`); we also probe
* the full payload's `from`/`actor` as a fallback. Returns the agent ref (name
* or id) or undefined when it can't be determined (caller then falls back to
* Slack/Telegram). The exact field path is verified against the live relay.
*/
async function resolveRelaySender(event: AgentEvent, expandedFull: unknown): Promise<string | undefined> {
// The cloud envelope-builder normalizes the relaycast `from` to the event's
// summary `actor` (`{ summary: { actor: { id, displayName } } }`), present
// directly on the event and via `expand('summary')`. Probe those first; fall
// back to the ALREADY-resolved full payload's `from`/`actor` (passed in to
// avoid a redundant expand round-trip).
const actorFrom = (obj: unknown): Record<string, unknown> | undefined => {
const r = asRecord(obj);
if (!r) return undefined;
return (
asRecord(r.actor) ??
asRecord(asRecord(r.summary)?.actor) ??
asRecord(asRecord(r.data)?.actor) ??
asRecord(asRecord(r.data)?.from) ??
asRecord(r.from) ??
undefined
);
};
const actor =
actorFrom((event as { summary?: unknown }).summary) ??
actorFrom(await event.expand('summary').catch(() => undefined)) ??
actorFrom(expandedFull);
return str(actor?.id) ?? str(actor?.name) ?? str(actor?.displayName);
}
// ── agent definition ─────────────────────────────────────────────────────
export default defineAgent({
schedules: [{ name: 'scan', cron: '0 9,17 * * *', tz: 'America/New_York' }],
triggers: {
// `on: 'app_mention'` never actually routes: the cloud's integration-watch
// matcher hard-excludes app_mention from generic resource matching
// (relayfileTriggerMatchesEvent short-circuits false for it), and Slack
// mentions inside an existing thread arrive to the webhook as a plain
// `message.created` event, not a literal `app_mention` eventType. Match on
// the Relayfile trigger + `@mention` text gate instead (same fix joke-bot
// already applies).
slack: [{ on: 'message.created', paths: ['/slack/channels/${SLACK_CHANNEL}/**'], match: '@mention' }],
telegram: [{ on: 'message' }]
},
handler: async (ctx, event) => {
// Q&A path: relay inbox DM
if (isRelaycastMessageEvent(event as unknown as AgentEvent)) {
await handleQaMessage(ctx, event as unknown as AgentEvent, 'relay');
return;
}
// Q&A path: telegram message
if (typeof event.type === 'string' && event.type.startsWith('telegram.')) {
await handleQaMessage(ctx, event as unknown as AgentEvent, 'telegram');
return;
}
// Q&A path: a Slack @mention, usually in a digest thread.
if (typeof event.type === 'string' && event.type.startsWith('slack.')) {
await handleQaMessage(ctx, event as unknown as AgentEvent, 'slack');
return;
}
// Cron path
if (!isCronTickEvent(event as unknown as AgentEvent)) return;
const delivery = createDelivery(ctx);
if (delivery.targets.length === 0) {
ctx.log('warn', 'hn-monitor.no-targets', { reason: 'neither SLACK_CHANNEL nor TELEGRAM_CHAT configured' });
return;
}
// Pending thread body recovery — if a previous run posted the header but
// the threaded body failed, retry it before processing new stories.
if (await retryPendingThreadBody(ctx, delivery)) return;
const topics = list(input(ctx, 'TOPICS'));
const lookbackHours = boundedPositiveInt(input(ctx, 'LOOKBACK_HOURS') ?? '24', 'LOOKBACK_HOURS', 72);
const maxStories = boundedPositiveInt(input(ctx, 'MAX_STORIES') ?? '8', 'MAX_STORIES', 20);
const stories = await fetchHackerNewsFeeds(lookbackHours);
const feedCounts = countFeeds(stories);
ctx.log(
'info',
`hn-monitor.feed-scan front_page=${feedCounts.front_page} show_hn=${feedCounts.show_hn} new=${feedCounts.new}`,
{ stories: stories.length, lookbackHours }
);
const matches = selectRelevantStories(stories, topics, maxStories);
ctx.log('info', `hn-monitor.matched-agentic matched=${matches.length}`, { matched: matches.length, candidates: stories.length });
const seen = await loadSeen(ctx);
const fresh = matches.filter((s) => !seen.includes(s.id));
ctx.log('info', `hn-monitor.fresh fresh=${fresh.length}`, { fresh: fresh.length });
if (fresh.length === 0) {
ctx.log('info', 'hn-monitor.nothing-new', { matched: matches.length });
return;
}
await postFreshStories(ctx, delivery, seen, fresh);
}
});
// ── Q&A handler ──────────────────────────────────────────────────────────
export async function handleQaMessage(
ctx: WorkforceCtx,
event: AgentEvent,
provider: 'slack' | 'telegram' | 'relay',
deps: {
complete?: (prompt: string) => Promise<string>;
fetchDetails?: (storyId: number) => Promise<HnStoryDetails | null>;
searchByTitle?: (question: string) => Promise<PostedStory | null>;
loadExactPosts?: (threadTs?: string) => Promise<PostRecord[]>;
loadThreadContext?: (expanded: unknown) => Promise<string>;
slackReply?: (channel: string, threadTs: string, text: string) => Promise<unknown>;
/** Inject a delivery client for testing (avoids real writeback). */
delivery?: DeliveryClient;
} = {}
): Promise<void> {
const expanded = await event.expand('full').catch(() => undefined);
if (!expanded) return;
let question: string | null = null;
let slackMessage: SlackMessage | null = null;
if (provider === 'slack') {
slackMessage = parseSlackMessage(expanded);
if (slackMessage.isBot || !slackMessage.text || !slackMessage.channel || !(slackMessage.threadTs || slackMessage.ts)) {
ctx.log('info', 'hn-monitor.qa.skip', { reason: 'unusable Slack mention' });
return;
}
question = slackMessage.text;
} else if (provider === 'telegram') {
const payload = expanded as { data?: unknown };
if (!payload.data) return;
const msg = readTelegramMessage(payload.data);
if (!msg) return;
// Gate: skip bot echoes, wrong chat, empty text
const reason = telegramSkipReason(msg, input(ctx, 'TELEGRAM_CHAT'));
if (reason) {
ctx.log('info', `hn-monitor.qa.skip reason=${reason.replace(/\s+/g, '-')}`);
return;
}
question = msg.text.trim();
} else {
// relay inbox DM
const parsed = parseRelayMessage(expanded as { data?: unknown });
if (!parsed) {
ctx.log('info', 'hn-monitor.qa.skip', { reason: 'unparseable relay message' });
return;
}
question = parsed.text;
}
if (!question) return;
const [exactPosts, memoryPosts, threadContext] = await Promise.all([
(deps.loadExactPosts ?? ((threadTs?: string) => loadExactPosts(ctx, threadTs)))(
provider === 'slack' ? slackMessage?.threadTs ?? slackMessage?.ts : undefined
).catch(() => []),
loadPosts(ctx).catch(() => []),
(deps.loadThreadContext ?? ((value: unknown) => loadSlackThreadContext(ctx, value)))(expanded).catch(() => '')
]);
const posts = mergePosts(exactPosts, memoryPosts);
ctx.log('info', 'hn-monitor.qa.recalled', {
posts: posts.length,
exactPosts: exactPosts.length,
memoryPosts: memoryPosts.length,
threadContext: Boolean(threadContext)
});
let source: QaGroundingSource = 'none';
const ordinal = ordinalFromQuestion(question);
const threadPost = findThreadPost(posts, expanded, threadContext);
let selectedStories: PostedStory[] = [];
if (ordinal !== undefined) {
const safeOrdinalPost = threadPost ?? (posts.length === 1 ? posts[0] : undefined);
if (safeOrdinalPost) {
selectedStories = selectQuestionStories(question, [safeOrdinalPost]).slice(0, 2);
if (selectedStories.length > 0) {
source = postGroupContains(exactPosts, safeOrdinalPost) ? 'exact_state' : 'memory';
}
}
} else {
if (threadPost) {
selectedStories = selectQuestionStories(`${question}\n${threadContext}`, [threadPost]).slice(0, 2);
if (selectedStories.length > 0) {
source = 'thread_context';
}
}
if (selectedStories.length === 0) selectedStories = selectQuestionStories(question, exactPosts).slice(0, 2);
if (selectedStories.length > 0) {
if (source === 'none') source = 'exact_state';
} else if (exactPosts.length === 0) {
selectedStories = selectQuestionStories(question, memoryPosts).slice(0, 2);
if (selectedStories.length > 0) source = 'memory';
}
}
if (selectedStories.length === 0 && threadContext && ordinal === undefined) {
selectedStories = selectQuestionStories(`${question}\n${threadContext}`, posts).slice(0, 2);
if (selectedStories.length > 0) source = 'thread_context';
}
if (selectedStories.length === 0) {
const lookup = await (deps.searchByTitle ?? findStoryByExactTitle)(question).catch(() => null);
if (lookup) {
selectedStories = [lookup];
source = 'algolia';
}
}
ctx.log('info', 'hn-monitor.qa.selected', {
source,
selected: selectedStories.map((story) => ({ id: story.id, title: story.title }))
});
const detailsLoader = deps.fetchDetails ?? fetchStoryDetails;
const details = (
await Promise.all(selectedStories.map((story) => detailsLoader(story.id).catch(() => null)))
).filter((item): item is HnStoryDetails => item !== null);
ctx.log('info', 'hn-monitor.qa.hydrated', {
source,
selected: selectedStories.map((story) => story.id),
hydrated: details.length
});
const lookupPost: PostRecord[] = source === 'algolia' && selectedStories[0]
? [{
postedAt: new Date().toISOString(),
digest: `Live exact-title HN lookup: ${selectedStories[0].title}\nArticle: ${selectedStories[0].url}\nHN discussion: ${selectedStories[0].hnUrl}`,
stories: selectedStories
}]
: [];
const groundingPosts = mergePosts(lookupPost, posts);
const context = groundingPosts.length
? groundingPosts.slice(0, 12).map((p) => `### Posted ${p.postedAt ?? 'Unknown'}\n${p.digest ?? ''}`).join('\n\n')
: 'No Hacker News digests have been posted yet.';
const liveContext = details.length
? details.map(renderStoryDetailsForPrompt).join('\n\n')
: 'No matching story needed live hydration, or the HN detail endpoint had no additional data.';
const prompt = [
"You are the conversational Hacker News radar for an engineering team building agent infrastructure.",
'Answer using ONLY the recently posted digests and live HN details below.',
`The selected story grounding source is ${source}.`,
source === 'algolia'
? 'Say briefly that you matched the supplied title with a live HN title lookup; do not imply it came from recalled digest memory.'
: '',
'When live comments are provided, describe them as HN community reactions, not as verified facts.',
'If the evidence does not cover the question or the referenced story is ambiguous, say so and ask for the story number/title.',
'Be concise, specific, and include the article and HN discussion links when they help.',
provider === 'slack' ? 'Use concise Slack mrkdwn; no markdown headings.' : 'Use concise chat-friendly formatting.',
'',
'## Recently posted digests (most recent ~30 days)',
context,
'',
'## Live HN story details and top comments',
liveContext,
'',
'## Slack thread parent context (may be empty)',
threadContext || '(No thread parent text was available.)',
'',
'## User question',
question
].join('\n');
const complete = deps.complete ?? ((p: string) => ctx.llm.complete(p, { maxTokens: 1024 }));
let answer: string;
try {
answer = await withTimeout(complete(prompt), 45_000, 'ctx.llm.complete');
} catch (error) {
ctx.log('warn', 'hn-monitor.qa.llm-fallback', { error: String(error) });
const titles = dedupePostedStories(selectedStories)
.slice(0, 15)
.map((story) => [
`- ${story.title ?? 'Untitled'}`,
` Article: ${story.url ?? story.hnUrl ?? ''}`,
` HN discussion: ${story.hnUrl ?? `https://news.ycombinator.com/item?id=${story.id}`}`
].join('\n'))
.join('\n');
answer = titles
? `I found the grounded HN story, but couldn't generate the full answer right now:\n${titles}`
: "I couldn't generate an answer right now, and I couldn't resolve a single grounded HN story from that question. Please specify the story number or exact title.";
}
const reply = answer.trim() || 'No answer available.';
if (provider === 'slack' && slackMessage?.channel) {
const threadTs = slackMessage.threadTs ?? slackMessage.ts;
if (!threadTs) return;
const replyFn = deps.slackReply ?? ((channel: string, ts: string, text: string) =>
slackClient({ writebackTimeoutMs: 0 }).reply(channel, ts, text));
await replyFn(slackMessage.channel, threadTs, reply);
ctx.log('info', 'hn-monitor.qa.slack-replied', { channel: slackMessage.channel, threadTs });
return;
}
// Relay DMs: reply over the relay to whoever DM'd us (agent-to-agent
// round-trip) when we can resolve the sender. Falls back to Slack/Telegram
// delivery below when the sender can't be determined, so there's no regression.
if (provider === 'relay' && ctx.relay) {
const sender = await resolveRelaySender(event, expanded);
if (sender) {
try {
const res = await ctx.relay.dm(sender, reply);
if (res.ok) {
ctx.log('info', 'hn-monitor.qa.relay-replied', { to: sender });
return;
}
ctx.log('warn', 'hn-monitor.qa.relay-reply-no-receipt', { to: sender });
} catch (error) {
ctx.log('warn', 'hn-monitor.qa.relay-reply-failed', { to: sender, error: String(error) });
}
// fall through to transport delivery on failure
}
}
// Reply only to the origin transport so questions don't mirror everywhere.
const delivery = deps.delivery ?? createDelivery(ctx);
if (delivery.targets.length > 0) {
if (provider === 'relay') {
// Fallback: relay sender unresolved — reply to Slack if configured (legacy
// behavior), else Telegram.
const nonRelayTargets = delivery.targets.filter((t): t is 'slack' | 'telegram' => t === 'slack' || t === 'telegram');
const targets: Array<'slack' | 'telegram'> = nonRelayTargets.includes('slack') ? ['slack'] : nonRelayTargets;
// When using injected mock, just publish directly (target filtering is
// the test's responsibility). When using real client, scope to targets.
const scoped = deps.delivery
? delivery
: createDelivery(ctx, undefined, targets);
await scoped.publish(reply);
} else if (provider === 'telegram') {
// Telegram Q&A: reply ONLY to Telegram.
const scoped = deps.delivery
? delivery
: createDelivery(ctx, undefined, [provider]);
await scoped.publish(answer.trim() || 'No answer available.');
}
}
}
// ── posting ──────────────────────────────────────────────────────────────
export async function postFreshStories(
ctx: WorkforceCtx,
delivery: DeliveryClient,
seen: number[],
fresh: Story[]
): Promise<void> {
// Claim the stories as seen BEFORE the post. Cron delivery is at-least-once:
// a single tick can re-invoke this handler (cloud re-runs a delivery whose
// lease expires before it reports done). Claiming first means a concurrent
// re-invocation loads these ids as already-seen and stays silent.
await saveSeen(ctx, [...seen, ...fresh.map((s) => s.id)].slice(-200));
let headerPosted = false;
let pending: PendingThreadBody | null = null;
try {
ctx.log('info', 'hn-monitor.summarizing', { fresh: fresh.length });
const { header, body, stories } = await summarize(ctx, fresh);
ctx.log('info', 'hn-monitor.posting', { targets: delivery.targets });
// Wait for the header receipt so its delivered Slack thread timestamp can
// be persisted for deterministic ordinal Q&A in older digest threads. The
// much larger body remains non-blocking and uses the returned draft ref.
const heads = ctx.sandbox?.cwd === '/simulated'
? await delivery.publish(header)
: await delivery.send(header);
if (heads.refs.length === 0) {
throw new Error(`Header publish failed across all targets`);
}
headerPosted = true;
if (heads.refs.length < delivery.targets.length) {
throw new Error(`Header published on only ${heads.refs.length}/${delivery.targets.length} targets`);
}
ctx.log('info', 'hn-monitor.header-published', { refs: heads.refs.length });
// Build pending state BEFORE sending the body, so even if delivery.send()
// throws (hard failure, not just ok:false), the catch block can save state
// for recovery on the next cron tick.
const pendingBase = {
targets: [...delivery.targets].sort().join(','),
header,
body,
createdAt: new Date().toISOString(),
stories,
headerRefs: saveHeaderRefs(heads)
};
// Thread the body under each header, also non-blocking.
const bodyResult = await delivery.send(body, { replyTo: heads, nonBlocking: true });
// In non-blocking mode, ok=true means at least one target got a draft ref.
// Check that ALL attempted targets received refs — if any were lost, treat
// as partial failure so the pending-recovery path saves state for retry.
if (!bodyResult.ok || bodyResult.refs.length < delivery.targets.length) {
pending = pendingBase;
throw new Error(`Threaded body failed on some targets`);
}
ctx.log('info', 'hn-monitor.posted', { targets: delivery.targets.join(',') });
// Retain the digest for Q&A recall (~30 day rolling window via memory ttl).
const exactStateSaved = await savePost(ctx, {
postedAt: new Date().toISOString(),
digest: `${header}\n${body}`,
stories,
threadRefs: saveHeaderRefs(heads)
});
if (!exactStateSaved) throw new ExactPostPersistenceError();
} catch (err) {
if (!headerPosted) {
// Nothing landed yet — release the provisional claim so the next tick
// retries this digest, then rethrow.
await saveSeen(ctx, seen).catch(() => {});
throw err;
}
if (pending) {
await savePendingThreadBody(ctx, pending)
.catch((error) => ctx.log('error', 'hn-monitor.pending-save-failed', { error: String(error) }));
}
if (err instanceof ExactPostPersistenceError) {
ctx.log('error', 'hn-monitor.post-grounding-persistence-failed', { error: err.message });
throw err;
}
// The header already posted; releasing + rethrowing would duplicate it on
// the runtime's retry. Keep the claim and let the next scan retry the body.
ctx.log('error', 'hn-monitor.thread-incomplete', { error: err instanceof Error ? err.message : String(err) });
}
}
/** Serialize DeliveryResult.refs into storable headerRefs. */
function saveHeaderRefs(result: DeliveryResult): PendingThreadBody['headerRefs'] {
return result.refs
.filter(
(r): r is import('@agentworkforce/delivery').SlackRef | import('@agentworkforce/delivery').TelegramRef =>
r.provider === 'slack' || r.provider === 'telegram'
)
.map((r) => ({
provider: r.provider,
// For Slack: draftRef is the relay path (parentRef). For Telegram:
// store the messageId in draftRef so recovery can reconstruct threading.
draftRef: 'draftRef' in r ? r.draftRef : r.messageId,
channel: r.provider === 'slack' ? r.channel : undefined,
chatId: r.provider === 'telegram' ? r.chatId : undefined,
threadTs: r.provider === 'slack' ? r.ts : undefined
}));
}
// ── pending thread body recovery ─────────────────────────────────────────
export async function retryPendingThreadBody(
ctx: WorkforceCtx,
delivery: DeliveryClient
): Promise<boolean> {
const pending = await loadPendingThreadBody(ctx);
if (!pending) return false;
// Compare targets with canonical ordering to avoid order-dependent mismatch.
const configuredTargets = [...delivery.targets].sort().join(',');
if (pending.targets !== configuredTargets) {
// Targets changed since the body was saved — clean up the stale record
// so it doesn't sit in memory until TTL expiry.
await clearPendingThreadBody(ctx).catch(() => {});
return false;
}
// Reconstruct replyTo from saved headerRefs for proper threading on retry.
const bodyOpts = pending.headerRefs?.length
? {
nonBlocking: true as const,
replyTo: {
ok: true,
refs: rebuildHeaderRefs(pending.headerRefs)
}
}
: { nonBlocking: true as const };
const bodyResult = await delivery.send(pending.body, bodyOpts);
// Match postFreshStories: ALL targets must receive refs for success.
if (!bodyResult.ok || bodyResult.refs.length < delivery.targets.length) {
ctx.log('error', 'hn-monitor.pending-body-retry-failed', { targets: configuredTargets });
return true;
}
const exactStateSaved = await savePost(ctx, {
postedAt: new Date().toISOString(),
digest: `${pending.header}\n${pending.body}`,
stories: pending.stories,
threadRefs: pending.headerRefs
});
if (!exactStateSaved) {
ctx.log('error', 'hn-monitor.post-grounding-persistence-failed', { recovery: true });
throw new ExactPostPersistenceError();
}
await clearPendingThreadBody(ctx);
ctx.log('info', 'hn-monitor.pending-body-posted', { targets: configuredTargets });
return true;
}
/** Reconstruct MessageRefs from stored headerRefs, with correct threading ids. */
function rebuildHeaderRefs(
stored: PendingThreadBody['headerRefs']
): Array<import('@agentworkforce/delivery').MessageRef> {
return stored.map((r) => {
if (r.provider === 'telegram') {
// For Telegram, draftRef stores the original messageId — use it for
// reply_to_message_id threading on retry.
return {
provider: 'telegram' as const,
chatId: r.chatId ?? '',
messageId: r.draftRef
};
}
return {
provider: 'slack' as const,
channel: r.channel ?? '',
ts: r.threadTs ?? '',
draftRef: r.draftRef
};
});
}
// ── HN fetching ──────────────────────────────────────────────────────────
interface HnHit {
objectID?: string;
title?: string | null;
url?: string | null;
points?: number | null;
num_comments?: number | null;
author?: string | null;
created_at?: string | null;
}
interface SignalGroup {
category: string;
patterns: RegExp[];
}
const SIGNAL_GROUPS: SignalGroup[] = [
{
category: 'Agent coordination',
patterns: [
/\bmulti[- ]agent\b/iu,
/\bagent(?:ic)? (?:orchestrat(?:ion|or)|coordination|communication|messaging|handoff|delegation|team|swarm)\b/iu,
/\b(?:agents? (?:talking|collaborating)|agent[- ]to[- ]agent|\bA2A\b|shared context)\b/iu
]
},
{
category: 'Coding agents',
patterns: [
/\b(?:AI |autonomous )?coding agents?\b/iu,
/\b(?:Claude Code|OpenAI Codex|Codex CLI|Cursor|Devin|OpenHands|SWE[- ]agent|SWE[- ]bench)\b/iu,
/\b(?:software|code) factor(?:y|ies)\b/iu,
/\bagent(?:ic)? (?:code review|software development|coding workflow)\b/iu
]
},
{
category: 'Agent infrastructure',
patterns: [
/\bagent(?:ic)? (?:runtime|infrastructure|platform|framework|protocol|sandbox|memory|context|harness|tooling|observability)\b/iu,
/\b(?:Model Context Protocol|MCP server|MCP client|MCP tools?)\b/iu,
/\b(?:tool calling|computer use|browser use)\b.*\b(?:agent|LLM|model)\b/iu,
/\b(?:agent|LLM|model)\b.*\b(?:tool calling|computer use|browser use)\b/iu
]
},
{
category: 'Agent workflows',
patterns: [
/\bagent(?:ic)? (?:workflow|loop|pipeline|automation)\b/iu,
/\b(?:background|long[- ]running|headless|autonomous|proactive) agents?\b/iu,
/\b(?:ReAct|agent loop|agent factory|AI factory)\b/iu
]
},
{
category: 'Agent Relay ecosystem',
patterns: [
/\b(?:Agent Relay|AgentWorkforce|Relayfile|Relaycast|Relayauth|Relaycron)\b/iu,
/\bheadless Slack for agents\b/iu
]
}
];
const GENERIC_AGENT_RE = /\b(?:AI agents?|LLM agents?|agentic|agents?)\b/iu;
const TECH_CONTEXT_RE = /\b(?:AI|LLM|model|code|coding|developer|software|workflow|runtime|tool|memory|context|browser|terminal|computer|autonomous|inference|open source|API|protocol)\b/iu;
const FALSE_POSITIVE_RE = /\b(?:travel|insurance|real estate|estate|sports|talent|literary|booking|border patrol) agents?\b/iu;
const WEAK_CUSTOM_TOPICS = new Set(['ai', 'agent', 'agents', 'agentic', 'typescript', 'developer tools', 'devtools', 'software']);
export async function fetchHackerNewsFeeds(lookbackHours = 24): Promise<Story[]> {
const cutoff = Math.floor((Date.now() - lookbackHours * 60 * 60 * 1000) / 1000);
const urls: Array<{ feed: HnFeed; url: string }> = [
{
feed: 'front_page',
url: 'https://hn.algolia.com/api/v1/search?tags=front_page&hitsPerPage=100'
},
{
feed: 'show_hn',
url: `https://hn.algolia.com/api/v1/search_by_date?tags=show_hn&hitsPerPage=250&numericFilters=created_at_i%3E${cutoff}`
},
{
feed: 'new',
url: `https://hn.algolia.com/api/v1/search_by_date?tags=story&hitsPerPage=1000&numericFilters=created_at_i%3E${cutoff}`
}
];
const batches = await Promise.all(urls.map(({ feed, url }) => fetchFeed(url, feed)));
const merged = new Map<number, Story>();
for (const story of batches.flat()) {
const prior = merged.get(story.id);
if (!prior) {
merged.set(story.id, story);
continue;
}
merged.set(story.id, {
...prior,
...story,
points: Math.max(prior.points, story.points),
comments: Math.max(prior.comments ?? 0, story.comments ?? 0),
feeds: [...new Set([...(prior.feeds ?? []), ...(story.feeds ?? [])])]
});
}
return [...merged.values()];
}
async function fetchFeed(url: string, feed: HnFeed): Promise<Story[]> {
const res = await fetchWithTimeout(url, {}, 8_000);
if (!res?.ok) return [];
try {
const payload = (await res.json()) as { hits?: HnHit[] };
return (payload.hits ?? []).map((hit) => storyFromHit(hit, feed)).filter((story): story is Story => story !== null);
} catch {
return [];
}
}
function storyFromHit(hit: HnHit, feed: HnFeed): Story | null {
const id = Number(hit.objectID);
const title = hit.title?.trim();
if (!Number.isSafeInteger(id) || id <= 0 || !title) return null;
const hnUrl = `https://news.ycombinator.com/item?id=${id}`;
const url = hit.url?.trim() || hnUrl;
return {
id,
title,
url,
hnUrl,
points: nonNegativeInt(hit.points),
comments: nonNegativeInt(hit.num_comments),
author: hit.author?.trim() || undefined,
createdAt: hit.created_at?.trim() || undefined,
domain: safeDomain(url),
feeds: [feed]
};
}
export function selectRelevantStories(stories: Story[], topics: string[], maxStories = 8): Story[] {
const customTopics = topics.map((topic) => topic.trim().toLowerCase()).filter(Boolean);
return stories
.map((story) => scoreStory(story, customTopics))
.filter((story) => (story.relevanceScore ?? 0) >= 4)
.sort((a, b) => rankScore(b) - rankScore(a) || b.id - a.id)
.slice(0, maxStories);
}
function scoreStory(story: Story, customTopics: string[]): Story {
const title = story.title;
const signals: string[] = [];
let relevanceScore = 0;
let category = '';
for (const group of SIGNAL_GROUPS) {
const matched = group.patterns.some((pattern) => pattern.test(title));
if (!matched) continue;
signals.push(group.category);
if (!category) {
category = group.category;
relevanceScore += group.category === 'Agent Relay ecosystem' ? 8 : 5;
} else {
relevanceScore += 2;
}
}
if (GENERIC_AGENT_RE.test(title) && TECH_CONTEXT_RE.test(title)) {
relevanceScore += 4;
if (!category) category = 'Agent ecosystem';
signals.push('agent + technical context');
}
const lower = title.toLowerCase();
for (const topic of customTopics) {
if (!lower.includes(topic)) continue;
if (!WEAK_CUSTOM_TOPICS.has(topic)) {
relevanceScore += GENERIC_AGENT_RE.test(title) || /\b(?:mcp|codex|claude code|cursor|devin|openhands)\b/iu.test(topic) ? 3 : 1;
signals.push(`topic:${topic}`);
} else if (GENERIC_AGENT_RE.test(title)) {
relevanceScore += 1;
}
}
if (FALSE_POSITIVE_RE.test(title) && !TECH_CONTEXT_RE.test(title)) relevanceScore = 0;
return {
...story,
category: category || 'Agent ecosystem',
signals: [...new Set(signals)],
relevanceScore
};
}
function rankScore(story: Story): number {
const engagement = Math.log2(2 + story.points + (story.comments ?? 0) * 2) * 8;
const sourceBoost = (story.feeds?.includes('front_page') ? 18 : 0) + (story.feeds?.includes('show_hn') ? 8 : 0);
const createdAtMs = story.createdAt ? Date.parse(story.createdAt) : Number.NaN;
const ageHours = Number.isFinite(createdAtMs) ? Math.max(0, (Date.now() - createdAtMs) / 3_600_000) : 24;
const recency = Math.max(0, 24 - ageHours) / 3;
return (story.relevanceScore ?? 0) * 100 + engagement + sourceBoost + recency;
}
function countFeeds(stories: Story[]): Record<HnFeed, number> {
return {
front_page: stories.filter((story) => story.feeds?.includes('front_page')).length,
show_hn: stories.filter((story) => story.feeds?.includes('show_hn')).length,
new: stories.filter((story) => story.feeds?.includes('new')).length
};
}
// ── summarization ────────────────────────────────────────────────────────
interface DigestNotes {
theme: string;
whyById: Map<number, string>;
}
async function summarize(ctx: WorkforceCtx, stories: Story[]): Promise<{ header: string; body: string; stories: PostedStory[] }> {
const storyData = stories.map((story) => ({
id: story.id,
title: story.title,
category: story.category,
points: story.points,
comments: story.comments ?? 0,
feeds: story.feeds ?? [],
url: story.url,
hnUrl: story.hnUrl
}));
let notes: DigestNotes = { theme: fallbackTheme(stories), whyById: new Map() };
try {
const output = await withTimeout(
ctx.llm.complete(
[
'You are curating Hacker News for the Agent Relay team, which builds agent messaging, multi-agent orchestration, agent runtimes, cloud sandboxes, coding-agent workflows, and developer infrastructure.',
'Return ONLY compact JSON with this shape:',
'{"theme":"one specific sentence about the batch","stories":[{"id":123,"why":"one specific sentence, <= 160 characters"}]}',
'Keep every supplied story. Explain why each matters to builders of agentic developer tools; avoid generic hype and do not invent facts beyond the title/metadata.',
'',
JSON.stringify(storyData)
].join('\n'),
{ maxTokens: 900 }
),
45_000,
'ctx.llm.complete'
);
notes = parseDigestNotes(output, stories);
} catch (error) {
ctx.log('warn', 'hn-monitor.llm-fallback', { error: String(error) });
}
return renderDigest(stories, notes);
}
function parseDigestNotes(output: string, stories: Story[]): DigestNotes {
const json = output.match(/\{[\s\S]*\}/u)?.[0] ?? output;
try {
const parsed = JSON.parse(json) as { theme?: unknown; stories?: Array<{ id?: unknown; why?: unknown }> };
const whyById = new Map<number, string>();
for (const item of parsed.stories ?? []) {
const id = Number(item.id);
if (!stories.some((story) => story.id === id) || typeof item.why !== 'string' || !item.why.trim()) continue;
whyById.set(id, truncate(oneLine(item.why), 180));
}
return {
theme: typeof parsed.theme === 'string' && parsed.theme.trim()
? truncate(oneLine(parsed.theme), 220)
: fallbackTheme(stories),
whyById
};
} catch {
return { theme: fallbackTheme(stories), whyById: new Map() };
}
}
export function renderDigest(
stories: Story[],
notes: { theme: string; whyById: Map<number, string> }
): { header: string; body: string; stories: PostedStory[] } {
const feeds = countFeeds(stories);
const feedSummary = [
feeds.front_page ? `${feeds.front_page} Front Page` : '',
feeds.show_hn ? `${feeds.show_hn} Show HN` : '',
feeds.new ? `${feeds.new} New` : ''
].filter(Boolean).join(' · ');
const noun = stories.length === 1 ? 'signal' : 'signals';
const header = [
`:satellite_antenna: *HN agentic radar — ${stories.length} fresh ${noun}*`,
`_${feedSummary || 'Agent infrastructure and developer tooling'} · Details in thread._`
].join('\n');
const postedStories: PostedStory[] = stories.map((story, index) => ({
...story,
rank: index + 1,
why: notes.whyById.get(story.id) ?? fallbackWhy(story)
}));
const lines = [`*:mag: What stands out*`, `_${escapeSlack(notes.theme)}_`];
for (const story of postedStories) {
const category = (story.category ?? 'Agent ecosystem').toUpperCase();
const metrics = [
`▲ ${story.points} points`,
`${story.comments ?? 0} comments`,
feedLabels(story.feeds)
].filter(Boolean).join(' · ');
const article = slackLink(story.url, story.title);
const hnUrl = story.hnUrl ?? `https://news.ycombinator.com/item?id=${story.id}`;
lines.push(
'',
`*${story.rank} · ${article}*`,
`\`${escapeSlack(category)}\` ${metrics}`,
escapeSlack(story.why),
`${slackLink(hnUrl, 'HN discussion')}${story.domain ? ` · ${escapeSlack(story.domain)}` : ''}`
);
}
lines.push('', '_Want the deeper read? Reply in this thread and @mention me with a story number or title for live details and top HN comments._');
return { header, body: lines.join('\n'), stories: postedStories };
}
function fallbackTheme(stories: Story[]): string {
const categories = [...new Set(stories.map((story) => story.category).filter(Boolean))];
return categories.length > 0
? `Fresh signals across ${categories.slice(0, 3).join(', ').toLowerCase()}.`
: 'Fresh signals for teams building agentic software and developer infrastructure.';
}
function fallbackWhy(story: Story): string {
const category = (story.category ?? 'agent ecosystem').toLowerCase();
return `Worth tracking for ${category}; open the article and HN thread for the implementation details and community reaction.`;