talon-agent 1.0.0 → 1.2.0

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.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/package.json +15 -11
  4. package/prompts/dream.md +7 -3
  5. package/prompts/heartbeat.md +30 -0
  6. package/prompts/identity.md +1 -0
  7. package/prompts/teams.md +3 -0
  8. package/prompts/telegram.md +1 -0
  9. package/src/__tests__/chat-settings.test.ts +108 -2
  10. package/src/__tests__/cleanup-registry.test.ts +58 -0
  11. package/src/__tests__/config.test.ts +118 -52
  12. package/src/__tests__/cron-store-extended.test.ts +661 -0
  13. package/src/__tests__/cron-store.test.ts +145 -11
  14. package/src/__tests__/daily-log.test.ts +224 -13
  15. package/src/__tests__/dispatcher.test.ts +424 -23
  16. package/src/__tests__/dream.test.ts +1028 -0
  17. package/src/__tests__/errors-extended.test.ts +428 -0
  18. package/src/__tests__/errors.test.ts +95 -3
  19. package/src/__tests__/fuzz.test.ts +87 -15
  20. package/src/__tests__/gateway-actions.test.ts +1174 -433
  21. package/src/__tests__/gateway-http.test.ts +210 -19
  22. package/src/__tests__/gateway-retry.test.ts +359 -0
  23. package/src/__tests__/gateway-withRetry-extended.test.ts +343 -0
  24. package/src/__tests__/graph.test.ts +830 -0
  25. package/src/__tests__/handlers-stream.test.ts +208 -0
  26. package/src/__tests__/handlers.test.ts +2539 -70
  27. package/src/__tests__/heartbeat.test.ts +364 -0
  28. package/src/__tests__/history-extended.test.ts +775 -0
  29. package/src/__tests__/history-persistence.test.ts +74 -19
  30. package/src/__tests__/history.test.ts +113 -79
  31. package/src/__tests__/integration.test.ts +43 -8
  32. package/src/__tests__/log-init.test.ts +129 -0
  33. package/src/__tests__/log.test.ts +23 -5
  34. package/src/__tests__/media-index.test.ts +317 -35
  35. package/src/__tests__/plugin.test.ts +314 -0
  36. package/src/__tests__/prompt-builder-extended.test.ts +296 -0
  37. package/src/__tests__/prompt-builder.test.ts +44 -9
  38. package/src/__tests__/sessions.test.ts +258 -4
  39. package/src/__tests__/storage-save-errors.test.ts +342 -0
  40. package/src/__tests__/teams-frontend.test.ts +526 -31
  41. package/src/__tests__/telegram-formatting.test.ts +82 -0
  42. package/src/__tests__/terminal-commands.test.ts +208 -1
  43. package/src/__tests__/terminal-renderer.test.ts +223 -0
  44. package/src/__tests__/time.test.ts +107 -0
  45. package/src/__tests__/workspace-migrate.test.ts +256 -0
  46. package/src/__tests__/workspace.test.ts +63 -1
  47. package/src/backend/claude-sdk/tools.ts +64 -18
  48. package/src/bootstrap.ts +14 -14
  49. package/src/cli.ts +440 -125
  50. package/src/core/cron.ts +20 -5
  51. package/src/core/dispatcher.ts +27 -9
  52. package/src/core/dream.ts +79 -24
  53. package/src/core/errors.ts +12 -2
  54. package/src/core/gateway-actions.ts +182 -46
  55. package/src/core/gateway.ts +93 -41
  56. package/src/core/heartbeat.ts +515 -0
  57. package/src/core/plugin.ts +1 -1
  58. package/src/core/prompt-builder.ts +1 -4
  59. package/src/core/pulse.ts +4 -3
  60. package/src/frontend/teams/actions.ts +3 -1
  61. package/src/frontend/teams/formatting.ts +47 -8
  62. package/src/frontend/teams/graph.ts +35 -11
  63. package/src/frontend/teams/index.ts +155 -57
  64. package/src/frontend/teams/tools.ts +4 -6
  65. package/src/frontend/telegram/actions.ts +358 -82
  66. package/src/frontend/telegram/admin.ts +162 -72
  67. package/src/frontend/telegram/callbacks.ts +16 -10
  68. package/src/frontend/telegram/commands.ts +37 -21
  69. package/src/frontend/telegram/formatting.ts +2 -4
  70. package/src/frontend/telegram/handlers.ts +262 -66
  71. package/src/frontend/telegram/index.ts +39 -14
  72. package/src/frontend/telegram/middleware.ts +14 -4
  73. package/src/frontend/telegram/userbot.ts +16 -4
  74. package/src/frontend/terminal/renderer.ts +1 -4
  75. package/src/index.ts +28 -4
  76. package/src/storage/chat-settings.ts +32 -9
  77. package/src/storage/cron-store.ts +53 -11
  78. package/src/storage/daily-log.ts +72 -19
  79. package/src/storage/history.ts +39 -21
  80. package/src/storage/media-index.ts +37 -12
  81. package/src/storage/sessions.ts +3 -2
  82. package/src/util/cleanup-registry.ts +34 -0
  83. package/src/util/config.ts +85 -23
  84. package/src/util/log.ts +47 -17
  85. package/src/util/paths.ts +10 -0
  86. package/src/util/time.ts +29 -6
  87. package/src/util/watchdog.ts +5 -1
  88. package/src/util/workspace.ts +51 -10
