@phren/agent 0.1.8 → 0.1.10

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 (58) hide show
  1. package/dist/commands/info.js +1 -0
  2. package/dist/commands/model.js +5 -4
  3. package/dist/commands/session.js +24 -2
  4. package/dist/commands.js +36 -1
  5. package/dist/config.js +27 -11
  6. package/dist/cost.js +11 -74
  7. package/dist/index.js +92 -35
  8. package/dist/mcp-client.js +4 -2
  9. package/dist/memory/context.js +56 -24
  10. package/dist/memory/session.js +21 -88
  11. package/dist/models.js +390 -0
  12. package/dist/multi/agent-types.js +170 -0
  13. package/dist/multi/child-entry.js +248 -78
  14. package/dist/multi/coordinator.js +69 -1
  15. package/dist/multi/diff-renderer.js +193 -17
  16. package/dist/multi/markdown.js +49 -23
  17. package/dist/multi/model-picker.js +12 -21
  18. package/dist/multi/multi-events.js +17 -0
  19. package/dist/multi/multi-render.js +1 -0
  20. package/dist/multi/provider-manager.js +23 -13
  21. package/dist/multi/spawner.js +84 -7
  22. package/dist/multi/syntax-highlight.js +64 -48
  23. package/dist/multi/worktree.js +43 -0
  24. package/dist/package-metadata.js +11 -0
  25. package/dist/permissions/checker.js +21 -1
  26. package/dist/providers/codex-auth.js +48 -34
  27. package/dist/providers/codex.js +110 -40
  28. package/dist/providers/ollama.js +5 -4
  29. package/dist/providers/openrouter.js +12 -5
  30. package/dist/providers/resolve.js +50 -32
  31. package/dist/providers/types.js +0 -1
  32. package/dist/repl.js +19 -34
  33. package/dist/tools/grep.js +111 -23
  34. package/dist/tools/mcp-resources.js +32 -0
  35. package/dist/tools/registry.js +13 -2
  36. package/dist/tools/shell.js +101 -3
  37. package/dist/tools/skill.js +44 -0
  38. package/dist/tools/spawn-agent.js +158 -0
  39. package/dist/tui/ansi.js +15 -11
  40. package/dist/tui/components/App.js +180 -20
  41. package/dist/tui/components/Banner.js +7 -4
  42. package/dist/tui/components/InputArea.js +54 -12
  43. package/dist/tui/components/PhrenInput.js +329 -0
  44. package/dist/tui/components/StatusBar.js +3 -1
  45. package/dist/tui/components/SteerQueue.js +4 -2
  46. package/dist/tui/components/ThinkingIndicator.js +12 -11
  47. package/dist/tui/components/ToolCall.js +17 -11
  48. package/dist/tui/components/ToolSpinner.js +13 -0
  49. package/dist/tui/hooks/useKeyboardShortcuts.js +65 -24
  50. package/dist/tui/hooks/useSearch.js +47 -0
  51. package/dist/tui/hooks/useSlashCommands.js +16 -19
  52. package/dist/tui/ink-entry.js +317 -18
  53. package/dist/tui/mouse.js +71 -0
  54. package/dist/tui/terminal-control.js +62 -0
  55. package/dist/tui/themes.js +398 -0
  56. package/dist/tui/tool-render.js +12 -1
  57. package/dist/tui.js +2 -1
  58. package/package.json +1 -3
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Agent type system — built-in and custom agent type definitions.
3
+ *
4
+ * Agent types restrict or configure child agents by limiting their tool set
5
+ * and injecting role-specific system prompt prefixes.
6
+ */
7
+ import { readFileSync, readdirSync, existsSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { homedir } from "node:os";
10
+ // ── Built-in agent types ───────────────────────────────────────────────────
11
+ export const BUILTIN_AGENT_TYPES = new Map([
12
+ [
13
+ "explore",
14
+ {
15
+ name: "explore",
16
+ description: "Read-only exploration agent for searching and reading code.",
17
+ allowedTools: [
18
+ "read_file",
19
+ "glob",
20
+ "grep",
21
+ "phren_search",
22
+ "git_status",
23
+ "git_diff",
24
+ ],
25
+ systemPromptPrefix: "You are a read-only exploration agent. You can search and read code but cannot modify files.",
26
+ },
27
+ ],
28
+ [
29
+ "plan",
30
+ {
31
+ name: "plan",
32
+ description: "Research and planning agent that can read code and capture findings.",
33
+ allowedTools: [
34
+ "read_file",
35
+ "glob",
36
+ "grep",
37
+ "phren_search",
38
+ "phren_add_finding",
39
+ "git_status",
40
+ "git_diff",
41
+ ],
42
+ systemPromptPrefix: "You are a planning agent. Research the codebase and create a detailed implementation plan.",
43
+ },
44
+ ],
45
+ [
46
+ "general",
47
+ {
48
+ name: "general",
49
+ description: "General-purpose agent with access to all tools.",
50
+ },
51
+ ],
52
+ ]);
53
+ // ── Custom agent types from filesystem ─────────────────────────────────────
54
+ const DEFAULT_AGENT_TYPES_DIR = join(homedir(), ".phren-agent", "agents");
55
+ /**
56
+ * Load custom agent types from .md files in the given directory.
57
+ * Each file should have YAML frontmatter between --- delimiters.
58
+ * Custom types override builtins with the same name.
59
+ */
60
+ export function loadCustomAgentTypes(dir) {
61
+ const merged = new Map(BUILTIN_AGENT_TYPES);
62
+ const agentDir = dir ?? DEFAULT_AGENT_TYPES_DIR;
63
+ if (!existsSync(agentDir))
64
+ return merged;
65
+ let files;
66
+ try {
67
+ files = readdirSync(agentDir).filter((f) => f.endsWith(".md"));
68
+ }
69
+ catch {
70
+ return merged;
71
+ }
72
+ for (const file of files) {
73
+ try {
74
+ const content = readFileSync(join(agentDir, file), "utf-8");
75
+ const parsed = parseFrontmatter(content);
76
+ if (parsed && parsed.name) {
77
+ merged.set(parsed.name, parsed);
78
+ }
79
+ }
80
+ catch {
81
+ // Skip malformed files
82
+ }
83
+ }
84
+ return merged;
85
+ }
86
+ /**
87
+ * Parse YAML-like frontmatter from a markdown file.
88
+ * Expects content between --- delimiters with key: value lines.
89
+ */
90
+ function parseFrontmatter(content) {
91
+ const lines = content.split("\n");
92
+ if (lines[0]?.trim() !== "---")
93
+ return null;
94
+ let endIdx = -1;
95
+ for (let i = 1; i < lines.length; i++) {
96
+ if (lines[i]?.trim() === "---") {
97
+ endIdx = i;
98
+ break;
99
+ }
100
+ }
101
+ if (endIdx === -1)
102
+ return null;
103
+ const frontmatterLines = lines.slice(1, endIdx);
104
+ const raw = {};
105
+ for (const line of frontmatterLines) {
106
+ const colonIdx = line.indexOf(":");
107
+ if (colonIdx === -1)
108
+ continue;
109
+ const key = line.slice(0, colonIdx).trim();
110
+ const value = line.slice(colonIdx + 1).trim();
111
+ if (key && value) {
112
+ raw[key] = value;
113
+ }
114
+ }
115
+ if (!raw["name"])
116
+ return null;
117
+ const def = {
118
+ name: raw["name"],
119
+ description: raw["description"] ?? "",
120
+ };
121
+ if (raw["model"])
122
+ def.model = raw["model"];
123
+ if (raw["maxTurns"])
124
+ def.maxTurns = parseInt(raw["maxTurns"], 10);
125
+ if (raw["allowedTools"]) {
126
+ def.allowedTools = raw["allowedTools"]
127
+ .split(",")
128
+ .map((t) => t.trim())
129
+ .filter(Boolean);
130
+ }
131
+ if (raw["disallowedTools"]) {
132
+ def.disallowedTools = raw["disallowedTools"]
133
+ .split(",")
134
+ .map((t) => t.trim())
135
+ .filter(Boolean);
136
+ }
137
+ if (raw["systemPromptPrefix"]) {
138
+ def.systemPromptPrefix = raw["systemPromptPrefix"];
139
+ }
140
+ return def;
141
+ }
142
+ // ── Lookup ─────────────────────────────────────────────────────────────────
143
+ /**
144
+ * Look up an agent type by name from builtins + custom types.
145
+ */
146
+ export function getAgentType(name) {
147
+ const all = loadCustomAgentTypes();
148
+ return all.get(name) ?? null;
149
+ }
150
+ // ── Apply to registry ──────────────────────────────────────────────────────
151
+ /**
152
+ * Apply an agent type's tool restrictions to a ToolRegistry.
153
+ * - If allowedTools is set, remove all tools not in the list.
154
+ * - If disallowedTools is set, remove those tools.
155
+ */
156
+ export function applyAgentType(registry, agentType) {
157
+ if (agentType.allowedTools) {
158
+ const allowed = new Set(agentType.allowedTools);
159
+ for (const name of registry.toolNames()) {
160
+ if (!allowed.has(name)) {
161
+ registry.remove(name);
162
+ }
163
+ }
164
+ }
165
+ if (agentType.disallowedTools) {
166
+ for (const name of agentType.disallowedTools) {
167
+ registry.remove(name);
168
+ }
169
+ }
170
+ }
@@ -1,30 +1,31 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Child agent entry point — standalone process that:
3
+ * Child agent entry point — persistent process that:
4
4
  * 1. Receives SpawnPayload via IPC from parent
5
- * 2. Resolves the LLM provider
6
- * 3. Registers the standard tool set
7
- * 4. Runs the agent loop with TurnHooks that serialize events back via process.send()
8
- * 5. Sends a final "done" message with the result
5
+ * 2. Resolves the LLM provider and registers tools
6
+ * 3. Runs the agent loop
7
+ * 4. Goes idle after task completion — stays alive waiting for messages
8
+ * 5. Wakes on WakeMessage or DeliverMessage to continue
9
+ * 6. Shuts down gracefully on ShutdownRequest
9
10
  */
10
11
  import { resolveProvider } from "../providers/resolve.js";
11
12
  import { ToolRegistry } from "../tools/registry.js";
12
13
  import { readFileTool } from "../tools/read-file.js";
13
14
  import { writeFileTool } from "../tools/write-file.js";
14
15
  import { editFileTool } from "../tools/edit-file.js";
15
- import { shellTool } from "../tools/shell.js";
16
+ import { shellTool, taskOutputTool, taskStopTool } from "../tools/shell.js";
16
17
  import { globTool } from "../tools/glob.js";
17
18
  import { grepTool } from "../tools/grep.js";
18
19
  import { createPhrenSearchTool } from "../tools/phren-search.js";
19
20
  import { createPhrenFindingTool } from "../tools/phren-finding.js";
20
21
  import { createPhrenGetTasksTool, createPhrenCompleteTaskTool } from "../tools/phren-tasks.js";
22
+ import { createSkillTool } from "../tools/skill.js";
21
23
  import { gitStatusTool, gitDiffTool, gitCommitTool } from "../tools/git.js";
22
- import { buildPhrenContext, buildContextSnippet } from "../memory/context.js";
23
- import { startSession, endSession, getPriorSummary } from "../memory/session.js";
24
- import { loadProjectContext } from "../memory/project-context.js";
25
- import { buildSystemPrompt } from "../system-prompt.js";
24
+ import { buildPhrenContext } from "../memory/context.js";
25
+ import { startSession, endSession } from "../memory/session.js";
26
26
  import { runAgent } from "../agent-loop.js";
27
27
  import { createCostTracker } from "../cost.js";
28
+ import { getAgentType, applyAgentType } from "./agent-types.js";
28
29
  /** Send a typed message to the parent process. */
29
30
  function send(msg) {
30
31
  if (process.send) {
@@ -54,46 +55,45 @@ function createIpcHooks(agentId) {
54
55
  },
55
56
  };
56
57
  }
57
- /** Run the agent with the given spawn payload. */
58
- async function runChildAgent(payload) {
59
- const { agentId, task, cwd, provider: providerName, model, project, permissions, maxTurns, budget, plan, verbose } = payload;
60
- // Set cwd
61
- process.chdir(cwd);
58
+ /** Build a lightweight system prompt for child agents. No "search memory first" forcing. */
59
+ function buildChildPrompt(task) {
60
+ return [
61
+ "You are a team agent. You have coding tools available but only use them when the task requires it.",
62
+ "If someone asks you a question or sends a conversational message, just respond directly — do NOT search, read files, or call tools unless the task explicitly requires code work.",
63
+ "When given a coding task, use your tools effectively: read files, make edits, run commands.",
64
+ "Be direct and concise.",
65
+ "",
66
+ `Your assignment: ${task}`,
67
+ ].join("\n");
68
+ }
69
+ /** Initialize the persistent agent state from the spawn payload. */
70
+ async function initAgentState(payload) {
71
+ const { agentId, task: _task, cwd, provider: providerName, model, project, permissions, maxTurns, budget, plan, verbose } = payload;
72
+ // Set cwd (use worktree path if provided)
73
+ process.chdir(payload.worktreePath ?? cwd);
62
74
  // Resolve LLM provider
63
- let provider;
64
- try {
65
- provider = resolveProvider(providerName, model);
66
- }
67
- catch (err) {
68
- send({ type: "error", agentId, error: err instanceof Error ? err.message : String(err) });
69
- process.exit(1);
70
- }
71
- // Build phren context
75
+ const provider = resolveProvider(providerName, model);
76
+ // Child agents get a lightweight prompt — no "search memory first" forcing
77
+ const systemPrompt = buildChildPrompt(_task);
78
+ // Quick phren init — just resolve context, skip slow FTS5 search
79
+ // Child agents call phren_search themselves when they actually need it
72
80
  const phrenCtx = await buildPhrenContext(project);
73
- let contextSnippet = "";
74
- let priorSummary = null;
75
81
  let sessionId = null;
76
82
  if (phrenCtx) {
77
- contextSnippet = await buildContextSnippet(phrenCtx, task);
78
- priorSummary = getPriorSummary(phrenCtx);
79
83
  sessionId = startSession(phrenCtx);
80
- const projectCtx = loadProjectContext(phrenCtx);
81
- if (projectCtx) {
82
- contextSnippet += `\n\n## Agent context (${phrenCtx.project})\n\n${projectCtx}`;
83
- }
84
84
  }
85
- const systemPrompt = buildSystemPrompt(contextSnippet, priorSummary);
86
- // Register tools
87
85
  const registry = new ToolRegistry();
88
86
  registry.setPermissions({
89
87
  mode: permissions,
90
88
  allowedPaths: [],
91
- projectRoot: cwd,
89
+ projectRoot: payload.worktreePath ?? cwd,
92
90
  });
93
91
  registry.register(readFileTool);
94
92
  registry.register(writeFileTool);
95
93
  registry.register(editFileTool);
96
94
  registry.register(shellTool);
95
+ registry.register(taskOutputTool);
96
+ registry.register(taskStopTool);
97
97
  registry.register(globTool);
98
98
  registry.register(grepTool);
99
99
  if (phrenCtx) {
@@ -101,69 +101,239 @@ async function runChildAgent(payload) {
101
101
  registry.register(createPhrenFindingTool(phrenCtx, sessionId));
102
102
  registry.register(createPhrenGetTasksTool(phrenCtx));
103
103
  registry.register(createPhrenCompleteTaskTool(phrenCtx, sessionId));
104
+ registry.register(createSkillTool(phrenCtx));
104
105
  }
105
106
  registry.register(gitStatusTool);
106
107
  registry.register(gitDiffTool);
107
108
  registry.register(gitCommitTool);
109
+ // Apply agent type restrictions (tool allow/disallow lists, prompt prefix)
110
+ if (payload.agentType) {
111
+ const typeDef = getAgentType(payload.agentType);
112
+ if (typeDef) {
113
+ applyAgentType(registry, typeDef);
114
+ }
115
+ }
108
116
  // Cost tracker
109
- const modelName = model ?? provider.name;
110
- const costTracker = createCostTracker(modelName, budget);
111
- const config = {
117
+ const modelName = provider.model ?? model ?? provider.name;
118
+ const costTracker = createCostTracker(modelName, budget, provider.name);
119
+ return {
120
+ agentId,
112
121
  provider,
113
122
  registry,
114
123
  systemPrompt,
115
- maxTurns,
116
- verbose,
117
124
  phrenCtx,
125
+ sessionId,
118
126
  costTracker,
127
+ maxTurns,
128
+ verbose,
119
129
  plan,
120
130
  hooks: createIpcHooks(agentId),
131
+ pendingDms: [],
132
+ taskCount: 0,
133
+ };
134
+ }
135
+ /** Run a single task. Returns the result. */
136
+ async function runTask(state, task) {
137
+ const config = {
138
+ provider: state.provider,
139
+ registry: state.registry,
140
+ systemPrompt: state.systemPrompt,
141
+ maxTurns: state.maxTurns,
142
+ verbose: state.verbose,
143
+ phrenCtx: state.phrenCtx,
144
+ costTracker: state.costTracker,
145
+ plan: state.plan && state.taskCount === 0, // Plan mode only on first task
146
+ hooks: state.hooks,
121
147
  };
122
- // Run the agent
123
- try {
124
- const result = await runAgent(task, config);
125
- // End phren session
126
- if (phrenCtx && sessionId) {
127
- const summary = result.finalText.slice(0, 500);
128
- endSession(phrenCtx, sessionId, summary);
148
+ const result = await runAgent(task, config);
149
+ state.taskCount++;
150
+ return {
151
+ finalText: result.finalText,
152
+ turns: result.turns,
153
+ toolCalls: result.toolCalls,
154
+ totalCost: result.totalCost,
155
+ };
156
+ }
157
+ /** Enter idle state — notify parent, wait for wake/shutdown/message. */
158
+ function goIdle(state, reason) {
159
+ // Flush pending DM summaries
160
+ const dmSummaries = state.pendingDms.length > 0 ? [...state.pendingDms] : undefined;
161
+ state.pendingDms = [];
162
+ send({
163
+ type: "idle",
164
+ agentId: state.agentId,
165
+ idleReason: reason,
166
+ dmSummaries,
167
+ });
168
+ }
169
+ /** Clean up and exit. */
170
+ function shutdown(state) {
171
+ // End phren session
172
+ if (state.phrenCtx && state.sessionId) {
173
+ endSession(state.phrenCtx, state.sessionId, `Agent shut down after ${state.taskCount} tasks`);
174
+ }
175
+ send({ type: "shutdown_approved", agentId: state.agentId });
176
+ process.exit(0);
177
+ }
178
+ // ── Main: persistent event loop ────────────────────────────────────────────
179
+ let agentState = null;
180
+ let isRunning = false;
181
+ /** Queue of messages received while the agent was busy running a task. */
182
+ const messageQueue = [];
183
+ async function handleMessage(msg) {
184
+ if (msg.type === "spawn") {
185
+ // Initial spawn — initialize state and run first task
186
+ try {
187
+ agentState = await initAgentState(msg);
188
+ }
189
+ catch (err) {
190
+ send({ type: "error", agentId: msg.agentId, error: err instanceof Error ? err.message : String(err) });
191
+ process.exit(1);
129
192
  }
130
- send({
131
- type: "done",
132
- agentId,
133
- result: {
134
- finalText: result.finalText,
135
- turns: result.turns,
136
- toolCalls: result.toolCalls,
137
- totalCost: result.totalCost,
138
- },
139
- });
193
+ isRunning = true;
194
+ try {
195
+ const result = await runTask(agentState, msg.task);
196
+ // Send done event (task completed, but process stays alive)
197
+ send({
198
+ type: "done",
199
+ agentId: agentState.agentId,
200
+ result,
201
+ });
202
+ isRunning = false;
203
+ // Process any queued messages before going idle
204
+ await drainQueue();
205
+ // Go idle if not already running another task
206
+ if (!isRunning) {
207
+ goIdle(agentState, "task_complete");
208
+ }
209
+ }
210
+ catch (err) {
211
+ isRunning = false;
212
+ if (agentState.phrenCtx && agentState.sessionId) {
213
+ endSession(agentState.phrenCtx, agentState.sessionId, `Error: ${err instanceof Error ? err.message : String(err)}`);
214
+ }
215
+ send({
216
+ type: "error",
217
+ agentId: agentState.agentId,
218
+ error: err instanceof Error ? err.message : String(err),
219
+ });
220
+ // Don't exit on error — go idle so parent can send new work or shutdown
221
+ goIdle(agentState, "available");
222
+ }
223
+ return;
224
+ }
225
+ if (!agentState) {
226
+ // Not initialized yet — ignore
227
+ return;
140
228
  }
141
- catch (err) {
142
- if (phrenCtx && sessionId) {
143
- endSession(phrenCtx, sessionId, `Error: ${err instanceof Error ? err.message : String(err)}`);
229
+ switch (msg.type) {
230
+ case "wake": {
231
+ if (isRunning) {
232
+ messageQueue.push(msg);
233
+ return;
234
+ }
235
+ isRunning = true;
236
+ const task = msg.task ?? msg.message ?? "Continue working";
237
+ try {
238
+ const result = await runTask(agentState, task);
239
+ send({ type: "done", agentId: agentState.agentId, result });
240
+ isRunning = false;
241
+ await drainQueue();
242
+ if (!isRunning)
243
+ goIdle(agentState, "task_complete");
244
+ }
245
+ catch (err) {
246
+ isRunning = false;
247
+ send({ type: "error", agentId: agentState.agentId, error: err instanceof Error ? err.message : String(err) });
248
+ goIdle(agentState, "available");
249
+ }
250
+ break;
251
+ }
252
+ case "deliver_message": {
253
+ if (isRunning) {
254
+ // Record DM for later idle notification
255
+ agentState.pendingDms.push({
256
+ from: msg.from,
257
+ content: msg.content,
258
+ timestamp: new Date().toISOString(),
259
+ });
260
+ // Also queue it as a wake message for when current task finishes
261
+ messageQueue.push({ type: "wake", message: `Message from ${msg.from}: ${msg.content}`, from: msg.from });
262
+ return;
263
+ }
264
+ // Not running — treat as a wake message
265
+ isRunning = true;
266
+ const wakeTask = `Message from ${msg.from}: ${msg.content}`;
267
+ try {
268
+ const result = await runTask(agentState, wakeTask);
269
+ send({ type: "done", agentId: agentState.agentId, result });
270
+ isRunning = false;
271
+ await drainQueue();
272
+ if (!isRunning)
273
+ goIdle(agentState, "task_complete");
274
+ }
275
+ catch (err) {
276
+ isRunning = false;
277
+ send({ type: "error", agentId: agentState.agentId, error: err instanceof Error ? err.message : String(err) });
278
+ goIdle(agentState, "available");
279
+ }
280
+ break;
281
+ }
282
+ case "cancel": {
283
+ // Hard cancel — exit immediately
284
+ if (agentState.phrenCtx && agentState.sessionId) {
285
+ endSession(agentState.phrenCtx, agentState.sessionId, "Cancelled by parent");
286
+ }
287
+ process.exit(130);
288
+ break;
289
+ }
290
+ case "shutdown_request": {
291
+ if (isRunning) {
292
+ // Queue shutdown for after current task
293
+ messageQueue.push(msg);
294
+ return;
295
+ }
296
+ shutdown(agentState);
297
+ break;
144
298
  }
145
- send({
146
- type: "error",
147
- agentId,
148
- error: err instanceof Error ? err.message : String(err),
149
- });
150
- process.exit(1);
151
299
  }
152
300
  }
153
- // ── Main: wait for spawn payload from parent ────────────────────────────────
154
- process.on("message", (msg) => {
155
- if (msg.type === "spawn") {
156
- runChildAgent(msg).then(() => {
157
- process.exit(0);
158
- }).catch((err) => {
159
- const agentId = msg.agentId;
160
- send({ type: "error", agentId, error: err instanceof Error ? err.message : String(err) });
161
- process.exit(1);
162
- });
301
+ /** Drain queued messages (received while running). Shutdown takes priority. */
302
+ async function drainQueue() {
303
+ // Check for shutdown first
304
+ const shutdownIdx = messageQueue.findIndex((m) => m.type === "shutdown_request");
305
+ if (shutdownIdx !== -1) {
306
+ messageQueue.length = 0;
307
+ if (agentState)
308
+ shutdown(agentState);
309
+ return;
310
+ }
311
+ // Process remaining messages
312
+ while (messageQueue.length > 0) {
313
+ const next = messageQueue.shift();
314
+ await handleMessage(next);
315
+ if (!agentState)
316
+ return; // shutdown happened
163
317
  }
164
- else if (msg.type === "cancel") {
165
- process.exit(130);
318
+ }
319
+ // ── Message listener ───────────────────────────────────────────────────────
320
+ process.on("message", (msg) => {
321
+ if (isRunning && msg.type !== "cancel" && msg.type !== "shutdown_request") {
322
+ // Queue non-urgent messages while running
323
+ if (msg.type === "deliver_message" && agentState) {
324
+ agentState.pendingDms.push({
325
+ from: msg.from,
326
+ content: msg.content,
327
+ timestamp: new Date().toISOString(),
328
+ });
329
+ }
330
+ messageQueue.push(msg);
331
+ return;
166
332
  }
333
+ handleMessage(msg).catch((err) => {
334
+ const agentId = agentState?.agentId ?? "unknown";
335
+ send({ type: "error", agentId, error: err instanceof Error ? err.message : String(err) });
336
+ });
167
337
  });
168
338
  // If no IPC channel (run directly), exit with error
169
339
  if (!process.send) {
@@ -88,9 +88,12 @@ function atomicWriteJsonSync(filePath, data) {
88
88
  export class TeamCoordinator {
89
89
  teamName;
90
90
  filePath;
91
+ configPath;
91
92
  constructor(teamName) {
92
93
  this.teamName = teamName;
93
- this.filePath = path.join(os.homedir(), ".phren-agent", "teams", teamName, "tasks.json");
94
+ const teamDir = path.join(os.homedir(), ".phren-agent", "teams", teamName);
95
+ this.filePath = path.join(teamDir, "tasks.json");
96
+ this.configPath = path.join(teamDir, "config.json");
94
97
  }
95
98
  // ── Read / Write helpers (always called inside a lock) ──────────────
96
99
  readFile() {
@@ -260,4 +263,69 @@ export class TeamCoordinator {
260
263
  lines.push(` (${summary})`);
261
264
  return lines.join("\n");
262
265
  }
266
+ // ── Config helpers (always called inside a lock) ──────────────────
267
+ readConfig() {
268
+ try {
269
+ const raw = fs.readFileSync(this.configPath, "utf-8");
270
+ return JSON.parse(raw);
271
+ }
272
+ catch {
273
+ const now = new Date().toISOString();
274
+ return { teamName: this.teamName, members: [], createdAt: now, updatedAt: now };
275
+ }
276
+ }
277
+ writeConfig(data) {
278
+ data.updatedAt = new Date().toISOString();
279
+ atomicWriteJsonSync(this.configPath, data);
280
+ }
281
+ // ── Member Registry ───────────────────────────────────────────────
282
+ /** Register an agent as a team member. Updates existing entry if agentId matches. */
283
+ registerAgent(agentId, name, agentType, model) {
284
+ return withLock(this.configPath, () => {
285
+ const data = this.readConfig();
286
+ const existing = data.members.find((m) => m.agentId === agentId);
287
+ if (existing) {
288
+ existing.name = name;
289
+ existing.agentType = agentType ?? existing.agentType;
290
+ existing.model = model ?? existing.model;
291
+ this.writeConfig(data);
292
+ return existing;
293
+ }
294
+ const member = {
295
+ agentId,
296
+ name,
297
+ agentType: agentType ?? "agent",
298
+ model: model ?? "unknown",
299
+ joinedAt: new Date().toISOString(),
300
+ };
301
+ data.members.push(member);
302
+ this.writeConfig(data);
303
+ return member;
304
+ });
305
+ }
306
+ /** Remove an agent from the team by agentId. Returns true if found and removed. */
307
+ unregisterAgent(agentId) {
308
+ return withLock(this.configPath, () => {
309
+ const data = this.readConfig();
310
+ const idx = data.members.findIndex((m) => m.agentId === agentId);
311
+ if (idx === -1)
312
+ return false;
313
+ data.members.splice(idx, 1);
314
+ this.writeConfig(data);
315
+ return true;
316
+ });
317
+ }
318
+ /** Get all registered team members (read-only snapshot). */
319
+ getMembers() {
320
+ return withLock(this.configPath, () => {
321
+ return structuredClone(this.readConfig().members);
322
+ });
323
+ }
324
+ /** Find a team member by name. Returns null if not found. */
325
+ getMember(name) {
326
+ return withLock(this.configPath, () => {
327
+ const data = this.readConfig();
328
+ return data.members.find((m) => m.name === name) ?? null;
329
+ });
330
+ }
263
331
  }