@phren/agent 0.1.15 → 0.3.6

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 (110) hide show
  1. package/README.md +86 -0
  2. package/dist/agent-loop/index.js +239 -65
  3. package/dist/agent-loop/stream.js +212 -29
  4. package/dist/agent-loop/types.js +15 -2
  5. package/dist/checkpoint.js +103 -22
  6. package/dist/commands/info.js +30 -15
  7. package/dist/commands/model.js +6 -2
  8. package/dist/commands/review.js +183 -0
  9. package/dist/commands/session.js +70 -7
  10. package/dist/commands.js +168 -12
  11. package/dist/config.js +87 -10
  12. package/dist/context/compactor.js +239 -0
  13. package/dist/context/pruner.js +39 -13
  14. package/dist/context/token-counter.js +33 -1
  15. package/dist/custom-commands.js +69 -0
  16. package/dist/guards/repeat-tool-reminder.js +75 -0
  17. package/dist/headless.js +115 -0
  18. package/dist/herdr-hooks.js +71 -0
  19. package/dist/index.js +351 -48
  20. package/dist/mcp-client.js +434 -73
  21. package/dist/mcp-oauth.js +121 -0
  22. package/dist/memory/anti-patterns.js +7 -3
  23. package/dist/memory/auto-capture.js +7 -3
  24. package/dist/memory/context.js +92 -73
  25. package/dist/memory/project-context.js +24 -5
  26. package/dist/memory/provenance.js +15 -0
  27. package/dist/memory/review-triage.js +166 -0
  28. package/dist/memory/session.js +36 -1
  29. package/dist/models.js +152 -19
  30. package/dist/multi/child-entry.js +65 -10
  31. package/dist/multi/diff-renderer.js +3 -3
  32. package/dist/multi/markdown.js +125 -27
  33. package/dist/multi/provider-manager.js +8 -0
  34. package/dist/multi/publish.js +72 -0
  35. package/dist/multi/spawner.js +45 -4
  36. package/dist/multi/syntax-highlight.js +25 -4
  37. package/dist/multi/types.js +1 -1
  38. package/dist/permissions/allowlist.js +86 -13
  39. package/dist/permissions/checker.js +42 -7
  40. package/dist/permissions/kernel-sandbox.js +197 -0
  41. package/dist/permissions/prompt.js +10 -1
  42. package/dist/permissions/sandbox.js +40 -17
  43. package/dist/providers/anthropic.js +154 -7
  44. package/dist/providers/codex-auth.js +28 -0
  45. package/dist/providers/codex.js +134 -23
  46. package/dist/providers/history.js +35 -0
  47. package/dist/providers/ollama.js +37 -6
  48. package/dist/providers/openai-compat.js +171 -74
  49. package/dist/providers/openrouter.js +47 -17
  50. package/dist/providers/replay.js +62 -0
  51. package/dist/providers/resolve.js +41 -7
  52. package/dist/providers/retry.js +38 -5
  53. package/dist/providers/types.js +9 -1
  54. package/dist/repl.js +47 -5
  55. package/dist/session/log.js +217 -0
  56. package/dist/session/persist.js +190 -0
  57. package/dist/settings.js +42 -26
  58. package/dist/system-prompt.js +18 -2
  59. package/dist/tools/apply-patch.js +355 -0
  60. package/dist/tools/edit-engine.js +287 -0
  61. package/dist/tools/edit-file.js +86 -27
  62. package/dist/tools/grep.js +25 -10
  63. package/dist/tools/lint-test.js +0 -22
  64. package/dist/tools/mcp-resources.js +51 -6
  65. package/dist/tools/phren-finding.js +12 -4
  66. package/dist/tools/phren-search.js +7 -2
  67. package/dist/tools/read-file.js +37 -9
  68. package/dist/tools/read-image.js +76 -0
  69. package/dist/tools/registry.js +27 -5
  70. package/dist/tools/shell.js +134 -71
  71. package/dist/tools/skill.js +20 -20
  72. package/dist/tools/spawn-agent.js +77 -13
  73. package/dist/tools/update-plan.js +48 -0
  74. package/dist/tools/web-fetch.js +110 -12
  75. package/dist/tools/web-search.js +4 -4
  76. package/dist/tui/components/App.js +98 -26
  77. package/dist/tui/components/ApprovalPanel.js +8 -0
  78. package/dist/tui/components/InputArea.js +5 -5
  79. package/dist/tui/components/ModelPicker.js +43 -0
  80. package/dist/tui/components/PhrenInput.js +10 -5
  81. package/dist/tui/components/PlanReview.js +7 -0
  82. package/dist/tui/components/ShortcutHelp.js +5 -0
  83. package/dist/tui/components/StatusBar.js +46 -20
  84. package/dist/tui/components/SteerQueue.js +1 -1
  85. package/dist/tui/components/ThinkingIndicator.js +6 -4
  86. package/dist/tui/components/ToolCall.js +10 -4
  87. package/dist/tui/components/ToolDetail.js +21 -0
  88. package/dist/tui/help.js +6 -0
  89. package/dist/tui/hooks/useKeyboardShortcuts.js +15 -1
  90. package/dist/tui/index.js +0 -1
  91. package/dist/tui/ink-entry.js +317 -33
  92. package/dist/tui/tool-render.js +1 -1
  93. package/dist/user-hooks.js +171 -0
  94. package/package.json +14 -8
  95. package/dist/multi/multi-commands.js +0 -170
  96. package/dist/multi/multi-events.js +0 -98
  97. package/dist/multi/multi-render.js +0 -147
  98. package/dist/multi/pane.js +0 -28
  99. package/dist/multi/tui-multi.js +0 -200
  100. package/dist/permissions/privacy.js +0 -248
  101. package/dist/tui/components/AgentMessage.js +0 -5
  102. package/dist/tui/components/ChatMessage.js +0 -23
  103. package/dist/tui/components/CodeBlock.js +0 -8
  104. package/dist/tui/components/Separator.js +0 -7
  105. package/dist/tui/components/StreamingText.js +0 -5
  106. package/dist/tui/components/UserMessage.js +0 -5
  107. package/dist/tui/menu-mode.js +0 -86
  108. package/dist/tui/mouse.js +0 -71
  109. package/dist/tui/terminal-control.js +0 -62
  110. package/dist/tui.js +0 -781