@@ -0,0 +1,364 @@
1
+ /**
2
+ * Tests for src/core/heartbeat.ts
3
+ *
4
+ * Covers: initHeartbeat, startHeartbeatTimer (double-start guard),
5
+ * forceHeartbeat (concurrency guard), state persistence semantics
6
+ * (success vs failure paths), and awaitCurrentRun.
7
+ * The actual SDK agent call is mocked to avoid spawning a real Claude agent.
8
+ */
9
+
10
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
11
+
12
+ // ── Mocks ─────────────────────────────────────────────────────────────────
13
+
14
+ vi.mock("../util/log.js", () => ({
15
+ log: vi.fn(),
16
+ logError: vi.fn(),
17
+ logWarn: vi.fn(),
18
+ }));
19
+
20
+ const existsSyncMock = vi.fn(() => false);
21
+ const readFileSyncMock = vi.fn(() => "null");
22
+ const mkdirSyncMock = vi.fn();
23
+
24
+ vi.mock("node:fs", () => ({
25
+ existsSync: existsSyncMock,
26
+ readFileSync: readFileSyncMock,
27
+ mkdirSync: mkdirSyncMock,
28
+ }));
29
+
30
+ const appendFileMock = vi.fn(async () => {});
31
+ const mkdirAsyncMock = vi.fn(async () => undefined);
32
+ vi.mock("node:fs/promises", () => ({
33
+ appendFile: appendFileMock,
34
+ mkdir: mkdirAsyncMock,
35
+ }));
36
+
37
+ const writeAtomicSyncMock = vi.fn();
38
+ vi.mock("write-file-atomic", () => ({
39
+ default: { sync: writeAtomicSyncMock },
40
+ }));
41
+
42
+ // Mock the agent SDK so runHeartbeatAgent doesn't actually spawn Claude
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ const queryMock = vi.fn<() => AsyncGenerator<any>>(async function* () {
45
+ // Yield nothing — simulates a clean run
46
+ });
47
+ vi.mock("@anthropic-ai/claude-agent-sdk", () => ({
48
+ query: queryMock,
49
+ }));
50
+
51
+ vi.mock("../util/paths.js", () => ({
52
+ files: {
53
+ heartbeatState: "/fake/.talon/workspace/memory/heartbeat_state.json",
54
+ dreamState: "/fake/.talon/workspace/memory/dream_state.json",
55
+ memory: "/fake/.talon/workspace/memory/memory.md",
56
+ log: "/fake/.talon/talon.log",
57
+ },
58
+ dirs: {
59
+ root: "/fake/.talon",
60
+ logs: "/fake/.talon/workspace/logs",
61
+ workspace: "/fake/.talon/workspace",
62
+ data: "/fake/.talon/data",
63
+ memory: "/fake/.talon/workspace/memory",
64
+ dailyMemory: "/fake/.talon/workspace/memory/daily",
65
+ prompts: "/fake/.talon/prompts",
66
+ },
67
+ }));
68
+
69
+ // ── Tests ─────────────────────────────────────────────────────────────────
70
+
71
+ const {
72
+ initHeartbeat,
73
+ startHeartbeatTimer,
74
+ stopHeartbeatTimer,
75
+ forceHeartbeat,
76
+ getHeartbeatStatus,
77
+ awaitCurrentRun,
78
+ } = await import("../core/heartbeat.js");
79
+
80
+ describe("initHeartbeat", () => {
81
+ it("accepts a config object without throwing", () => {
82
+ expect(() => initHeartbeat({ model: "claude-sonnet-4-6" })).not.toThrow();
83
+ });
84
+
85
+ it("accepts all optional config fields", () => {
86
+ expect(() =>
87
+ initHeartbeat({
88
+ model: "claude-sonnet-4-6",
89
+ heartbeatModel: "claude-haiku-4-5",
90
+ claudeBinary: "/usr/local/bin/claude",
91
+ workspace: "/tmp/test-workspace",
92
+ }),
93
+ ).not.toThrow();
94
+ });
95
+ });
96
+
97
+ describe("startHeartbeatTimer", () => {
98
+ beforeEach(() => {
99
+ vi.useFakeTimers();
100
+ initHeartbeat({ model: "claude-sonnet-4-6" });
101
+ });
102
+
103
+ afterEach(() => {
104
+ stopHeartbeatTimer();
105
+ vi.useRealTimers();
106
+ });
107
+
108
+ it("guards against double-start during startup delay", () => {
109
+ const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
110
+ const setIntervalSpy = vi.spyOn(globalThis, "setInterval");
111
+
112
+ startHeartbeatTimer(60);
113
+ expect(setTimeoutSpy).toHaveBeenCalledTimes(1);
114
+ expect(setIntervalSpy).not.toHaveBeenCalled();
115
+
116
+ // Calling again during the 5-minute startup delay should be a no-op
117
+ startHeartbeatTimer(60);
118
+ expect(setTimeoutSpy).toHaveBeenCalledTimes(1);
119
+ expect(setIntervalSpy).not.toHaveBeenCalled();
120
+
121
+ setTimeoutSpy.mockRestore();
122
+ setIntervalSpy.mockRestore();
123
+ });
124
+
125
+ it("guards against double-start after interval is set", () => {
126
+ const setIntervalSpy = vi.spyOn(globalThis, "setInterval");
127
+
128
+ startHeartbeatTimer(60);
129
+ expect(setIntervalSpy).not.toHaveBeenCalled();
130
+
131
+ // Advance past startup delay to create the interval timer
132
+ vi.advanceTimersByTime(5 * 60 * 1000 + 100);
133
+ expect(setIntervalSpy).toHaveBeenCalledTimes(1);
134
+
135
+ // Now try to start again — should be a no-op (interval count stays at 1)
136
+ startHeartbeatTimer(60);
137
+ expect(setIntervalSpy).toHaveBeenCalledTimes(1);
138
+
139
+ setIntervalSpy.mockRestore();
140
+ });
141
+ });
142
+
143
+ describe("forceHeartbeat", () => {
144
+ beforeEach(() => {
145
+ initHeartbeat({ model: "claude-sonnet-4-6" });
146
+ existsSyncMock.mockReturnValue(false);
147
+ readFileSyncMock.mockReset();
148
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
149
+ readFileSyncMock.mockImplementation(((filePath: string) => {
150
+ const p = String(filePath).replace(/\\/g, "/");
151
+ if (p.endsWith("/heartbeat.md"))
152
+ return "heartbeat prompt {{workspace}} {{logsDir}} {{lastRunIso}} {{memoryFile}} {{instructionsFile}} {{runCount}} {{intervalMinutes}}";
153
+ return "null";
154
+ }) as any);
155
+ writeAtomicSyncMock.mockClear();
156
+ queryMock.mockClear();
157
+ });
158
+
159
+ it("writes heartbeat state twice (running then idle) on success", async () => {
160
+ await forceHeartbeat();
161
+
162
+ expect(writeAtomicSyncMock).toHaveBeenCalledTimes(2);
163
+
164
+ const firstCall = JSON.parse(
165
+ writeAtomicSyncMock.mock.calls[0][1] as string,
166
+ );
167
+ expect(firstCall.status).toBe("running");
168
+
169
+ const secondCall = JSON.parse(
170
+ writeAtomicSyncMock.mock.calls[1][1] as string,
171
+ );
172
+ expect(secondCall.status).toBe("idle");
173
+ });
174
+
175
+ it("increments run_count only on success", async () => {
176
+ await forceHeartbeat();
177
+
178
+ const finalState = JSON.parse(
179
+ writeAtomicSyncMock.mock.calls[
180
+ writeAtomicSyncMock.mock.calls.length - 1
181
+ ][1] as string,
182
+ );
183
+ expect(finalState.run_count).toBe(1);
184
+ expect(finalState.status).toBe("idle");
185
+ });
186
+
187
+ it("preserves previous last_run on failure", async () => {
188
+ const previousLastRun = Date.now() - 3600_000;
189
+ existsSyncMock.mockReturnValue(true);
190
+ readFileSyncMock.mockReturnValue(
191
+ JSON.stringify({
192
+ last_run: previousLastRun,
193
+ status: "idle",
194
+ run_count: 5,
195
+ }),
196
+ );
197
+
198
+ // Make agent throw
199
+ queryMock.mockImplementationOnce(async function* () {
200
+ throw new Error("Agent exploded");
201
+ });
202
+
203
+ await expect(forceHeartbeat()).rejects.toThrow("Agent exploded");
204
+
205
+ // The last write should preserve previous last_run and run_count
206
+ const finalState = JSON.parse(
207
+ writeAtomicSyncMock.mock.calls[
208
+ writeAtomicSyncMock.mock.calls.length - 1
209
+ ][1] as string,
210
+ );
211
+ expect(finalState.last_run).toBe(previousLastRun);
212
+ expect(finalState.run_count).toBe(5);
213
+ expect(finalState.status).toBe("idle");
214
+ });
215
+
216
+ it("sets last_started even on failure", async () => {
217
+ existsSyncMock.mockReturnValue(false);
218
+
219
+ queryMock.mockImplementationOnce(async function* () {
220
+ throw new Error("Boom");
221
+ });
222
+
223
+ await expect(forceHeartbeat()).rejects.toThrow("Boom");
224
+
225
+ const finalState = JSON.parse(
226
+ writeAtomicSyncMock.mock.calls[
227
+ writeAtomicSyncMock.mock.calls.length - 1
228
+ ][1] as string,
229
+ );
230
+ expect(finalState.last_started).toBeGreaterThan(0);
231
+ });
232
+
233
+ it("rejects concurrent runs (concurrency guard)", async () => {
234
+ const firstRun = forceHeartbeat().catch(() => {});
235
+
236
+ // The running flag should now be true
237
+ await expect(forceHeartbeat()).rejects.toThrow("Heartbeat already running");
238
+ await firstRun;
239
+ });
240
+
241
+ it("resolves successfully when agent mock yields no messages", async () => {
242
+ await expect(forceHeartbeat()).resolves.toBeUndefined();
243
+ });
244
+ });
245
+
246
+ describe("getHeartbeatStatus", () => {
247
+ it("returns null when no state file exists", () => {
248
+ existsSyncMock.mockReturnValue(false);
249
+ expect(getHeartbeatStatus()).toBeNull();
250
+ });
251
+
252
+ it("returns parsed state when file exists", () => {
253
+ const state = {
254
+ last_run: Date.now(),
255
+ status: "idle",
256
+ run_count: 3,
257
+ };
258
+ existsSyncMock.mockReturnValue(true);
259
+ readFileSyncMock.mockReturnValue(JSON.stringify(state));
260
+ const result = getHeartbeatStatus();
261
+ expect(result?.run_count).toBe(3);
262
+ expect(result?.status).toBe("idle");
263
+ });
264
+
265
+ it("returns null for corrupt JSON", () => {
266
+ existsSyncMock.mockReturnValue(true);
267
+ readFileSyncMock.mockReturnValue("{ invalid json ");
268
+ expect(getHeartbeatStatus()).toBeNull();
269
+ });
270
+
271
+ it("returns null when last_run is not a number", () => {
272
+ existsSyncMock.mockReturnValue(true);
273
+ readFileSyncMock.mockReturnValue(
274
+ JSON.stringify({
275
+ last_run: "not-a-number",
276
+ status: "idle",
277
+ run_count: 0,
278
+ }),
279
+ );
280
+ expect(getHeartbeatStatus()).toBeNull();
281
+ });
282
+
283
+ it("returns null when run_count is not a number", () => {
284
+ existsSyncMock.mockReturnValue(true);
285
+ readFileSyncMock.mockReturnValue(
286
+ JSON.stringify({
287
+ last_run: Date.now(),
288
+ status: "idle",
289
+ run_count: "five",
290
+ }),
291
+ );
292
+ expect(getHeartbeatStatus()).toBeNull();
293
+ });
294
+
295
+ it("returns null when status is invalid", () => {
296
+ existsSyncMock.mockReturnValue(true);
297
+ readFileSyncMock.mockReturnValue(
298
+ JSON.stringify({
299
+ last_run: Date.now(),
300
+ status: "broken",
301
+ run_count: 1,
302
+ }),
303
+ );
304
+ expect(getHeartbeatStatus()).toBeNull();
305
+ });
306
+
307
+ it("returns null when last_run is non-finite", () => {
308
+ existsSyncMock.mockReturnValue(true);
309
+ // 1e309 parses to Infinity, which is typeof number but not finite
310
+ readFileSyncMock.mockReturnValue(
311
+ '{"last_run":1e309,"status":"idle","run_count":0}',
312
+ );
313
+ expect(getHeartbeatStatus()).toBeNull();
314
+ });
315
+ });
316
+
317
+ describe("awaitCurrentRun", () => {
318
+ beforeEach(() => {
319
+ initHeartbeat({ model: "claude-sonnet-4-6" });
320
+ existsSyncMock.mockReturnValue(false);
321
+ readFileSyncMock.mockReset();
322
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
323
+ readFileSyncMock.mockImplementation(((filePath: string) => {
324
+ const p = String(filePath).replace(/\\/g, "/");
325
+ if (p.endsWith("/heartbeat.md"))
326
+ return "heartbeat prompt {{workspace}} {{logsDir}} {{lastRunIso}} {{memoryFile}} {{instructionsFile}} {{runCount}} {{intervalMinutes}}";
327
+ return "null";
328
+ }) as any);
329
+ writeAtomicSyncMock.mockClear();
330
+ });
331
+
332
+ it("resolves immediately when no run is in progress", async () => {
333
+ await expect(awaitCurrentRun()).resolves.toBeUndefined();
334
+ });
335
+
336
+ it("waits for in-flight run to complete", async () => {
337
+ let resolveAgent!: () => void;
338
+ const agentPromise = new Promise<void>((r) => {
339
+ resolveAgent = r;
340
+ });
341
+
342
+ queryMock.mockImplementationOnce(async function* () {
343
+ await agentPromise;
344
+ });
345
+
346
+ const runPromise = forceHeartbeat().catch(() => {});
347
+
348
+ // awaitCurrentRun should not resolve until the agent finishes
349
+ let awaited = false;
350
+ const awaitPromise = awaitCurrentRun().then(() => {
351
+ awaited = true;
352
+ });
353
+
354
+ // Give microtasks a chance to run
355
+ await new Promise((r) => setTimeout(r, 10));
356
+ expect(awaited).toBe(false);
357
+
358
+ // Now resolve the agent
359
+ resolveAgent();
360
+ await awaitPromise;
361
+ await runPromise;
362
+ expect(awaited).toBe(true);
363
+ });
364
+ });