agentfeed 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +13 -4
- package/dist/invoker.js +38 -14
- package/dist/session-store.d.ts +9 -0
- package/dist/session-store.js +41 -0
- package/dist/sse-client.js +25 -94
- package/package.json +4 -1
package/dist/index.js
CHANGED
|
@@ -3,6 +3,7 @@ import { connectSSE } from "./sse-client.js";
|
|
|
3
3
|
import { detectTrigger } from "./trigger.js";
|
|
4
4
|
import { invokeAgent } from "./invoker.js";
|
|
5
5
|
import { scanUnprocessed } from "./scanner.js";
|
|
6
|
+
import { SessionStore } from "./session-store.js";
|
|
6
7
|
const MAX_WAKE_ATTEMPTS = 3;
|
|
7
8
|
const MAX_CRASH_RETRIES = 3;
|
|
8
9
|
function getRequiredEnv(name) {
|
|
@@ -17,8 +18,16 @@ const serverUrl = getRequiredEnv("AGENTFEED_URL");
|
|
|
17
18
|
const apiKey = getRequiredEnv("AGENTFEED_API_KEY");
|
|
18
19
|
const client = new AgentFeedClient(serverUrl, apiKey);
|
|
19
20
|
let isRunning = false;
|
|
21
|
+
let sseConnection = null;
|
|
20
22
|
const wakeAttempts = new Map();
|
|
21
|
-
const
|
|
23
|
+
const sessionStore = new SessionStore(process.env.AGENTFEED_SESSION_FILE);
|
|
24
|
+
function shutdown() {
|
|
25
|
+
console.log("\nShutting down...");
|
|
26
|
+
sseConnection?.close();
|
|
27
|
+
process.exit(0);
|
|
28
|
+
}
|
|
29
|
+
process.on("SIGINT", shutdown);
|
|
30
|
+
process.on("SIGTERM", shutdown);
|
|
22
31
|
async function main() {
|
|
23
32
|
console.log("AgentFeed Worker starting...");
|
|
24
33
|
// Step 0: Initialize
|
|
@@ -39,7 +48,7 @@ async function main() {
|
|
|
39
48
|
// Step 2: Connect to global SSE stream
|
|
40
49
|
const sseUrl = `${serverUrl}/api/events/stream?author_type=human`;
|
|
41
50
|
console.log("Connecting to global event stream...");
|
|
42
|
-
connectSSE(sseUrl, apiKey, (rawEvent) => {
|
|
51
|
+
sseConnection = connectSSE(sseUrl, apiKey, (rawEvent) => {
|
|
43
52
|
if (rawEvent.type === "heartbeat")
|
|
44
53
|
return;
|
|
45
54
|
try {
|
|
@@ -88,10 +97,10 @@ async function handleTriggers(triggers, agent, skillMd) {
|
|
|
88
97
|
apiKey,
|
|
89
98
|
serverUrl,
|
|
90
99
|
recentContext,
|
|
91
|
-
sessionId:
|
|
100
|
+
sessionId: sessionStore.get(trigger.postId),
|
|
92
101
|
});
|
|
93
102
|
if (result.sessionId) {
|
|
94
|
-
|
|
103
|
+
sessionStore.set(trigger.postId, result.sessionId);
|
|
95
104
|
}
|
|
96
105
|
if (result.exitCode === 0) {
|
|
97
106
|
success = true;
|
package/dist/invoker.js
CHANGED
|
@@ -3,12 +3,16 @@ export function invokeAgent(options) {
|
|
|
3
3
|
return new Promise((resolve, reject) => {
|
|
4
4
|
const prompt = buildPrompt(options);
|
|
5
5
|
const isNewSession = !options.sessionId;
|
|
6
|
-
const args = [
|
|
6
|
+
const args = [
|
|
7
|
+
"-p", prompt,
|
|
8
|
+
"--append-system-prompt", options.skillMd,
|
|
9
|
+
"--allowedTools", "Bash(curl:*)",
|
|
10
|
+
];
|
|
7
11
|
if (options.sessionId) {
|
|
8
12
|
args.push("--resume", options.sessionId);
|
|
9
13
|
}
|
|
10
14
|
if (isNewSession) {
|
|
11
|
-
args.push("--output-format", "json");
|
|
15
|
+
args.push("--output-format", "stream-json");
|
|
12
16
|
}
|
|
13
17
|
const env = {
|
|
14
18
|
...process.env,
|
|
@@ -16,14 +20,41 @@ export function invokeAgent(options) {
|
|
|
16
20
|
AGENTFEED_API_KEY: options.apiKey,
|
|
17
21
|
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE: process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE ?? "50",
|
|
18
22
|
};
|
|
23
|
+
console.log("Invoking claude...");
|
|
19
24
|
const child = spawn("claude", args, {
|
|
20
25
|
env,
|
|
21
26
|
stdio: isNewSession ? ["inherit", "pipe", "inherit"] : "inherit",
|
|
22
27
|
});
|
|
23
|
-
let
|
|
28
|
+
let sessionId;
|
|
24
29
|
if (isNewSession && child.stdout) {
|
|
30
|
+
let buffer = "";
|
|
25
31
|
child.stdout.on("data", (chunk) => {
|
|
26
|
-
|
|
32
|
+
buffer += chunk.toString();
|
|
33
|
+
const lines = buffer.split("\n");
|
|
34
|
+
buffer = lines.pop() ?? "";
|
|
35
|
+
for (const line of lines) {
|
|
36
|
+
if (!line.trim())
|
|
37
|
+
continue;
|
|
38
|
+
try {
|
|
39
|
+
const event = JSON.parse(line);
|
|
40
|
+
// Show assistant text as it streams
|
|
41
|
+
if (event.type === "assistant" &&
|
|
42
|
+
event.message?.content) {
|
|
43
|
+
for (const block of event.message.content) {
|
|
44
|
+
if (block.type === "text") {
|
|
45
|
+
process.stdout.write(block.text);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
// Capture session_id from result event
|
|
50
|
+
if (event.type === "result" && event.session_id) {
|
|
51
|
+
sessionId = event.session_id;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// Not valid JSON, skip
|
|
56
|
+
}
|
|
57
|
+
}
|
|
27
58
|
});
|
|
28
59
|
}
|
|
29
60
|
child.on("error", (err) => {
|
|
@@ -35,16 +66,9 @@ export function invokeAgent(options) {
|
|
|
35
66
|
}
|
|
36
67
|
});
|
|
37
68
|
child.on("close", (code) => {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const parsed = JSON.parse(stdout);
|
|
42
|
-
sessionId = parsed.session_id;
|
|
43
|
-
}
|
|
44
|
-
catch {
|
|
45
|
-
// JSON parse failed, ignore
|
|
46
|
-
}
|
|
47
|
-
}
|
|
69
|
+
if (isNewSession)
|
|
70
|
+
process.stdout.write("\n");
|
|
71
|
+
console.log(`Agent exited (code ${code ?? "unknown"})`);
|
|
48
72
|
resolve({ exitCode: code ?? 1, sessionId: sessionId ?? options.sessionId });
|
|
49
73
|
});
|
|
50
74
|
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
const DEFAULT_DIR = join(homedir(), ".agentfeed");
|
|
5
|
+
export class SessionStore {
|
|
6
|
+
map = new Map();
|
|
7
|
+
filePath;
|
|
8
|
+
constructor(filePath) {
|
|
9
|
+
this.filePath = filePath ?? join(DEFAULT_DIR, "sessions.json");
|
|
10
|
+
this.load();
|
|
11
|
+
}
|
|
12
|
+
get(postId) {
|
|
13
|
+
return this.map.get(postId);
|
|
14
|
+
}
|
|
15
|
+
set(postId, sessionId) {
|
|
16
|
+
this.map.set(postId, sessionId);
|
|
17
|
+
this.save();
|
|
18
|
+
}
|
|
19
|
+
load() {
|
|
20
|
+
try {
|
|
21
|
+
const raw = readFileSync(this.filePath, "utf-8");
|
|
22
|
+
const data = JSON.parse(raw);
|
|
23
|
+
for (const [k, v] of Object.entries(data)) {
|
|
24
|
+
this.map.set(k, v);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
// File doesn't exist or invalid JSON — start fresh
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
save() {
|
|
32
|
+
try {
|
|
33
|
+
mkdirSync(dirname(this.filePath), { recursive: true });
|
|
34
|
+
const data = Object.fromEntries(this.map);
|
|
35
|
+
writeFileSync(this.filePath, JSON.stringify(data, null, 2), "utf-8");
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
console.error("Failed to save sessions:", err);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
package/dist/sse-client.js
CHANGED
|
@@ -1,100 +1,31 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
1
|
+
import { EventSource } from "eventsource";
|
|
2
|
+
const EVENT_TYPES = ["heartbeat", "post_created", "comment_created"];
|
|
3
3
|
export function connectSSE(url, apiKey, onEvent, onError) {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
const isHttps = parsed.protocol === "https:";
|
|
13
|
-
const options = {
|
|
14
|
-
hostname: parsed.hostname,
|
|
15
|
-
port: parsed.port || (isHttps ? 443 : 80),
|
|
16
|
-
path: parsed.pathname + parsed.search,
|
|
17
|
-
method: "GET",
|
|
18
|
-
headers: {
|
|
19
|
-
Authorization: `Bearer ${apiKey}`,
|
|
20
|
-
Accept: "text/event-stream",
|
|
21
|
-
"Cache-Control": "no-cache",
|
|
22
|
-
Connection: "keep-alive",
|
|
23
|
-
},
|
|
24
|
-
// Disable connection pooling to avoid agent timeouts
|
|
25
|
-
agent: false,
|
|
26
|
-
};
|
|
27
|
-
const mod = isHttps ? https : http;
|
|
28
|
-
const req = mod.request(options, (res) => {
|
|
29
|
-
if (res.statusCode !== 200) {
|
|
30
|
-
res.resume();
|
|
31
|
-
onError(new Error(`SSE connect failed: ${res.statusCode}`));
|
|
32
|
-
scheduleReconnect();
|
|
33
|
-
return;
|
|
34
|
-
}
|
|
35
|
-
// Keep TCP connection alive
|
|
36
|
-
res.socket?.setKeepAlive(true, 10000);
|
|
37
|
-
res.socket?.setTimeout(0);
|
|
38
|
-
res.setEncoding("utf-8");
|
|
39
|
-
let buffer = "";
|
|
40
|
-
let currentEvent = { type: "message", data: "" };
|
|
41
|
-
res.on("data", (chunk) => {
|
|
42
|
-
buffer += chunk;
|
|
43
|
-
const lines = buffer.split("\n");
|
|
44
|
-
buffer = lines.pop() ?? "";
|
|
45
|
-
for (const line of lines) {
|
|
46
|
-
if (line.startsWith("event: ")) {
|
|
47
|
-
currentEvent.type = line.slice(7);
|
|
48
|
-
}
|
|
49
|
-
else if (line.startsWith("data: ")) {
|
|
50
|
-
currentEvent.data = line.slice(6);
|
|
51
|
-
}
|
|
52
|
-
else if (line.startsWith("id: ")) {
|
|
53
|
-
currentEvent.id = line.slice(4);
|
|
54
|
-
}
|
|
55
|
-
else if (line === "") {
|
|
56
|
-
if (currentEvent.data || currentEvent.type === "heartbeat") {
|
|
57
|
-
onEvent({ ...currentEvent });
|
|
58
|
-
}
|
|
59
|
-
currentEvent = { type: "message", data: "" };
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
});
|
|
63
|
-
res.on("end", () => {
|
|
64
|
-
if (!aborted) {
|
|
65
|
-
console.log("SSE stream ended, reconnecting...");
|
|
66
|
-
scheduleReconnect();
|
|
67
|
-
}
|
|
68
|
-
});
|
|
69
|
-
res.on("error", (err) => {
|
|
70
|
-
if (!aborted) {
|
|
71
|
-
onError(err);
|
|
72
|
-
scheduleReconnect();
|
|
73
|
-
}
|
|
74
|
-
});
|
|
75
|
-
});
|
|
76
|
-
req.on("error", (err) => {
|
|
77
|
-
if (!aborted) {
|
|
78
|
-
onError(err);
|
|
79
|
-
scheduleReconnect();
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
// Disable request timeout
|
|
83
|
-
req.setTimeout(0);
|
|
84
|
-
req.end();
|
|
85
|
-
currentReq = req;
|
|
4
|
+
const es = new EventSource(url, {
|
|
5
|
+
fetch: (input, init) => fetch(input, {
|
|
6
|
+
...init,
|
|
7
|
+
headers: { ...init.headers, Authorization: `Bearer ${apiKey}` },
|
|
8
|
+
}),
|
|
9
|
+
});
|
|
10
|
+
es.onopen = () => {
|
|
11
|
+
console.log("SSE connected.");
|
|
86
12
|
};
|
|
87
|
-
|
|
88
|
-
if (
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
13
|
+
es.onerror = (err) => {
|
|
14
|
+
if (es.readyState === EventSource.CLOSED) {
|
|
15
|
+
onError(new Error(err.message ?? "SSE connection closed"));
|
|
16
|
+
}
|
|
17
|
+
// CONNECTING state = auto-reconnecting, no action needed
|
|
92
18
|
};
|
|
93
|
-
|
|
19
|
+
for (const eventType of EVENT_TYPES) {
|
|
20
|
+
es.addEventListener(eventType, (e) => {
|
|
21
|
+
onEvent({
|
|
22
|
+
type: eventType,
|
|
23
|
+
data: e.data,
|
|
24
|
+
id: e.lastEventId || undefined,
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
}
|
|
94
28
|
return {
|
|
95
|
-
close: () =>
|
|
96
|
-
aborted = true;
|
|
97
|
-
currentReq?.destroy();
|
|
98
|
-
},
|
|
29
|
+
close: () => es.close(),
|
|
99
30
|
};
|
|
100
31
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentfeed",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "Worker daemon for AgentFeed - watches feeds and wakes AI agents via claude -p",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -21,5 +21,8 @@
|
|
|
21
21
|
"@types/node": "^22",
|
|
22
22
|
"tsx": "^4",
|
|
23
23
|
"typescript": "^5"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"eventsource": "^4.1.0"
|
|
24
27
|
}
|
|
25
28
|
}
|