@agentmeshhq/agent 0.1.7 → 0.1.8

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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/dist/__tests__/context.test.d.ts +1 -0
  3. package/dist/__tests__/context.test.js +353 -0
  4. package/dist/__tests__/context.test.js.map +1 -0
  5. package/dist/cli/context.d.ts +4 -0
  6. package/dist/cli/context.js +190 -0
  7. package/dist/cli/context.js.map +1 -0
  8. package/dist/cli/index.js +17 -0
  9. package/dist/cli/index.js.map +1 -1
  10. package/dist/cli/start.d.ts +1 -0
  11. package/dist/cli/start.js +10 -5
  12. package/dist/cli/start.js.map +1 -1
  13. package/dist/context/handoff.d.ts +48 -0
  14. package/dist/context/handoff.js +88 -0
  15. package/dist/context/handoff.js.map +1 -0
  16. package/dist/context/index.d.ts +7 -0
  17. package/dist/context/index.js +8 -0
  18. package/dist/context/index.js.map +1 -0
  19. package/dist/context/schema.d.ts +82 -0
  20. package/dist/context/schema.js +33 -0
  21. package/dist/context/schema.js.map +1 -0
  22. package/dist/context/storage.d.ts +49 -0
  23. package/dist/context/storage.js +172 -0
  24. package/dist/context/storage.js.map +1 -0
  25. package/dist/core/daemon.d.ts +7 -0
  26. package/dist/core/daemon.js +53 -2
  27. package/dist/core/daemon.js.map +1 -1
  28. package/dist/core/heartbeat.d.ts +6 -0
  29. package/dist/core/heartbeat.js +8 -0
  30. package/dist/core/heartbeat.js.map +1 -1
  31. package/dist/core/injector.d.ts +9 -0
  32. package/dist/core/injector.js +55 -3
  33. package/dist/core/injector.js.map +1 -1
  34. package/dist/core/tmux.d.ts +13 -0
  35. package/dist/core/tmux.js +62 -0
  36. package/dist/core/tmux.js.map +1 -1
  37. package/package.json +11 -11
  38. package/src/__tests__/context.test.ts +464 -0
  39. package/src/cli/context.ts +232 -0
  40. package/src/cli/index.ts +17 -0
  41. package/src/cli/start.ts +11 -9
  42. package/src/context/handoff.ts +122 -0
  43. package/src/context/index.ts +8 -0
  44. package/src/context/schema.ts +111 -0
  45. package/src/context/storage.ts +197 -0
  46. package/src/core/daemon.ts +59 -1
  47. package/src/core/heartbeat.ts +13 -0
  48. package/src/core/injector.ts +74 -30
  49. package/src/core/tmux.ts +75 -0
package/src/cli/index.ts CHANGED
@@ -5,6 +5,7 @@ import { Command } from "commander";
5
5
  import pc from "picocolors";
6
6
  import { attach } from "./attach.js";
7
7
  import { configCmd } from "./config.js";
8
+ import { contextCmd } from "./context.js";
8
9
  import { init } from "./init.js";
9
10
  import { list } from "./list.js";
10
11
  import { logs } from "./logs.js";
@@ -46,6 +47,7 @@ program
46
47
  .option("-w, --workdir <path>", "Working directory")
47
48
  .option("-m, --model <model>", "Model identifier")
48
49
  .option("-f, --foreground", "Run in foreground (blocking)")
50
+ .option("--no-context", "Start fresh without restoring previous context")
49
51
  .action(async (options) => {
50
52
  try {
51
53
  await start(options);
@@ -190,4 +192,19 @@ program
190
192
  }
191
193
  });
192
194
 
195
+ program
196
+ .command("context")
197
+ .description("Manage agent context persistence")
198
+ .argument("[action]", "Action: show (default), clear, export, import, list, path")
199
+ .argument("[name]", "Agent name or file path (for import)")
200
+ .option("-o, --output <path>", "Output file path (for export)")
201
+ .action(async (action, name, options) => {
202
+ try {
203
+ await contextCmd(action || "show", name, options);
204
+ } catch (error) {
205
+ console.error(pc.red((error as Error).message));
206
+ process.exit(1);
207
+ }
208
+ });
209
+
193
210
  program.parse();
package/src/cli/start.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { spawn } from "node:child_process";
2
- import { fileURLToPath } from "node:url";
3
2
  import path from "node:path";
