-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocalbuddy_main.ts
More file actions
1070 lines (961 loc) · 36.9 KB
/
localbuddy_main.ts
File metadata and controls
1070 lines (961 loc) · 36.9 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
#!/usr/bin/env bun
/**
* PushPals LocalBuddy - HTTP Server
*
* Usage:
* bun run localbuddy --server http://localhost:3001 [--port 3003] [--sessionId <id>]
*
* Accepts messages from clients via HTTP.
* - Lightweight chat can be answered directly by LocalBuddy.
* - Requests can be explicitly routed to RemoteBuddy via `/ask_remote_buddy ...`.
* - Routed requests are enqueued immediately; RemoteBuddy handles deeper planning/context.
*/
import { randomUUID } from "crypto";
import {
CommunicationManager,
detectRepoRoot,
loadPromptTemplate,
loadPushPalsConfig,
} from "shared";
import { createLLMClient, type LLMClient } from "../../remotebuddy/src/llm.js";
import {
buildJobStatusReply,
buildRequestStatusReply,
extractReferencedJobToken,
isStatusLookupPrompt,
type JobApiRow,
type JobLogApiRow,
type RequestApiRow,
} from "./request_status.js";
import { answerLocalReadonlyQuery, isLocalReadonlyQueryPrompt } from "./local_readonly.js";
// ─── CLI args ───────────────────────────────────────────────────────────────
const CONFIG = loadPushPalsConfig();
function parseArgs(): {
server: string;
port: number;
sessionId: string;
authToken: string | null;
} {
const args = process.argv.slice(2);
let server = CONFIG.server.url;
let port = CONFIG.localbuddy.port;
let sessionId = CONFIG.sessionId;
let authToken = CONFIG.authToken;
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case "--server":
server = args[++i];
break;
case "--port":
port = parseInt(args[++i], 10);
break;
case "--sessionId":
sessionId = args[++i];
break;
case "--token":
authToken = args[++i];
break;
}
}
return { server, port, sessionId, authToken };
}
function parseStatusHeartbeatMs(fallbackMs: number): number {
const parsed = Math.floor(fallbackMs);
if (!Number.isFinite(parsed)) return 120_000;
if (parsed <= 0) return 0;
return Math.max(30_000, parsed);
}
function summarizeFailureForPrompt(value: unknown): string {
const text = String(value ?? "")
.replace(/\s+/g, " ")
.trim();
if (!text) return "";
const lowered = text.toLowerCase();
if (
lowered.includes("cannot truncate prompt with n_keep") ||
lowered.includes("context size has been exceeded") ||
(lowered.includes("prompt exceeded") && lowered.includes("context"))
) {
return "Prompt/context exceeded the model window.";
}
if (
lowered.includes("connection refused") ||
lowered.includes("connection error") ||
lowered.includes("econnrefused")
) {
return "LLM endpoint connection error.";
}
if (lowered.includes("timed out") || lowered.includes("job timeout")) {
return "Worker job timed out.";
}
if (lowered.includes("response did not contain parseable json")) {
return "Model returned non-JSON output when structured output was expected.";
}
const stackLikeIndex = text.search(/\b(traceback|stack trace| at [A-Za-z0-9_.]+[:(])/i);
const compact = stackLikeIndex > 0 ? text.slice(0, stackLikeIndex).trim() : text;
if (compact.length <= 220) return compact;
return `${compact.slice(0, 217)}...`;
}
const ASK_REMOTE_BUDDY_COMMAND = "/ask_remote_buddy";
const LOCAL_QUICK_REPLY_SYSTEM_PROMPT = loadPromptTemplate(
"localbuddy/local_quick_reply_system_prompt.md",
).trim();
const LOCAL_QUICK_REPLY_JSON_SYSTEM_SUFFIX = loadPromptTemplate(
"localbuddy/local_quick_reply_json_system_suffix.md",
).trim();
function tryParseJsonObject(raw: string): Record<string, unknown> | null {
const parseAtDepth = (input: string, depth: number): Record<string, unknown> | null => {
if (depth > 2) return null;
const trimmed = input.trim();
if (!trimmed) return null;
try {
const parsed = JSON.parse(trimmed);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>;
}
if (typeof parsed === "string" && parsed.trim()) {
return parseAtDepth(parsed, depth + 1);
}
} catch {
// fall through
}
return null;
};
const trimmed = raw.trim();
if (!trimmed) return null;
const direct = parseAtDepth(trimmed, 0);
if (direct) return direct;
const firstBrace = trimmed.indexOf("{");
const lastBrace = trimmed.lastIndexOf("}");
if (firstBrace >= 0 && lastBrace > firstBrace) {
const sliced = trimmed.slice(firstBrace, lastBrace + 1);
const nested = parseAtDepth(sliced, 0);
if (nested) return nested;
}
return null;
}
function extractLocalReplyFromObject(value: Record<string, unknown> | null): string {
if (!value) return "";
const candidates = [
value.reply,
value.assistant_message,
value.message,
value.text,
value.content,
];
for (const candidate of candidates) {
if (typeof candidate === "string" && candidate.trim()) {
return candidate.trim();
}
}
return "";
}
function extractLocalReplyFromJsonLikeText(value: string): string {
const keyPattern = "(reply|assistant_message|message|text|content)";
const directMatch = value.match(
new RegExp(`"${keyPattern}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`, "i"),
);
if (!directMatch?.[2]) return "";
const encoded = directMatch[2];
try {
const decoded = JSON.parse(`"${encoded}"`);
return typeof decoded === "string" ? decoded.trim() : "";
} catch {
return encoded.trim();
}
}
function fallbackLocalReply(userPrompt: string): string {
const text = userPrompt.trim().toLowerCase();
if (/^(hi|hello|hey)\b/.test(text)) {
return "Hello. I can answer lightweight questions directly, or route execution work with /ask_remote_buddy <request>.";
}
if (/status|what'?s the status|whats the status/.test(text)) {
return "I’m online and ready. For full job/repo status, use /ask_remote_buddy <request>.";
}
return "I can answer lightweight questions directly. For execution or coding work, use /ask_remote_buddy <request>.";
}
function sanitizeLocalReply(raw: string, userPrompt: string): string {
let text = String(raw ?? "")
.replace(/^```(?:json)?\s*/i, "")
.replace(/```/g, "")
.trim();
if (!text) return fallbackLocalReply(userPrompt);
// Some providers ignore/relax JSON schema and return alternate keys.
const parsed = tryParseJsonObject(text);
const extracted = extractLocalReplyFromObject(parsed);
if (extracted) {
text = extracted;
} else {
const extractedFromJsonLike = extractLocalReplyFromJsonLikeText(text);
if (extractedFromJsonLike) {
text = extractedFromJsonLike;
}
}
const lowered = text.toLowerCase();
const reasoningSignals = [
"analyze the user's request",
"identify the constraints",
"self-correction",
"step-by-step",
"my reasoning",
"chain-of-thought",
];
if (reasoningSignals.some((signal) => lowered.includes(signal))) {
return fallbackLocalReply(userPrompt);
}
// Keep only the first short paragraph/sentence if model rambles.
const firstParagraph = text.split(/\n\s*\n/)[0]?.trim() ?? text;
text = firstParagraph.length > 320 ? `${firstParagraph.slice(0, 317)}...` : firstParagraph;
if (/^\d+\.\s+\*\*/.test(text) || /^analysis[:\s]/i.test(text)) {
return fallbackLocalReply(userPrompt);
}
const stillJsonLike =
/^\s*\{[\s\S]*\}\s*$/.test(text) &&
/"(reply|assistant_message|message|text|content)"\s*:/.test(text);
if (stillJsonLike) {
return fallbackLocalReply(userPrompt);
}
return text || fallbackLocalReply(userPrompt);
}
interface RequestListResponse {
ok: boolean;
requests?: RequestApiRow[];
message?: string;
}
interface JobListResponse {
ok: boolean;
jobs?: JobApiRow[];
message?: string;
}
interface JobLogListResponse {
ok: boolean;
logs?: JobLogApiRow[];
cursor?: number | null;
message?: string;
}
type RequestPriority = "interactive" | "normal" | "background";
function classifyRemoteRequestPriority(input: string): RequestPriority {
const text = String(input ?? "")
.trim()
.toLowerCase();
if (!text) return "normal";
if (
/\b(status|progress|queue|queued|eta|where|hows my job|what'?s my status|check on)\b/.test(text)
) {
return "interactive";
}
if (
/\b(comprehensive|deep dive|full pass|phase\s+\d|architecture|migration|refactor|rewrite|all components|everything)\b/.test(
text,
) ||
text.length > 1200
) {
return "background";
}
return "normal";
}
function queueWaitBudgetForPriority(priority: RequestPriority): number {
switch (priority) {
case "interactive":
return 20_000;
case "background":
return 240_000;
default:
return 90_000;
}
}
function formatEtaFromMs(ms: number | undefined): string {
if (!Number.isFinite(ms as number) || (ms as number) <= 0) return "now";
const value = Math.max(0, Math.floor(ms as number));
if (value < 1_000) return `${value}ms`;
const secs = Math.ceil(value / 1_000);
if (secs < 60) return `${secs}s`;
const minutes = Math.floor(secs / 60);
const remSecs = secs % 60;
return remSecs > 0 ? `${minutes}m ${remSecs}s` : `${minutes}m`;
}
function parseRemoteBuddyCommand(input: string): {
forceRemote: boolean;
prompt: string;
usageMessage?: string;
} {
const trimmed = String(input ?? "").trim();
const command = ASK_REMOTE_BUDDY_COMMAND.toLowerCase();
if (!trimmed.toLowerCase().startsWith(command)) {
return { forceRemote: false, prompt: trimmed };
}
const rest = trimmed
.slice(command.length)
.replace(/^[:\-]\s*/, "")
.trim();
if (!rest) {
return {
forceRemote: true,
prompt: "",
usageMessage:
"Usage: /ask_remote_buddy <request>. Example: /ask_remote_buddy fix the failing job status in the dashboard.",
};
}
return { forceRemote: true, prompt: rest };
}
function isLikelyLocalOnlyPrompt(input: string): boolean {
const text = String(input ?? "")
.trim()
.toLowerCase();
if (!text) return true;
if (isLocalReadonlyQueryPrompt(text)) {
return true;
}
if (
/^(hi|hello|hey|yo|sup|thanks|thank you|thx|ok|okay|cool|nice|good morning|good afternoon|good evening)[!. ]*$/.test(
text,
)
) {
return true;
}
if (/^(how are you|what can you do|who are you|are you there|status\??)\b/.test(text)) {
return true;
}
const executionCue =
/\b(fix|implement|write|create|add|remove|delete|rename|refactor|run|test|lint|build|debug|search|find|edit|update|change)\b/.test(
text,
);
if (executionCue) return false;
// Short affirmatives are replies to a prior RemoteBuddy question ("Should I implement this?")
// and should be forwarded there, not handled locally.
if (
/^(yes|confirm|confirmed|proceed|go ahead|go|do it|let'?s?(?: do it| go)?|sure|yep|yup|absolutely|approved?)[!. ]*$/.test(
text,
)
) {
return false;
}
return text.length <= 120;
}
// ─── LocalBuddy HTTP Server ─────────────────────────────────────────────────
class LocalBuddyServer {
private agentId = "localbuddy-1";
private server: string;
private sessionId: string;
private repo: string;
private authToken: string | null;
private llm: LLMClient;
private readonly recentJobFailures: Array<{ jobId: string; summary: string; ts: string }> = [];
private readonly seenJobFailureKeys = new Set<string>();
constructor(opts: { server: string; sessionId: string; authToken: string | null }) {
this.server = opts.server;
this.sessionId = opts.sessionId;
this.authToken = opts.authToken;
// Detect repo root from current working directory
this.repo = detectRepoRoot(process.cwd());
console.log(`[LocalBuddy] Detected repo root: ${this.repo}`);
// Initialize LLM client for prompt enhancement
const llmCfg = CONFIG.localbuddy.llm;
this.llm = createLLMClient({
service: "localbuddy",
sessionId: this.sessionId,
backend: llmCfg.backend,
endpoint: llmCfg.endpoint,
model: llmCfg.model,
apiKey: llmCfg.apiKey,
serverUrl: this.server,
authToken: this.authToken,
});
console.log(`[LocalBuddy] LLM client initialized`);
}
private async answerLocally(userPrompt: string): Promise<string> {
const normalized = String(userPrompt ?? "").trim();
if (!normalized) {
return "I didn't receive a request. Try a quick question, or use /ask_remote_buddy <request> to route work to RemoteBuddy.";
}
const statusReply = await this.answerRequestStatus(normalized);
if (statusReply) return statusReply;
const readonlyReply = await answerLocalReadonlyQuery(normalized, {
repoRoot: this.repo,
serverUrl: this.server,
authHeaders: this.authHeaders(),
});
if (readonlyReply) return readonlyReply;
try {
const output = await this.llm.generate({
system: `${LOCAL_QUICK_REPLY_SYSTEM_PROMPT}\n\n${LOCAL_QUICK_REPLY_JSON_SYSTEM_SUFFIX}`,
messages: [
{
role: "user",
content: loadPromptTemplate("localbuddy/local_quick_reply_user_prompt.md", {
user_message: normalized,
}),
},
],
json: true,
maxTokens: 300,
temperature: 0.2,
});
const parsed = tryParseJsonObject(output.text);
const reply = extractLocalReplyFromObject(parsed) || output.text;
const text = sanitizeLocalReply(reply, normalized);
if (text) return text;
} catch (err) {
console.error("[LocalBuddy] Local reply generation failed:", err);
}
return fallbackLocalReply(normalized);
}
private authHeaders(contentType = false): Record<string, string> {
const headers: Record<string, string> = {};
if (contentType) headers["Content-Type"] = "application/json";
if (this.authToken) headers["Authorization"] = `Bearer ${this.authToken}`;
return headers;
}
private toSingleLine(value: unknown, maxChars = 220): string {
const text = String(value ?? "")
.replace(/\s+/g, " ")
.trim();
if (!text) return "";
if (text.length <= maxChars) return text;
return `${text.slice(0, Math.max(0, maxChars - 3))}...`;
}
private async fetchJobLogTail(jobId: string, limit = 8): Promise<string[]> {
try {
const res = await fetch(
`${this.server}/jobs/${encodeURIComponent(jobId)}/logs?limit=${Math.max(1, Math.min(20, limit))}`,
{ headers: this.authHeaders() },
);
if (!res.ok) return [];
const payload = (await res.json()) as JobLogListResponse;
if (!payload.ok || !Array.isArray(payload.logs)) return [];
return payload.logs
.map((row) => this.toSingleLine(row?.message, 220))
.filter(Boolean)
.slice(-Math.max(1, Math.min(10, limit)));
} catch {
return [];
}
}
private async emitProactiveFailureUpdate(
comm: CommunicationManager,
jobId: string,
message: string,
detail: string,
): Promise<void> {
const shortJob = jobId.slice(0, 8);
const messageText = this.toSingleLine(message, 220) || "WorkerPal job failed.";
const detailText = this.toSingleLine(detail, 200);
const detailSuffix = detailText && detailText !== messageText ? ` (${detailText})` : "";
const intro =
`WorkerPal job ${shortJob} failed: ${messageText}${detailSuffix}. ` +
"I got the failure and I'm checking recent logs now.";
const introOk = await comm.assistantMessage(intro);
if (!introOk) {
console.warn(`[LocalBuddy] Failed to emit proactive failure intro for job ${jobId}`);
}
const tail = await this.fetchJobLogTail(jobId, 8);
if (tail.length === 0) return;
const likelyCause = summarizeFailureForPrompt(tail[tail.length - 1] ?? detail ?? message);
const diagnosis = `Diagnosis for job ${shortJob}: ${likelyCause}\nRecent logs:\n\`\`\`\n${tail.join("\n")}\n\`\`\``;
const diagnosisOk = await comm.assistantMessage(diagnosis);
if (!diagnosisOk) {
console.warn(`[LocalBuddy] Failed to emit proactive failure diagnosis for job ${jobId}`);
}
}
private async answerRequestStatus(userPrompt: string): Promise<string | null> {
if (!isStatusLookupPrompt(userPrompt)) return null;
try {
const [requestData, jobData] = await Promise.all([
fetch(`${this.server}/requests?status=all&limit=200`, {
headers: this.authHeaders(),
}),
fetch(`${this.server}/jobs?status=all&limit=400`, {
headers: this.authHeaders(),
}),
]);
if (!requestData.ok) {
return `I couldn't check request status right now (requests API ${requestData.status}).`;
}
if (!jobData.ok) {
return `I couldn't check request status right now (jobs API ${jobData.status}).`;
}
const requestsPayload = (await requestData.json()) as RequestListResponse;
const jobsPayload = (await jobData.json()) as JobListResponse;
const sessionJobs = (jobsPayload.jobs ?? []).filter(
(row) => row.sessionId === this.sessionId,
);
let logs: JobLogApiRow[] = [];
const requestedJobToken = extractReferencedJobToken(userPrompt);
const mightBeJobQuery =
Boolean(requestedJobToken) || /\b(job|workerpal|task)\b/i.test(userPrompt);
if (mightBeJobQuery && sessionJobs.length > 0) {
let selectedJob: JobApiRow | null =
sessionJobs.find((row) => row.status === "claimed") ??
sessionJobs.find((row) => row.status === "pending") ??
sessionJobs[0];
if (requestedJobToken) {
const token = requestedJobToken.toLowerCase();
const matchedJob =
sessionJobs.find((row) => row.id.toLowerCase() === token) ??
sessionJobs.find((row) => row.id.toLowerCase().startsWith(token)) ??
null;
selectedJob = matchedJob;
}
if (selectedJob) {
const logsRes = await fetch(`${this.server}/jobs/${selectedJob.id}/logs?limit=10`, {
headers: this.authHeaders(),
});
if (logsRes.ok) {
const logsPayload = (await logsRes.json()) as JobLogListResponse;
logs = logsPayload.logs ?? [];
}
}
}
const jobReply = buildJobStatusReply({
userPrompt,
sessionId: this.sessionId,
jobs: jobsPayload.jobs ?? [],
logs,
summarizeFailure: summarizeFailureForPrompt,
});
if (jobReply) return jobReply;
return buildRequestStatusReply({
userPrompt,
sessionId: this.sessionId,
requests: requestsPayload.requests ?? [],
jobs: sessionJobs,
summarizeFailure: summarizeFailureForPrompt,
});
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
return `I couldn't check request status right now (${summarizeFailureForPrompt(reason)}).`;
}
}
/**
* Start the HTTP server
*/
async startServer(port: number): Promise<void> {
// Capture `this` context for use in fetch handler
const agentId = this.agentId;
const repo = this.repo;
const sessionId = this.sessionId;
const serverUrl = this.server;
const authToken = this.authToken;
const answerLocally = this.answerLocally.bind(this);
const comm = new CommunicationManager({
serverUrl,
sessionId,
authToken,
from: `agent:${agentId}`,
});
let stopping = false;
let statusSessionReady = false;
const ensureSessionWithRetry = async (
maxRetries = 20,
baseDelayMs = 500,
maxDelayMs = 5000,
): Promise<boolean> => {
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (authToken) headers["Authorization"] = `Bearer ${authToken}`;
for (let attempt = 1; attempt <= maxRetries && !stopping; attempt++) {
try {
const res = await fetch(`${serverUrl}/sessions`, {
method: "POST",
headers,
body: JSON.stringify({ sessionId }),
});
if (res.ok) return true;
} catch {
// retry
}
const delayMs = Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs);
await Bun.sleep(delayMs);
}
return false;
};
const emitStartupPresence = async (): Promise<void> => {
const ready = await ensureSessionWithRetry();
if (!ready) {
console.warn("[LocalBuddy] Could not ensure session for startup presence events");
return;
}
statusSessionReady = true;
const startupDeadlineMs = Date.now() + 15_000;
while (!stopping) {
const statusOk = await comm.status(agentId, "idle", "LocalBuddy online and ready");
if (statusOk) return;
statusSessionReady = false;
if (Date.now() >= startupDeadlineMs) break;
await Bun.sleep(1_000);
statusSessionReady = await ensureSessionWithRetry(3, 400, 2_500);
}
console.warn("[LocalBuddy] Failed to emit startup status event");
};
void emitStartupPresence();
const statusHeartbeatMs = parseStatusHeartbeatMs(CONFIG.localbuddy.statusHeartbeatMs);
const statusHeartbeatTimer =
statusHeartbeatMs > 0
? setInterval(() => {
void (async () => {
if (stopping) return;
if (!statusSessionReady) {
statusSessionReady = await ensureSessionWithRetry(3, 400, 2500);
}
const ok = await comm.status(agentId, "idle", "LocalBuddy heartbeat");
if (!ok) {
statusSessionReady = false;
}
})();
}, statusHeartbeatMs)
: null;
const monitorStartedAt = Date.now();
const stopSessionEvents = comm.subscribeSessionEvents(
(envelope) => {
if (envelope.type !== "job_failed") return;
if (stopping) return;
const tsMs = Date.parse(envelope.ts);
if (Number.isFinite(tsMs) && tsMs + 2000 < monitorStartedAt) return;
const payload = envelope.payload as {
jobId?: unknown;
message?: unknown;
detail?: unknown;
};
const jobId = String(payload.jobId ?? "").trim();
const message = summarizeFailureForPrompt(payload.message);
const detail = summarizeFailureForPrompt(payload.detail);
if (!jobId || !message) return;
const dedupeKey = `${jobId}:${message}`;
if (this.seenJobFailureKeys.has(dedupeKey)) return;
this.seenJobFailureKeys.add(dedupeKey);
if (this.seenJobFailureKeys.size > 200) {
const oldest = this.seenJobFailureKeys.values().next().value;
if (typeof oldest === "string") {
this.seenJobFailureKeys.delete(oldest);
}
}
const summary =
detail && detail !== message ? `${message} (detail: ${detail.slice(0, 120)})` : message;
this.recentJobFailures.unshift({ jobId, summary, ts: envelope.ts });
if (this.recentJobFailures.length > 20) {
this.recentJobFailures.length = 20;
}
console.warn(`[LocalBuddy] Observed WorkerPal job failure ${jobId}: ${summary}`);
void this.emitProactiveFailureUpdate(comm, jobId, message, detail);
},
{
onError: (message) => console.warn(`[LocalBuddy] Session monitor: ${message}`),
},
);
const stopMonitor = () => {
stopping = true;
void comm.status(agentId, "shutting_down", "LocalBuddy shutting down");
if (statusHeartbeatTimer) {
clearInterval(statusHeartbeatTimer);
}
try {
stopSessionEvents();
} catch {
// ignore shutdown errors
}
};
process.once("SIGINT", stopMonitor);
process.once("SIGTERM", stopMonitor);
if (process.platform === "win32") {
process.once("SIGBREAK", stopMonitor);
}
// Retry Bun.serve() on EADDRINUSE — can happen when Bun crashes and auto-restarts
// before the dying process has fully released the port.
const maxPortRetries = 8;
for (let portAttempt = 1; portAttempt <= maxPortRetries; portAttempt++) {
try {
Bun.serve({
port,
hostname: "0.0.0.0",
idleTimeout: 120,
async fetch(req: Request): Promise<Response> {
const url = new URL(req.url);
const pathname = url.pathname;
const method = req.method;
const jsonHeaders = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
"Access-Control-Allow-Headers": "content-type, authorization",
};
const makeJson = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: jsonHeaders });
// Handle CORS preflight
if (method === "OPTIONS") {
return new Response(null, { status: 204, headers: jsonHeaders });
}
// POST /message - Main endpoint for client messages with streaming status
if (pathname === "/message" && method === "POST") {
try {
const body = (await req.json()) as { text: string };
const rawPrompt = String(body.text ?? "");
const routing = parseRemoteBuddyCommand(rawPrompt);
const routedPrompt = routing.prompt;
const forceRemote = routing.forceRemote;
const statusLookupIntent = isStatusLookupPrompt(routedPrompt);
const localOnly =
!forceRemote && (statusLookupIntent || isLikelyLocalOnlyPrompt(routedPrompt));
if (!rawPrompt.trim()) {
return makeJson({ ok: false, message: "text is required" }, 400);
}
console.log(
`[LocalBuddy] Received message: ${rawPrompt.substring(0, 80)}${rawPrompt.length > 80 ? "..." : ""}`,
);
if (forceRemote) {
console.log(
"[LocalBuddy] Routing mode: forced RemoteBuddy via /ask_remote_buddy",
);
} else if (statusLookupIntent) {
console.log("[LocalBuddy] Routing mode: local status lookup");
} else if (localOnly) {
console.log("[LocalBuddy] Routing mode: local-only reply");
} else {
console.log("[LocalBuddy] Routing mode: queue for RemoteBuddy");
}
// ── Step 0: Emit user message to server session so it appears in UI ──
const cmdHeaders: Record<string, string> = { "Content-Type": "application/json" };
if (authToken) cmdHeaders["Authorization"] = `Bearer ${authToken}`;
void comm
.userMessage(rawPrompt)
.then((ok) => {
if (!ok) {
console.error(`[LocalBuddy] Failed to emit user message to session`);
}
})
.catch((err) =>
console.error(`[LocalBuddy] Failed to emit user message to session:`, err),
);
void comm
.assistantMessage(
forceRemote
? "Received your request. Routing this to RemoteBuddy now."
: localOnly
? "Received your request. I can answer this directly as LocalBuddy."
: "Received your request. Queueing this to RemoteBuddy now.",
)
.then((ok) => {
if (!ok) {
console.error(
`[LocalBuddy] Failed to emit immediate acknowledgement message`,
);
}
})
.catch((err) =>
console.error(
`[LocalBuddy] Failed to emit immediate acknowledgement message:`,
err,
),
);
// ── Process and stream status back via SSE ──
let closed = false;
const stream = new ReadableStream({
async start(controller) {
const send = (data: { type: string; message: string; data?: any }) => {
if (closed) return;
try {
controller.enqueue(
new TextEncoder().encode(`data: ${JSON.stringify(data)}\n\n`),
);
} catch {
closed = true;
}
};
const close = () => {
if (closed) return;
closed = true;
try {
controller.close();
} catch {
/* already closed */
}
};
try {
if (routing.usageMessage) {
send({ type: "status", message: "Command missing request body." });
await comm.assistantMessage(routing.usageMessage);
send({
type: "complete",
message: "Handled locally",
data: { mode: "local_usage_hint", sessionId },
});
close();
return;
}
if (localOnly) {
send({ type: "status", message: "Generating LocalBuddy response..." });
const localReply = await answerLocally(routedPrompt);
await comm.assistantMessage(localReply);
send({
type: "complete",
message: "Responded locally",
data: { mode: "local", sessionId },
});
close();
return;
}
// Queue immediately; RemoteBuddy handles context/planning.
send({ type: "status", message: "Enqueuing to Request Queue..." });
const priority = classifyRemoteRequestPriority(routedPrompt);
const queueWaitBudgetMs = queueWaitBudgetForPriority(priority);
const res = await fetch(`${serverUrl}/requests/enqueue`, {
method: "POST",
headers: cmdHeaders,
body: JSON.stringify({
sessionId,
prompt: routedPrompt,
priority,
queueWaitBudgetMs,
}),
});
if (!res.ok) {
const err = await res.text();
console.error(`[LocalBuddy] Failed to enqueue request: ${err}`);
send({ type: "error", message: `Failed to enqueue: ${err}` });
close();
return;
}
const data = (await res.json()) as {
ok: boolean;
requestId?: string;
queuePosition?: number;
etaMs?: number;
};
console.log(`[LocalBuddy] Enqueued request: ${data.requestId}`);
const requestSuffix = data.requestId
? ` (${data.requestId.slice(0, 8)})`
: "";
const queueSuffix =
Number.isFinite(data.queuePosition as number) &&
(data.queuePosition as number) > 0
? ` Priority ${priority}; queue #${data.queuePosition} (ETA ${formatEtaFromMs(
data.etaMs,
)}).`
: ` Priority ${priority}.`;
await comm.assistantMessage(
`Request queued${requestSuffix}.${queueSuffix} RemoteBuddy is planning and will assign a WorkerPal.`,
);
// Final success message
send({
type: "complete",
message: "Request enqueued successfully",
data: {
requestId: data.requestId,
sessionId,
priority,
queuePosition: data.queuePosition,
etaMs: data.etaMs,
},
});
close();
} catch (err) {
console.error(`[LocalBuddy] Error processing message:`, err);
send({ type: "error", message: String(err) });
close();
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
"Access-Control-Allow-Origin": "*",
},
});
} catch (err) {
console.error(`[LocalBuddy] Error processing message:`, err);
return makeJson({ ok: false, message: String(err) }, 500);
}
}
// GET /healthz - Health check endpoint
if (pathname === "/healthz" && method === "GET") {
return makeJson({
ok: true,
agentId,
repo,
sessionId,
});
}
// GET / - Info endpoint
if (pathname === "/" && method === "GET") {
return makeJson({
name: "PushPals LocalBuddy",
version: "0.1.0",
endpoints: {
"POST /message":
"Send a message to LocalBuddy (use /ask_remote_buddy <request> to force remote routing)",
"GET /healthz": "Health check",
},
});
}
return makeJson({ ok: false, message: "Not found" }, 404);
},
});
// Bun.serve() succeeded — exit the retry loop
break;
} catch (err: any) {
if (err?.code === "EADDRINUSE" && portAttempt < maxPortRetries) {
console.warn(
`[LocalBuddy] Port ${port} in use; retrying in 2000ms (attempt ${portAttempt}/${maxPortRetries})...`,
);
await Bun.sleep(2000);
} else {