@@ -0,0 +1,171 @@
1
+ import { spawn } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { agentConfigDir, agentUserDir } from "./config.js";
5
+ export const HOOK_EVENT_NAMES = [
6
+ "PreToolUse",
7
+ "PostToolUse",
8
+ "UserPromptSubmit",
9
+ "Stop",
10
+ ];
11
+ const DEFAULT_TIMEOUT_MS = 10_000;
12
+ const MAX_OUTPUT_CHARS = 16_384;
13
+ function isHookCommand(value) {
14
+ return !!value && typeof value === "object" && typeof value.command === "string";
15
+ }
16
+ function readHooksFile(file) {
17
+ try {
18
+ const parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
19
+ const hooks = parsed?.hooks;
20
+ if (!hooks || typeof hooks !== "object" || Array.isArray(hooks))
21
+ return null;
22
+ const out = {};
23
+ let found = false;
24
+ for (const event of HOOK_EVENT_NAMES) {
25
+ const list = hooks[event];
26
+ if (!Array.isArray(list))
27
+ continue;
28
+ const commands = list.filter(isHookCommand);
29
+ if (commands.length === 0)
30
+ continue;
31
+ out[event] = commands;
32
+ found = true;
33
+ }
34
+ return found ? out : null;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ export function loadHooksConfig(cwd = process.cwd(), options = {}) {
41
+ const userFile = path.join(agentUserDir(options.home), "hooks.json");
42
+ const projectFile = path.join(agentConfigDir(cwd), "hooks.json");
43
+ const merged = {};
44
+ let found = false;
45
+ for (const file of [userFile, projectFile]) {
46
+ const cfg = readHooksFile(file);
47
+ if (!cfg)
48
+ continue;
49
+ found = true;
50
+ for (const event of HOOK_EVENT_NAMES) {
51
+ const list = cfg[event];
52
+ if (!list)
53
+ continue;
54
+ merged[event] = [...(merged[event] ?? []), ...list];
55
+ }
56
+ }
57
+ return found ? merged : null;
58
+ }
59
+ function matchesTool(matcher, toolName) {
60
+ if (!matcher || matcher === "*")
61
+ return true;
62
+ try {
63
+ return new RegExp(matcher).test(toolName);
64
+ }
65
+ catch {
66
+ return matcher === toolName;
67
+ }
68
+ }
69
+ function capOutput(text) {
70
+ return text.length > MAX_OUTPUT_CHARS ? text.slice(0, MAX_OUTPUT_CHARS) : text;
71
+ }
72
+ function defaultHookExecutor(command, stdin, options) {
73
+ return new Promise((resolve) => {
74
+ let stdout = "";
75
+ let stderr = "";
76
+ let timedOut = false;
77
+ let settled = false;
78
+ let child;
79
+ try {
80
+ child = spawn(command, { shell: true, cwd: options.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
81
+ }
82
+ catch (err) {
83
+ resolve({ exitCode: null, stdout: "", stderr: err instanceof Error ? err.message : String(err), timedOut: false });
84
+ return;
85
+ }
86
+ const finish = (exitCode) => {
87
+ if (settled)
88
+ return;
89
+ settled = true;
90
+ clearTimeout(timer);
91
+ resolve({ exitCode, stdout: capOutput(stdout), stderr: capOutput(stderr), timedOut });
92
+ };
93
+ const timer = setTimeout(() => {
94
+ timedOut = true;
95
+ try {
96
+ child.kill("SIGKILL");
97
+ }
98
+ catch { }
99
+ finish(null);
100
+ }, options.timeoutMs);
101
+ timer.unref();
102
+ child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
103
+ child.stderr?.on("data", (chunk) => { stderr += chunk.toString(); });
104
+ child.on("error", (err) => { stderr += err.message; finish(null); });
105
+ child.on("close", (code) => { finish(code); });
106
+ child.stdin?.on("error", () => { });
107
+ child.stdin?.end(stdin);
108
+ });
109
+ }
110
+ async function runHook(hook, payload, options) {
111
+ const executor = options.executor ?? defaultHookExecutor;
112
+ const timeoutMs = options.timeoutMs ?? hook.timeoutMs ?? DEFAULT_TIMEOUT_MS;
113
+ try {
114
+ return await executor(hook.command, JSON.stringify(payload), {
115
+ cwd: options.cwd ?? process.cwd(),
116
+ timeoutMs,
117
+ });
118
+ }
119
+ catch (err) {
120
+ return {
121
+ exitCode: null,
122
+ stdout: "",
123
+ stderr: err instanceof Error ? err.message : String(err),
124
+ timedOut: false,
125
+ };
126
+ }
127
+ }
128
+ export async function runPreToolUseHooks(config, toolName, input, options = {}) {
129
+ const hooks = (config?.PreToolUse ?? []).filter((hook) => matchesTool(hook.matcher, toolName));
130
+ if (hooks.length === 0)
131
+ return { denied: false, message: "" };
132
+ const payload = {
133
+ hook_event_name: "PreToolUse",
134
+ tool_name: toolName,
135
+ tool_input: input,
136
+ cwd: options.cwd ?? process.cwd(),
137
+ };
138
+ for (const hook of hooks) {
139
+ const result = await runHook(hook, payload, options);
140
+ if (result.exitCode !== null && result.exitCode !== 0) {
141
+ const message = result.stderr.trim() || result.stdout.trim() || `Blocked by PreToolUse hook: ${hook.command}`;
142
+ return { denied: true, message };
143
+ }
144
+ }
145
+ return { denied: false, message: "" };
146
+ }
147
+ export async function runPostToolUseHooks(config, toolName, input, output, isError, options = {}) {
148
+ const hooks = (config?.PostToolUse ?? []).filter((hook) => matchesTool(hook.matcher, toolName));
149
+ if (hooks.length === 0)
150
+ return;
151
+ const payload = {
152
+ hook_event_name: "PostToolUse",
153
+ tool_name: toolName,
154
+ tool_input: input,
155
+ tool_response: output,
156
+ is_error: isError,
157
+ cwd: options.cwd ?? process.cwd(),
158
+ };
159
+ for (const hook of hooks) {
160
+ await runHook(hook, payload, options);
161
+ }
162
+ }
163
+ export async function runLifecycleHooks(config, event, payload = {}, options = {}) {
164
+ const hooks = config?.[event] ?? [];
165
+ if (hooks.length === 0)
166
+ return;
167
+ const body = { hook_event_name: event, ...payload, cwd: options.cwd ?? process.cwd() };
168
+ for (const hook of hooks) {
169
+ await runHook(hook, body, options);
170
+ }
171
+ }
package/package.json CHANGED
@@ -1,21 +1,23 @@
1
1
  {
2
2
  "name": "@phren/agent",
3
- "version": "0.1.15",
4
- "description": "Coding agent with persistent memory — powered by phren",
3
+ "version": "0.3.6",
4
+ "description": "phren's coding agent: starts every session knowing your project's memory, tasks and decisions",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "phren-agent": "dist/bin.js"
8
8
  },
9
9
  "exports": {
10
- ".": "./dist/index.js"
10
+ ".": "./dist/index.js",
11
+ "./package.json": "./package.json"
11
12
  },
12
13
  "files": [
13
14
  "dist"
14
15
  ],
15
16
  "dependencies": {
16
- "ink": "^6.8.0",
17
- "react": "^19.2.4",
18
- "@phren/cli": "0.1.11"
17
+ "@modelcontextprotocol/sdk": "^1.30.1",
18
+ "ink": "^7.1.1",
19
+ "react": "^19.3.0",
20
+ "@phren/cli": "0.3.6"
19
21
  },
20
22
  "engines": {
21
23
  "node": ">=20.0.0"
@@ -35,10 +37,14 @@
35
37
  "directory": "packages/agent"
36
38
  },
37
39
  "devDependencies": {
38
- "@types/react": "^19.2.14"
40
+ "@types/react": "^19.3.0"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
39
44
  },
40
45
  "scripts": {
41
46
  "build": "tsc -p tsconfig.json",
42
- "test": "echo 'Run tests from repo root: pnpm -w test'"
47
+ "test": "vitest run",
48
+ "lint": "biome lint --config-path ../../biome.json src/"
43
49
  }
44
50
  }
@@ -1,170 +0,0 @@
1
- import { createPane, appendToPane, flushPartial } from "./pane.js";
2
- import { s, statusColor } from "./multi-render.js";
3
- function resolveAgentTarget(target, agentOrder, panes, spawner) {
4
- // Try numeric index (1-based)
5
- const idx = parseInt(target, 10);
6
- if (!isNaN(idx) && idx >= 1 && idx <= agentOrder.length) {
7
- return agentOrder[idx - 1];
8
- }
9
- // Try name match
10
- for (const [id, pane] of panes) {
11
- if (pane.name === target)
12
- return id;
13
- }
14
- // Try agent ID
15
- if (spawner.getAgent(target))
16
- return target;
17
- return null;
18
- }
19
- function appendToSystem(ctx, text) {
20
- if (!ctx.selectedId || !ctx.panes.has(ctx.selectedId)) {
21
- // Create a virtual system pane
22
- const pane = createPane("_system", "system");
23
- ctx.panes.set("_system", pane);
24
- if (!ctx.agentOrder.includes("_system"))
25
- ctx.agentOrder.push("_system");
26
- ctx.setSelectedId("_system");
27
- appendToPane(pane, text + "\n");
28
- }
29
- else {
30
- const pane = ctx.panes.get(ctx.selectedId);
31
- flushPartial(pane);
32
- appendToPane(pane, text + "\n");
33
- }
34
- ctx.render();
35
- }
36
- export function handleSlashCommand(line, ctx) {
37
- const parts = line.split(/\s+/);
38
- const cmd = parts[0].toLowerCase();
39
- if (cmd === "/spawn") {
40
- const name = parts[1];
41
- const task = parts.slice(2).join(" ");
42
- if (!name || !task) {
43
- appendToSystem(ctx, "Usage: /spawn <name> <task>");
44
- return true;
45
- }
46
- const opts = {
47
- task,
48
- cwd: process.cwd(),
49
- provider: ctx.config.provider.name,
50
- permissions: "auto-confirm",
51
- verbose: ctx.config.verbose,
52
- };
53
- const agentId = ctx.spawner.spawn(opts);
54
- const pane = ctx.getOrCreatePane(agentId);
55
- pane.name = name;
56
- appendToPane(pane, s.cyan(`Spawned agent "${name}" (${agentId}): ${task}`) + "\n");
57
- ctx.setSelectedId(agentId);
58
- ctx.render();
59
- return true;
60
- }
61
- if (cmd === "/list") {
62
- const agents = ctx.spawner.listAgents();
63
- if (agents.length === 0) {
64
- appendToSystem(ctx, "No agents.");
65
- }
66
- else {
67
- const lines = ["Agents:"];
68
- for (let i = 0; i < agents.length; i++) {
69
- const a = agents[i];
70
- const pane = ctx.panes.get(a.id);
71
- const name = pane?.name ?? a.id;
72
- const color = statusColor(a.status);
73
- const elapsed = a.finishedAt
74
- ? `${((a.finishedAt - a.startedAt) / 1000).toFixed(1)}s`
75
- : `${((Date.now() - a.startedAt) / 1000).toFixed(0)}s`;
76
- lines.push(` ${i + 1}. ${name} [${color(a.status)}] ${s.dim(elapsed)} — ${a.task.slice(0, 50)}`);
77
- }
78
- appendToSystem(ctx, lines.join("\n"));
79
- }
80
- return true;
81
- }
82
- if (cmd === "/kill") {
83
- const target = parts[1];
84
- if (!target) {
85
- appendToSystem(ctx, "Usage: /kill <name|index>");
86
- return true;
87
- }
88
- const agentId = resolveAgentTarget(target, ctx.agentOrder, ctx.panes, ctx.spawner);
89
- if (!agentId) {
90
- appendToSystem(ctx, `Agent "${target}" not found.`);
91
- return true;
92
- }
93
- const ok = ctx.spawner.cancel(agentId);
94
- const pane = ctx.getOrCreatePane(agentId);
95
- if (ok) {
96
- appendToPane(pane, s.yellow("\n--- Cancelled ---\n"));
97
- }
98
- else {
99
- appendToSystem(ctx, `Agent "${target}" is not running.`);
100
- }
101
- ctx.render();
102
- return true;
103
- }
104
- if (cmd === "/broadcast") {
105
- const msg = parts.slice(1).join(" ");
106
- if (!msg) {
107
- appendToSystem(ctx, "Usage: /broadcast <message>");
108
- return true;
109
- }
110
- const agents = ctx.spawner.listAgents();
111
- let sent = 0;
112
- for (const a of agents) {
113
- if (a.status === "running") {
114
- const pane = ctx.getOrCreatePane(a.id);
115
- appendToPane(pane, s.yellow(`[broadcast] ${msg}`) + "\n");
116
- sent++;
117
- }
118
- }
119
- appendToSystem(ctx, `Broadcast sent to ${sent} running agent(s).`);
120
- return true;
121
- }
122
- if (cmd === "/msg") {
123
- const target = parts[1];
124
- const msg = parts.slice(2).join(" ");
125
- if (!target || !msg) {
126
- appendToSystem(ctx, "Usage: /msg <agent> <text>");
127
- return true;
128
- }
129
- const agentId = resolveAgentTarget(target, ctx.agentOrder, ctx.panes, ctx.spawner);
130
- if (!agentId) {
131
- appendToSystem(ctx, `Agent "${target}" not found.`);
132
- return true;
133
- }
134
- const ok = ctx.spawner.sendToAgent(agentId, msg, "user");
135
- if (ok) {
136
- const recipientPane = ctx.getOrCreatePane(agentId);
137
- flushPartial(recipientPane);
138
- appendToPane(recipientPane, s.yellow(`[user -> ${recipientPane.name}] ${msg}`) + "\n");
139
- if (ctx.selectedId && ctx.selectedId !== agentId && ctx.panes.has(ctx.selectedId)) {
140
- const curPane = ctx.panes.get(ctx.selectedId);
141
- flushPartial(curPane);
142
- appendToPane(curPane, s.yellow(`[user -> ${recipientPane.name}] ${msg}`) + "\n");
143
- }
144
- }
145
- else {
146
- appendToSystem(ctx, `Agent "${target}" is not running.`);
147
- }
148
- ctx.render();
149
- return true;
150
- }
151
- if (cmd === "/help") {
152
- appendToSystem(ctx, [
153
- "Commands:",
154
- " /spawn <name> <task> — Spawn a new agent",
155
- " /list — List all agents",
156
- " /kill <name|index> — Terminate an agent",
157
- " /msg <agent> <text> — Send direct message to an agent",
158
- " /broadcast <msg> — Send to all running agents",
159
- " /help — Show this help",
160
- "",
161
- "Keys:",
162
- " 1-9 — Select agent by number",
163
- " Ctrl+Left/Right — Cycle agents",
164
- " PageUp/PageDown — Scroll output",
165
- " Ctrl+D — Exit (kills all)",
166
- ].join("\n"));
167
- return true;
168
- }
169
- return false;
170
- }
@@ -1,98 +0,0 @@
1
- import { appendToPane, flushPartial } from "./pane.js";
2
- import { getAgentStyle } from "./agent-colors.js";
3
- import { decodeDiffPayload, renderInlineDiff, DIFF_MARKER } from "./diff-renderer.js";
4
- import { s, formatToolStart, formatToolEnd } from "./multi-render.js";
5
- export function wireSpawnerEvents(spawner, ctx) {
6
- spawner.on("text_delta", (agentId, text) => {
7
- const pane = ctx.getOrCreatePane(agentId);
8
- appendToPane(pane, text);
9
- if (agentId === ctx.getSelectedId())
10
- ctx.render();
11
- });
12
- spawner.on("text_block", (agentId, text) => {
13
- const pane = ctx.getOrCreatePane(agentId);
14
- appendToPane(pane, text + "\n");
15
- if (agentId === ctx.getSelectedId())
16
- ctx.render();
17
- });
18
- spawner.on("tool_start", (agentId, toolName, input) => {
19
- const pane = ctx.getOrCreatePane(agentId);
20
- flushPartial(pane);
21
- appendToPane(pane, formatToolStart(toolName, input) + "\n");
22
- if (agentId === ctx.getSelectedId())
23
- ctx.render();
24
- });
25
- spawner.on("tool_end", (agentId, toolName, input, output, isError, durationMs) => {
26
- const pane = ctx.getOrCreatePane(agentId);
27
- flushPartial(pane);
28
- const diffData = (toolName === "edit_file" || toolName === "write_file") ? decodeDiffPayload(output) : null;
29
- const cleanOutput = diffData ? output.slice(0, output.indexOf(DIFF_MARKER)) : output;
30
- appendToPane(pane, formatToolEnd(toolName, input, cleanOutput, isError, durationMs) + "\n");
31
- if (diffData) {
32
- appendToPane(pane, renderInlineDiff(diffData.oldContent, diffData.newContent, diffData.filePath) + "\n");
33
- }
34
- if (agentId === ctx.getSelectedId())
35
- ctx.render();
36
- });
37
- spawner.on("status", (agentId, message) => {
38
- const pane = ctx.getOrCreatePane(agentId);
39
- appendToPane(pane, s.dim(message) + "\n");
40
- if (agentId === ctx.getSelectedId())
41
- ctx.render();
42
- });
43
- spawner.on("done", (agentId, result) => {
44
- const pane = ctx.getOrCreatePane(agentId);
45
- flushPartial(pane);
46
- const style = getAgentStyle(pane.index);
47
- appendToPane(pane, "\n" + style.color(`--- ${style.icon} Agent completed ---`) + "\n");
48
- appendToPane(pane, s.dim(` Turns: ${result.turns} Tool calls: ${result.toolCalls}${result.totalCost ? ` Cost: ${result.totalCost}` : ""}`) + "\n");
49
- ctx.render();
50
- });
51
- spawner.on("error", (agentId, error) => {
52
- const pane = ctx.getOrCreatePane(agentId);
53
- flushPartial(pane);
54
- const style = getAgentStyle(pane.index);
55
- appendToPane(pane, "\n" + style.color(`--- ${style.icon} Error: ${error} ---`) + "\n");
56
- ctx.render();
57
- });
58
- spawner.on("exit", (agentId, code) => {
59
- const pane = ctx.getOrCreatePane(agentId);
60
- if (code !== null && code !== 0) {
61
- appendToPane(pane, s.dim(` Process exited with code ${code}`) + "\n");
62
- }
63
- ctx.render();
64
- });
65
- spawner.on("idle", (agentId, reason, dmSummaries) => {
66
- const pane = ctx.getOrCreatePane(agentId);
67
- const style = getAgentStyle(pane.index);
68
- appendToPane(pane, s.dim(` ${style.icon} Agent idle (${reason})`) + "\n");
69
- if (dmSummaries && dmSummaries.length > 0) {
70
- appendToPane(pane, s.dim(" Messages received while running:") + "\n");
71
- for (const dm of dmSummaries) {
72
- appendToPane(pane, s.yellow(` [${dm.from}] ${dm.content.slice(0, 100)}`) + "\n");
73
- }
74
- }
75
- ctx.render();
76
- });
77
- spawner.on("shutdown_approved", (agentId) => {
78
- const pane = ctx.getOrCreatePane(agentId);
79
- appendToPane(pane, s.dim(" Agent shut down gracefully.") + "\n");
80
- ctx.render();
81
- });
82
- spawner.on("message", (from, to, content) => {
83
- const senderPane = ctx.panes.get(from);
84
- if (senderPane) {
85
- flushPartial(senderPane);
86
- const toName = ctx.panes.get(to)?.name ?? to;
87
- appendToPane(senderPane, s.yellow(`[${senderPane.name} -> ${toName}] ${content}`) + "\n");
88
- }
89
- const recipientPane = ctx.panes.get(to);
90
- if (recipientPane) {
91
- flushPartial(recipientPane);
92
- const fromName = senderPane?.name ?? from;
93
- appendToPane(recipientPane, s.yellow(`[${fromName} -> ${recipientPane.name}] ${content}`) + "\n");
94
- }
95
- if (from === ctx.getSelectedId() || to === ctx.getSelectedId())
96
- ctx.render();
97
- });
98
- }
@@ -1,147 +0,0 @@
1
- import { getAgentStyle, formatAgentName } from "./agent-colors.js";
2
- // ── ANSI helpers (mirrors tui.ts pattern) ────────────────────────────────────
3
- export const ESC = "\x1b[";
4
- export const s = {
5
- reset: `${ESC}0m`,
6
- bold: (t) => `${ESC}1m${t}${ESC}0m`,
7
- dim: (t) => `${ESC}2m${t}${ESC}0m`,
8
- cyan: (t) => `${ESC}36m${t}${ESC}0m`,
9
- green: (t) => `${ESC}32m${t}${ESC}0m`,
10
- yellow: (t) => `${ESC}33m${t}${ESC}0m`,
11
- red: (t) => `${ESC}31m${t}${ESC}0m`,
12
- gray: (t) => `${ESC}90m${t}${ESC}0m`,
13
- white: (t) => `${ESC}37m${t}${ESC}0m`,
14
- bgGreen: (t) => `${ESC}42m${t}${ESC}0m`,
15
- bgRed: (t) => `${ESC}41m${t}${ESC}0m`,
16
- bgGray: (t) => `${ESC}100m${t}${ESC}0m`,
17
- bgCyan: (t) => `${ESC}46m${t}${ESC}0m`,
18
- bgYellow: (t) => `${ESC}43m${t}${ESC}0m`,
19
- invert: (t) => `${ESC}7m${t}${ESC}0m`,
20
- };
21
- function stripAnsi(t) {
22
- return t.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");
23
- }
24
- function cols() {
25
- return process.stdout.columns || 80;
26
- }
27
- function rows() {
28
- return process.stdout.rows || 24;
29
- }
30
- export function statusColor(status) {
31
- switch (status) {
32
- case "starting": return s.yellow;
33
- case "running": return s.green;
34
- case "idle": return s.cyan;
35
- case "done": return s.gray;
36
- case "error": return s.red;
37
- case "cancelled": return s.gray;
38
- }
39
- }
40
- export function formatToolStart(toolName, input) {
41
- const preview = JSON.stringify(input).slice(0, 60);
42
- return s.dim(` > ${toolName}(${preview})...`);
43
- }
44
- export function formatToolEnd(toolName, input, output, isError, durationMs) {
45
- const dur = durationMs < 1000 ? `${durationMs}ms` : `${(durationMs / 1000).toFixed(1)}s`;
46
- const icon = isError ? s.red("x") : s.green("ok");
47
- const preview = JSON.stringify(input).slice(0, 50);
48
- const header = s.dim(` ${toolName}(${preview})`) + ` ${icon} ${s.dim(dur)}`;
49
- const allLines = output.split("\n");
50
- const w = cols();
51
- const body = allLines.slice(0, 4).map((l) => s.dim(` | ${l.slice(0, w - 6)}`)).join("\n");
52
- const more = allLines.length > 4 ? `\n${s.dim(` | ... (${allLines.length} lines)`)}` : "";
53
- return `${header}\n${body}${more}`;
54
- }
55
- export function renderTopBar(spawner, panes, selectedId) {
56
- const w_ = cols();
57
- const agents = spawner.listAgents();
58
- const tabs = [];
59
- for (let i = 0; i < agents.length; i++) {
60
- const a = agents[i];
61
- const isSel = a.id === selectedId;
62
- const pane = panes.get(a.id);
63
- const paneIdx = pane?.index ?? i;
64
- const stColor = statusColor(a.status);
65
- const agentLabel = formatAgentName(pane?.name ?? a.task.slice(0, 12), paneIdx);
66
- const statusTag = stColor(a.status);
67
- const raw = ` ${i + 1}:${stripAnsi(agentLabel)} [${stripAnsi(statusTag)}] `;
68
- const colored = ` ${i + 1}:${agentLabel} [${statusTag}] `;
69
- const tab = isSel ? s.invert(raw) : colored;
70
- tabs.push(tab);
71
- }
72
- if (agents.length === 0) {
73
- tabs.push(s.dim(" no agents "));
74
- }
75
- const title = s.bold(" phren-multi ");
76
- const tabStr = tabs.join(s.dim("|"));
77
- const line = title + s.dim("|") + tabStr;
78
- const pad = Math.max(0, w_ - stripAnsi(line).length);
79
- return s.invert(stripAnsi(title)) + s.dim("|") + tabStr + " ".repeat(pad);
80
- }
81
- export function renderMainArea(panes, selectedId, scrollOffset) {
82
- const availRows = rows() - 3; // top bar + bottom bar + input line
83
- if (availRows < 1)
84
- return [];
85
- if (!selectedId || !panes.has(selectedId)) {
86
- const emptyMsg = s.dim(" No agent selected. Use /spawn <name> <task> to create one.");
87
- const lines = [emptyMsg];
88
- while (lines.length < availRows)
89
- lines.push("");
90
- return lines;
91
- }
92
- const pane = panes.get(selectedId);
93
- // Include partial line if any
94
- const allLines = [...pane.lines];
95
- if (pane.partial)
96
- allLines.push(pane.partial);
97
- // Apply scroll offset
98
- const totalLines = allLines.length;
99
- let start = Math.max(0, totalLines - availRows - scrollOffset);
100
- let end = start + availRows;
101
- if (end > totalLines) {
102
- end = totalLines;
103
- start = Math.max(0, end - availRows);
104
- }
105
- const visible = allLines.slice(start, end);
106
- const w_ = cols();
107
- const output = [];
108
- const paneStyle = getAgentStyle(pane.index);
109
- const linePrefix = paneStyle.color(paneStyle.icon) + " ";
110
- const prefixLen = 2; // icon + space
111
- for (const line of visible) {
112
- output.push(linePrefix + line.slice(0, w_ - prefixLen));
113
- }
114
- // Pad remaining rows
115
- while (output.length < availRows)
116
- output.push("");
117
- return output;
118
- }
119
- export function renderBottomBar(spawner) {
120
- const w_ = cols();
121
- const agentCount = spawner.listAgents().length;
122
- const runningCount = spawner.getAgentsByStatus("running").length;
123
- const left = ` Agents: ${agentCount} (${runningCount} running)`;
124
- const right = `1-9:select Ctrl+</>:cycle /spawn /list /kill /broadcast Ctrl+D:exit `;
125
- const pad = Math.max(0, w_ - left.length - right.length);
126
- return s.invert(left + " ".repeat(pad) + right);
127
- }
128
- export function render(w, spawner, panes, selectedId, scrollOffset, inputLine) {
129
- // Hide cursor, move to top, clear screen
130
- w.write(`${ESC}?25l${ESC}H${ESC}2J`);
131
- // Top bar
132
- w.write(renderTopBar(spawner, panes, selectedId));
133
- w.write("\n");
134
- // Main area
135
- const mainLines = renderMainArea(panes, selectedId, scrollOffset);
136
- for (const line of mainLines) {
137
- w.write(line + "\n");
138
- }
139
- // Bottom bar
140
- w.write(renderBottomBar(spawner));
141
- w.write("\n");
142
- // Input line
143
- const prompt = s.cyan("multi> ");
144
- w.write(prompt + inputLine);
145
- // Show cursor
146
- w.write(`${ESC}?25h`);
147
- }
@@ -1,28 +0,0 @@
1
- export const MAX_SCROLLBACK = 1000;
2
- let nextPaneIndex = 0;
3
- export function resetPaneIndex() {
4
- nextPaneIndex = 0;
5
- }
6
- export function createPane(agentId, name) {
7
- return { agentId, name, index: nextPaneIndex++, lines: [], partial: "" };
8
- }
9
- export function appendToPane(pane, text) {
10
- // Merge with partial line buffer
11
- const combined = pane.partial + text;
12
- const parts = combined.split("\n");
13
- // Everything except the last segment is a complete line
14
- for (let i = 0; i < parts.length - 1; i++) {
15
- pane.lines.push(parts[i]);
16
- }
17
- pane.partial = parts[parts.length - 1];
18
- // Enforce scrollback cap
19
- if (pane.lines.length > MAX_SCROLLBACK) {
20
- pane.lines.splice(0, pane.lines.length - MAX_SCROLLBACK);
21
- }
22
- }
23
- export function flushPartial(pane) {
24
- if (pane.partial) {
25
- pane.lines.push(pane.partial);
26
- pane.partial = "";
27
- }
28
- }