4
- import { AgentDaemon } from "../core/daemon.js";
5
- import { loadConfig, getAgentState } from "../config/loader.js";
6
- import { sessionExists, getSessionName } from "../core/tmux.js";
3
+ import { fileURLToPath } from "node:url";
7
4
  import pc from "picocolors";
5
+ import { getAgentState, loadConfig } from "../config/loader.js";
6
+ import { AgentDaemon } from "../core/daemon.js";
7
+ import { getSessionName, sessionExists } from "../core/tmux.js";
8
8
 
9
9
  export interface StartOptions {
10
10
  name: string;
@@ -12,6 +12,7 @@ export interface StartOptions {
12
12
  workdir?: string;
13
13
  model?: string;
14
14
  foreground?: boolean;
15
+ noContext?: boolean;
15
16
  }
16
17
 
17
18
  export async function start(options: StartOptions): Promise<void> {
@@ -40,7 +41,10 @@ export async function start(options: StartOptions): Promise<void> {
40
41
  // If --foreground flag is set, run in foreground (blocking)
41
42
  if (options.foreground) {
42
43
  try {
43
- const daemon = new AgentDaemon(options);
44
+ const daemon = new AgentDaemon({
45
+ ...options,
46
+ restoreContext: !options.noContext,
47
+ });
44
48
  await daemon.start();
45
49
  // Keep process alive
46
50
  await new Promise(() => {});
@@ -55,16 +59,14 @@ export async function start(options: StartOptions): Promise<void> {
55
59
  console.log(`Starting agent "${options.name}" in background...`);
56
60
 
57
61
  // Get the path to this CLI
58
- const cliPath = path.resolve(
59
- path.dirname(fileURLToPath(import.meta.url)),
60
- "../cli/index.js"
61
- );
62
+ const cliPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../cli/index.js");
62
63
 
63
64
  // Build args for the background process
64
65
  const args = ["start", "--name", options.name, "--foreground"];
65
66
  if (options.command) args.push("--command", options.command);
66
67
  if (options.workdir) args.push("--workdir", options.workdir);
67
68
  if (options.model) args.push("--model", options.model);
69
+ if (options.noContext) args.push("--no-context");
68
70
 
69
71
  // Spawn detached background process
70
72
  const child = spawn("node", [cliPath, ...args], {
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Context Handoff Module
3
+ * Functions for sharing context between agents via handoffs
4
+ */
5
+
6
+ import type { AgentContext } from "./schema.js";
7
+ import { loadContext } from "./storage.js";
8
+
9
+ /**
10
+ * Minimal context for handoff (excludes sensitive/large data)
11
+ */
12
+ export interface HandoffContext {
13
+ /** Working directory */
14
+ workdir: string;
15
+ /** Git branch if in a repo */
16
+ gitBranch?: string;
17
+ /** Current goal being worked on */
18
+ currentGoal?: string;
19
+ /** Active tasks (in_progress and pending) */
20
+ activeTasks: Array<{
21
+ content: string;
22
+ status: "in_progress" | "pending";
23
+ priority: string;
24
+ }>;
25
+ /** Recent accomplishments */
26
+ recentAccomplishments: string[];
27
+ /** Key topics from conversation */
28
+ topics: string[];
29
+ /** Any custom context data */
30
+ custom?: Record<string, unknown>;
31
+ }
32
+
33
+ /**
34
+ * Extracts handoff-relevant context from full agent context
35
+ */
36
+ export function extractHandoffContext(context: AgentContext): HandoffContext {
37
+ return {
38
+ workdir: context.workingState.workdir,
39
+ gitBranch: context.workingState.gitBranch,
40
+ currentGoal: context.tasks.currentGoal,
41
+ activeTasks: context.tasks.tasks
42
+ .filter((t) => t.status === "in_progress" || t.status === "pending")
43
+ .map((t) => ({
44
+ content: t.content,
45
+ status: t.status as "in_progress" | "pending",
46
+ priority: t.priority,
47
+ })),
48
+ recentAccomplishments: context.conversation.accomplishments.slice(0, 5),
49
+ topics: context.conversation.topics.slice(0, 10),
50
+ custom: Object.keys(context.custom).length > 0 ? context.custom : undefined,
51
+ };
52
+ }
53
+
54
+ /**
55
+ * Gets handoff context for an agent by ID
56
+ */
57
+ export function getHandoffContextForAgent(agentId: string): HandoffContext | null {
58
+ const context = loadContext(agentId);
59
+ if (!context) {
60
+ return null;
61
+ }
62
+ return extractHandoffContext(context);
63
+ }
64
+
65
+ /**
66
+ * Serializes handoff context to a string for inclusion in API calls
67
+ */
68
+ export function serializeHandoffContext(context: HandoffContext): string {
69
+ return JSON.stringify(context);
70
+ }
71
+
72
+ /**
73
+ * Parses handoff context from a string (received from API)
74
+ */
75
+ export function parseHandoffContext(contextString: string): HandoffContext | null {
76
+ try {
77
+ return JSON.parse(contextString) as HandoffContext;
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Generates a human-readable summary of handoff context
85
+ */
86
+ export function formatHandoffContextSummary(context: HandoffContext): string {
87
+ const lines: string[] = [];
88
+
89
+ if (context.workdir) {
90
+ lines.push(`Working directory: ${context.workdir}`);
91
+ }
92
+ if (context.gitBranch) {
93
+ lines.push(`Git branch: ${context.gitBranch}`);
94
+ }
95
+ if (context.currentGoal) {
96
+ lines.push(`Current goal: ${context.currentGoal}`);
97
+ }
98
+
99
+ if (context.activeTasks.length > 0) {
100
+ lines.push("");
101
+ lines.push("Active tasks:");
102
+ for (const task of context.activeTasks) {
103
+ const icon = task.status === "in_progress" ? ">" : "-";
104
+ lines.push(` ${icon} ${task.content}`);
105
+ }
106
+ }
107
+
108
+ if (context.recentAccomplishments.length > 0) {
109
+ lines.push("");
110
+ lines.push("Recent accomplishments:");
111
+ for (const acc of context.recentAccomplishments) {
112
+ lines.push(` - ${acc}`);
113
+ }
114
+ }
115
+
116
+ if (context.topics.length > 0) {
117
+ lines.push("");
118
+ lines.push(`Topics: ${context.topics.join(", ")}`);
119
+ }
120
+
121
+ return lines.join("\n");
122
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Context Module
3
+ * Agent context persistence for cross-session state management
4
+ */
5
+
6
+ export * from "./handoff.js";
7
+ export * from "./schema.js";
8
+ export * from "./storage.js";
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Agent Context Schema
3
+ * Defines the structure for persisting agent context across sessions
4
+ */
5
+
6
+ export const CONTEXT_VERSION = 1;
7
+ export const CONTEXT_DIR = `${process.env.HOME}/.agentmesh/context`;
8
+
9
+ /**
10
+ * Summary of conversation history for context restoration
11
+ */
12
+ export interface ConversationSummary {
13
+ /** Total messages in the conversation */
14
+ messageCount: number;
15
+ /** Key topics discussed */
16
+ topics: string[];
17
+ /** Summary of what was accomplished */
18
+ accomplishments: string[];
19
+ /** Last 5 user messages (truncated) */
20
+ recentMessages: Array<{
21
+ role: "user" | "assistant";
22
+ content: string;
23
+ timestamp: string;
24
+ }>;
25
+ }
26
+
27
+ /**
28
+ * Current working state of the agent
29
+ */
30
+ export interface WorkingState {
31
+ /** Current working directory */
32
+ workdir: string;
33
+ /** Recently accessed files */
34
+ recentFiles: string[];
35
+ /** Open file paths being edited */
36
+ openFiles: string[];
37
+ /** Git branch if in a repo */
38
+ gitBranch?: string;
39
+ /** Git status summary */
40
+ gitStatus?: string;
41
+ }
42
+
43
+ /**
44
+ * In-progress task state from TodoWrite
45
+ */
46
+ export interface TaskState {
47
+ /** Active tasks */
48
+ tasks: Array<{
49
+ content: string;
50
+ status: "pending" | "in_progress" | "completed" | "cancelled";
51
+ priority: "high" | "medium" | "low";
52
+ }>;
53
+ /** Overall goal being worked on */
54
+ currentGoal?: string;
55
+ }
56
+
57
+ /**
58
+ * Custom key-value store for agent-specific context
59
+ */
60
+ export interface CustomContext {
61
+ [key: string]: unknown;
62
+ }
63
+
64
+ /**
65
+ * Full agent context structure
66
+ */
67
+ export interface AgentContext {
68
+ /** Schema version for migration support */
69
+ version: number;
70
+ /** Agent ID this context belongs to */
71
+ agentId: string;
72
+ /** Agent name */
73
+ agentName: string;
74
+ /** When this context was last saved */
75
+ savedAt: string;
76
+ /** Conversation summary */
77
+ conversation: ConversationSummary;
78
+ /** Current working state */
79
+ workingState: WorkingState;
80
+ /** Task state */
81
+ tasks: TaskState;
82
+ /** Custom context data */
83
+ custom: CustomContext;
84
+ }
85
+
86
+ /**
87
+ * Creates an empty context for a new agent
88
+ */
89
+ export function createEmptyContext(agentId: string, agentName: string): AgentContext {
90
+ return {
91
+ version: CONTEXT_VERSION,
92
+ agentId,
93
+ agentName,
94
+ savedAt: new Date().toISOString(),
95
+ conversation: {
96
+ messageCount: 0,
97
+ topics: [],
98
+ accomplishments: [],
99
+ recentMessages: [],
100
+ },
101
+ workingState: {
102
+ workdir: process.cwd(),
103
+ recentFiles: [],
104
+ openFiles: [],
105
+ },
106
+ tasks: {
107
+ tasks: [],
108
+ },
109
+ custom: {},
110
+ };
111
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Context Storage Module
3
+ * Handles saving and loading agent context to/from disk
4
+ */
5
+
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import { type AgentContext, CONTEXT_DIR, CONTEXT_VERSION, createEmptyContext } from "./schema.js";
9
+
10
+ /**
11
+ * Ensures the context directory exists
12
+ */
13
+ export function ensureContextDir(): void {
14
+ if (!fs.existsSync(CONTEXT_DIR)) {
15
+ fs.mkdirSync(CONTEXT_DIR, { recursive: true });
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Gets the context file path for an agent
21
+ */
22
+ export function getContextPath(agentId: string): string {
23
+ return path.join(CONTEXT_DIR, `${agentId}.json`);
24
+ }
25
+
26
+ /**
27
+ * Saves agent context to disk
28
+ */
29
+ export function saveContext(context: AgentContext): void {
30
+ ensureContextDir();
31
+ const contextPath = getContextPath(context.agentId);
32
+
33
+ // Update savedAt timestamp
34
+ context.savedAt = new Date().toISOString();
35
+
36
+ fs.writeFileSync(contextPath, JSON.stringify(context, null, 2));
37
+ }
38
+
39
+ /**
40
+ * Loads agent context from disk
41
+ * Returns null if context doesn't exist or is invalid
42
+ */
43
+ export function loadContext(agentId: string): AgentContext | null {
44
+ const contextPath = getContextPath(agentId);
45
+
46
+ try {
47
+ if (!fs.existsSync(contextPath)) {
48
+ return null;
49
+ }
50
+
51
+ const content = fs.readFileSync(contextPath, "utf-8");
52
+ const context = JSON.parse(content) as AgentContext;
53
+
54
+ // Validate version
55
+ if (context.version !== CONTEXT_VERSION) {
56
+ // In the future, we can migrate old versions here
57
+ console.warn(`Context version mismatch: expected ${CONTEXT_VERSION}, got ${context.version}`);
58
+ return null;
59
+ }
60
+
61
+ return context;
62
+ } catch (error) {
63
+ console.error(`Failed to load context for agent ${agentId}:`, error);
64
+ return null;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Loads context or creates a new empty one
70
+ */
71
+ export function loadOrCreateContext(agentId: string, agentName: string): AgentContext {
72
+ const existing = loadContext(agentId);
73
+ if (existing) {
74
+ return existing;
75
+ }
76
+ return createEmptyContext(agentId, agentName);
77
+ }
78
+
79
+ /**
80
+ * Deletes agent context from disk
81
+ */
82
+ export function deleteContext(agentId: string): boolean {
83
+ const contextPath = getContextPath(agentId);
84
+
85
+ try {
86
+ if (fs.existsSync(contextPath)) {
87
+ fs.unlinkSync(contextPath);
88
+ return true;
89
+ }
90
+ return false;
91
+ } catch (error) {
92
+ console.error(`Failed to delete context for agent ${agentId}:`, error);
93
+ return false;
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Lists all saved context files
99
+ */
100
+ export function listContexts(): Array<{ agentId: string; savedAt: string }> {
101
+ ensureContextDir();
102
+
103
+ try {
104
+ const files = fs.readdirSync(CONTEXT_DIR);
105
+ const contexts: Array<{ agentId: string; savedAt: string }> = [];
106
+
107
+ for (const file of files) {
108
+ if (!file.endsWith(".json")) continue;
109
+
110
+ const agentId = file.replace(".json", "");
111
+ const context = loadContext(agentId);
112
+ if (context) {
113
+ contexts.push({
114
+ agentId,
115
+ savedAt: context.savedAt,
116
+ });
117
+ }
118
+ }
119
+
120
+ return contexts.sort((a, b) => new Date(b.savedAt).getTime() - new Date(a.savedAt).getTime());
121
+ } catch {
122
+ return [];
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Updates specific fields in the context
128
+ */
129
+ export function updateContext(
130
+ agentId: string,
131
+ updates: Partial<Omit<AgentContext, "version" | "agentId" | "savedAt">>,
132
+ ): AgentContext | null {
133
+ const context = loadContext(agentId);
134
+ if (!context) {
135
+ return null;
136
+ }
137
+
138
+ const updated: AgentContext = {
139
+ ...context,
140
+ ...updates,
141
+ // Preserve these fields
142
+ version: CONTEXT_VERSION,
143
+ agentId: context.agentId,
144
+ savedAt: new Date().toISOString(),
145
+ };
146
+
147
+ saveContext(updated);
148
+ return updated;
149
+ }
150
+
151
+ /**
152
+ * Exports context to a specified file path
153
+ */
154
+ export function exportContext(agentId: string, outputPath: string): boolean {
155
+ const context = loadContext(agentId);
156
+ if (!context) {
157
+ return false;
158
+ }
159
+
160
+ try {
161
+ fs.writeFileSync(outputPath, JSON.stringify(context, null, 2));
162
+ return true;
163
+ } catch (error) {
164
+ console.error(`Failed to export context:`, error);
165
+ return false;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Imports context from a file path
171
+ */
172
+ export function importContext(inputPath: string): AgentContext | null {
173
+ try {
174
+ if (!fs.existsSync(inputPath)) {
175
+ console.error(`File not found: ${inputPath}`);
176
+ return null;
177
+ }
178
+
179
+ const content = fs.readFileSync(inputPath, "utf-8");
180
+ const context = JSON.parse(content) as AgentContext;
181
+
182
+ // Validate required fields
183
+ if (!context.agentId || !context.agentName) {
184
+ console.error("Invalid context file: missing agentId or agentName");
185
+ return null;
186
+ }
187
+
188
+ // Update version and save
189
+ context.version = CONTEXT_VERSION;
190
+ saveContext(context);
191
+
192
+ return context;
193
+ } catch (error) {
194
+ console.error(`Failed to import context:`, error);
195
+ return null;
196
+ }
197
+ }
@@ -6,10 +6,12 @@ import {
6
6
  updateAgentInState,
7
7
  } from "../config/loader.js";
8
8
  import type { AgentConfig, Config } from "../config/schema.js";
9
+ import { loadContext, loadOrCreateContext, saveContext } from "../context/index.js";
9
10
  import { Heartbeat } from "./heartbeat.js";
10
- import { handleWebSocketEvent, injectStartupMessage } from "./injector.js";
11
+ import { handleWebSocketEvent, injectRestoredContext, injectStartupMessage } from "./injector.js";
11
12
  import { checkInbox, registerAgent } from "./registry.js";
12
13
  import {
14
+ captureSessionContext,
13
15
  createSession,
14
16
  destroySession,
15
17
  getSessionName,
@@ -24,6 +26,8 @@ export interface DaemonOptions {
24
26
  workdir?: string;
25
27
  model?: string;
26
28
  daemonize?: boolean;
29
+ /** Whether to restore context from previous session (default: true) */
30
+ restoreContext?: boolean;
27
31
  }
28
32
 
29
33
  export class AgentDaemon {
@@ -35,6 +39,7 @@ export class AgentDaemon {
35
39
  private token: string | null = null;
36
40
  private agentId: string | null = null;
37
41
  private isRunning = false;
42
+ private shouldRestoreContext: boolean;
38
43
 
39
44
  constructor(options: DaemonOptions) {
40
45
  const config = loadConfig();
@@ -44,6 +49,7 @@ export class AgentDaemon {
44
49
 
45
50
  this.config = config;
46
51
  this.agentName = options.name;
52
+ this.shouldRestoreContext = options.restoreContext !== false;
47
53
 
48
54
  // Find or create agent config
49
55
  let agentConfig = config.agents.find((a) => a.name === options.name);
@@ -141,6 +147,11 @@ export class AgentDaemon {
141
147
  onError: (error) => {
142
148
  console.error("Heartbeat error:", error.message);
143
149
  },
150
+ onContextSave: () => {
151
+ // Periodically save context (every 5 heartbeats = ~2.5 minutes)
152
+ this.saveAgentContext();
153
+ },
154
+ contextSaveFrequency: 5,
144
155
  onTokenRefresh: (newToken) => {
145
156
  this.token = newToken;
146
157
  // Update state file
@@ -210,6 +221,18 @@ export class AgentDaemon {
210
221
  injectStartupMessage(this.agentName, 0);
211
222
  }
212
223
 
224
+ // Restore context from previous session
225
+ if (this.shouldRestoreContext && this.agentId) {
226
+ console.log("Checking for previous context...");
227
+ const savedContext = loadContext(this.agentId);
228
+ if (savedContext) {
229
+ console.log(`Restoring context from ${savedContext.savedAt}`);
230
+ // Wait a moment for the session to be ready
231
+ await new Promise((resolve) => setTimeout(resolve, 1000));
232
+ injectRestoredContext(this.agentName, savedContext);
233
+ }
234
+ }
235
+
213
236
  this.isRunning = true;
214
237
 
215
238
  console.log(`
@@ -235,6 +258,12 @@ Nudge agent:
235
258
 
236
259
  this.isRunning = false;
237
260
 
261
+ // Save context before stopping
262
+ if (this.agentId) {
263
+ console.log("Saving agent context...");
264
+ this.saveAgentContext();
265
+ }
266
+
238
267
  // Stop heartbeat
239
268
  if (this.heartbeat) {
240
269
  this.heartbeat.stop();
@@ -256,4 +285,33 @@ Nudge agent:
256
285
  console.log("Agent stopped.");
257
286
  process.exit(0);
258
287
  }
288
+
289
+ /**
290
+ * Saves the current agent context to disk
291
+ */
292
+ private saveAgentContext(): void {
293
+ if (!this.agentId) return;
294
+
295
+ try {
296
+ // Load existing context or create new
297
+ const context = loadOrCreateContext(this.agentId, this.agentName);
298
+
299
+ // Capture current session state
300
+ const sessionContext = captureSessionContext(this.agentName);
301
+ if (sessionContext) {
302
+ context.workingState = {
303
+ ...context.workingState,
304
+ workdir: sessionContext.workdir,
305
+ gitBranch: sessionContext.gitBranch,
306
+ gitStatus: sessionContext.gitStatus,
307
+ };
308
+ }
309
+
310
+ // Save updated context
311
+ saveContext(context);
312
+ console.log(`Context saved for agent ${this.agentName}`);
313
+ } catch (error) {
314
+ console.error("Failed to save agent context:", error);
315
+ }
316
+ }
259
317
  }
@@ -13,16 +13,23 @@ export interface HeartbeatConfig {
13
13
  workspace: string;
14
14
  onError?: (error: Error) => void;
15
15
  onTokenRefresh?: (newToken: string) => void;
16
+ /** Called periodically to save agent context (every N heartbeats) */
17
+ onContextSave?: () => void;
18
+ /** How many heartbeats between context saves (default: 5) */
19
+ contextSaveFrequency?: number;
16
20
  }
17
21
 
18
22
  export class Heartbeat {
19
23
  private config: HeartbeatConfig;
20
24
  private currentToken: string;
21
25
  private intervalId: NodeJS.Timeout | null = null;
26
+ private heartbeatCount = 0;
27
+ private contextSaveFrequency: number;
22
28
 
23
29
  constructor(config: HeartbeatConfig) {
24
30
  this.config = config;
25
31
  this.currentToken = config.token;
32
+ this.contextSaveFrequency = config.contextSaveFrequency ?? 5;
26
33
  }
27
34
 
28
35
  start(): void {
@@ -78,6 +85,12 @@ export class Heartbeat {
78
85
  }
79
86
  throw new Error(`Heartbeat failed: ${response.status}`);
80
87
  }
88
+
89
+ // Periodically save context
90
+ this.heartbeatCount++;
91
+ if (this.config.onContextSave && this.heartbeatCount % this.contextSaveFrequency === 0) {
92
+ this.config.onContextSave();
93
+ }
81
94
  } catch (error) {
82
95
  this.config.onError?.(error as Error);
83
96
  }