@phren/agent 0.1.8 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/info.js +1 -0
- package/dist/commands/model.js +5 -4
- package/dist/commands/session.js +24 -2
- package/dist/commands.js +36 -1
- package/dist/config.js +27 -11
- package/dist/cost.js +11 -74
- package/dist/index.js +92 -35
- package/dist/mcp-client.js +4 -2
- package/dist/memory/context.js +56 -24
- package/dist/memory/session.js +21 -88
- package/dist/models.js +390 -0
- package/dist/multi/agent-types.js +170 -0
- package/dist/multi/child-entry.js +248 -78
- package/dist/multi/coordinator.js +69 -1
- package/dist/multi/diff-renderer.js +193 -17
- package/dist/multi/markdown.js +49 -23
- package/dist/multi/model-picker.js +12 -21
- package/dist/multi/multi-events.js +17 -0
- package/dist/multi/multi-render.js +1 -0
- package/dist/multi/provider-manager.js +23 -13
- package/dist/multi/spawner.js +84 -7
- package/dist/multi/syntax-highlight.js +64 -48
- package/dist/multi/worktree.js +43 -0
- package/dist/package-metadata.js +11 -0
- package/dist/permissions/checker.js +21 -1
- package/dist/providers/codex-auth.js +48 -34
- package/dist/providers/codex.js +110 -40
- package/dist/providers/ollama.js +5 -4
- package/dist/providers/openrouter.js +12 -5
- package/dist/providers/resolve.js +50 -32
- package/dist/providers/types.js +0 -1
- package/dist/repl.js +19 -34
- package/dist/tools/grep.js +111 -23
- package/dist/tools/mcp-resources.js +32 -0
- package/dist/tools/registry.js +13 -2
- package/dist/tools/shell.js +101 -3
- package/dist/tools/skill.js +44 -0
- package/dist/tools/spawn-agent.js +158 -0
- package/dist/tui/ansi.js +15 -11
- package/dist/tui/components/App.js +179 -8
- package/dist/tui/components/Banner.js +7 -4
- package/dist/tui/components/InputArea.js +54 -12
- package/dist/tui/components/PhrenInput.js +329 -0
- package/dist/tui/components/StatusBar.js +3 -1
- package/dist/tui/components/SteerQueue.js +4 -2
- package/dist/tui/components/ThinkingIndicator.js +7 -5
- package/dist/tui/components/ToolCall.js +12 -8
- package/dist/tui/components/ToolSpinner.js +13 -0
- package/dist/tui/hooks/useKeyboardShortcuts.js +65 -24
- package/dist/tui/hooks/useSearch.js +47 -0
- package/dist/tui/hooks/useSlashCommands.js +16 -19
- package/dist/tui/ink-entry.js +373 -14
- package/dist/tui/mouse.js +71 -0
- package/dist/tui/terminal-control.js +62 -0
- package/dist/tui/themes.js +398 -0
- package/dist/tui/tool-render.js +12 -1
- package/dist/tui.js +2 -1
- package/package.json +1 -3
package/dist/multi/spawner.js
CHANGED
|
@@ -12,6 +12,7 @@ import { fork } from "node:child_process";
|
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
13
|
import { dirname, join } from "node:path";
|
|
14
14
|
import { EventEmitter } from "node:events";
|
|
15
|
+
import { createWorktree, hasWorktreeChanges, removeWorktree } from "./worktree.js";
|
|
15
16
|
const __filename = fileURLToPath(import.meta.url);
|
|
16
17
|
const __dirname = dirname(__filename);
|
|
17
18
|
/** Resolved path to the child-entry module. */
|
|
@@ -61,10 +62,12 @@ export class AgentSpawner extends EventEmitter {
|
|
|
61
62
|
plan: opts.plan ?? false,
|
|
62
63
|
verbose: opts.verbose ?? false,
|
|
63
64
|
env: childEnv,
|
|
65
|
+
agentType: opts.agentType,
|
|
64
66
|
};
|
|
65
67
|
const entry = {
|
|
66
68
|
id: agentId,
|
|
67
69
|
task: opts.task,
|
|
70
|
+
displayName: opts.displayName,
|
|
68
71
|
status: "starting",
|
|
69
72
|
startedAt: Date.now(),
|
|
70
73
|
};
|
|
@@ -78,6 +81,18 @@ export class AgentSpawner extends EventEmitter {
|
|
|
78
81
|
this.processes.set(agentId, child);
|
|
79
82
|
entry.pid = child.pid;
|
|
80
83
|
entry.status = "running";
|
|
84
|
+
// If worktree isolation requested, create a worktree and redirect cwd
|
|
85
|
+
if (opts.isolation === "worktree") {
|
|
86
|
+
try {
|
|
87
|
+
const wt = createWorktree(payload.cwd, agentId);
|
|
88
|
+
entry.worktree = wt;
|
|
89
|
+
payload.cwd = wt.path;
|
|
90
|
+
payload.worktreePath = wt.path;
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
this.emit("status", agentId, `Worktree creation failed: ${err}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
81
96
|
// Send the spawn payload
|
|
82
97
|
child.send(payload);
|
|
83
98
|
// Handle IPC messages from child
|
|
@@ -94,6 +109,17 @@ export class AgentSpawner extends EventEmitter {
|
|
|
94
109
|
agent.error = `Process exited with code ${code}`;
|
|
95
110
|
}
|
|
96
111
|
}
|
|
112
|
+
// Clean up worktree if no uncommitted changes remain
|
|
113
|
+
if (agent?.worktree) {
|
|
114
|
+
const wt = agent.worktree;
|
|
115
|
+
if (!hasWorktreeChanges(wt.path)) {
|
|
116
|
+
removeWorktree(opts.cwd ?? process.cwd(), wt.path, wt.branch);
|
|
117
|
+
agent.worktree = undefined;
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
this.emit("status", agentId, `Worktree preserved with changes: ${wt.path} (branch: ${wt.branch})`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
97
123
|
this.processes.delete(agentId);
|
|
98
124
|
this.emit("exit", agentId, code);
|
|
99
125
|
});
|
|
@@ -131,20 +157,30 @@ export class AgentSpawner extends EventEmitter {
|
|
|
131
157
|
break;
|
|
132
158
|
case "done":
|
|
133
159
|
if (agent) {
|
|
134
|
-
|
|
135
|
-
agent.finishedAt = Date.now();
|
|
160
|
+
// Don't mark as "done" status — child stays alive and will go idle
|
|
136
161
|
agent.result = msg.result;
|
|
137
162
|
}
|
|
138
163
|
this.emit("done", msg.agentId, msg.result);
|
|
139
164
|
break;
|
|
140
165
|
case "error":
|
|
141
166
|
if (agent) {
|
|
142
|
-
agent.status = "error";
|
|
143
|
-
agent.finishedAt = Date.now();
|
|
144
167
|
agent.error = msg.error;
|
|
145
168
|
}
|
|
146
169
|
this.emit("error", msg.agentId, msg.error);
|
|
147
170
|
break;
|
|
171
|
+
case "idle":
|
|
172
|
+
if (agent) {
|
|
173
|
+
agent.status = "idle";
|
|
174
|
+
}
|
|
175
|
+
this.emit("idle", msg.agentId, msg.idleReason, msg.dmSummaries);
|
|
176
|
+
break;
|
|
177
|
+
case "shutdown_approved":
|
|
178
|
+
if (agent) {
|
|
179
|
+
agent.status = "done";
|
|
180
|
+
agent.finishedAt = Date.now();
|
|
181
|
+
}
|
|
182
|
+
this.emit("shutdown_approved", msg.agentId);
|
|
183
|
+
break;
|
|
148
184
|
}
|
|
149
185
|
}
|
|
150
186
|
/** Route a direct message from one agent to another. */
|
|
@@ -179,6 +215,41 @@ export class AgentSpawner extends EventEmitter {
|
|
|
179
215
|
child.send({ type: "deliver_message", from: from ?? "user", content: message });
|
|
180
216
|
return true;
|
|
181
217
|
}
|
|
218
|
+
/** Wake an idle agent with a new task or message. */
|
|
219
|
+
wakeAgent(agentId, opts) {
|
|
220
|
+
const child = this.processes.get(agentId);
|
|
221
|
+
const agent = this.agents.get(agentId);
|
|
222
|
+
if (!child || !agent || agent.status !== "idle")
|
|
223
|
+
return false;
|
|
224
|
+
agent.status = "running";
|
|
225
|
+
child.send({ type: "wake", task: opts?.task, message: opts?.message, from: opts?.from });
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
/** Request graceful shutdown — waits for ShutdownApproved or force kills after timeout. */
|
|
229
|
+
requestShutdown(agentId, timeoutMs = 10_000) {
|
|
230
|
+
const child = this.processes.get(agentId);
|
|
231
|
+
if (!child)
|
|
232
|
+
return Promise.resolve(false);
|
|
233
|
+
child.send({ type: "shutdown_request" });
|
|
234
|
+
return new Promise((resolve) => {
|
|
235
|
+
const onApproved = (id) => {
|
|
236
|
+
if (id === agentId) {
|
|
237
|
+
clearTimeout(timer);
|
|
238
|
+
this.removeListener("shutdown_approved", onApproved);
|
|
239
|
+
resolve(true);
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
const timer = setTimeout(() => {
|
|
243
|
+
this.removeListener("shutdown_approved", onApproved);
|
|
244
|
+
// Force kill
|
|
245
|
+
if (this.processes.has(agentId)) {
|
|
246
|
+
child.kill();
|
|
247
|
+
}
|
|
248
|
+
resolve(false);
|
|
249
|
+
}, timeoutMs);
|
|
250
|
+
this.on("shutdown_approved", onApproved);
|
|
251
|
+
});
|
|
252
|
+
}
|
|
182
253
|
/** Get the current state of an agent. */
|
|
183
254
|
getAgent(agentId) {
|
|
184
255
|
return this.agents.get(agentId);
|
|
@@ -191,12 +262,18 @@ export class AgentSpawner extends EventEmitter {
|
|
|
191
262
|
getAgentsByStatus(status) {
|
|
192
263
|
return [...this.agents.values()].filter((a) => a.status === status);
|
|
193
264
|
}
|
|
194
|
-
/** Shut down all running agents
|
|
265
|
+
/** Shut down all running and idle agents gracefully, then force-kill stragglers. */
|
|
195
266
|
async shutdown() {
|
|
267
|
+
// Request graceful shutdown for idle agents (they can exit cleanly)
|
|
268
|
+
const idle = this.getAgentsByStatus("idle");
|
|
269
|
+
const shutdownPromises = idle.map((a) => this.requestShutdown(a.id, 5_000));
|
|
270
|
+
// Cancel running agents (they're mid-task, can't wait)
|
|
196
271
|
const running = this.getAgentsByStatus("running");
|
|
197
272
|
for (const agent of running) {
|
|
198
273
|
this.cancel(agent.id);
|
|
199
274
|
}
|
|
275
|
+
// Wait for graceful shutdowns
|
|
276
|
+
await Promise.all(shutdownPromises);
|
|
200
277
|
// Wait for all processes to exit (max 10s)
|
|
201
278
|
if (this.processes.size > 0) {
|
|
202
279
|
await new Promise((resolve) => {
|
|
@@ -207,10 +284,10 @@ export class AgentSpawner extends EventEmitter {
|
|
|
207
284
|
};
|
|
208
285
|
setTimeout(() => {
|
|
209
286
|
// Force kill remaining
|
|
210
|
-
for (const [
|
|
287
|
+
for (const [, child] of this.processes) {
|
|
211
288
|
child.kill();
|
|
212
|
-
this.processes.delete(id);
|
|
213
289
|
}
|
|
290
|
+
this.processes.clear();
|
|
214
291
|
resolve();
|
|
215
292
|
}, 10_000);
|
|
216
293
|
check();
|
|
@@ -28,118 +28,134 @@ export function detectLanguage(filename) {
|
|
|
28
28
|
return EXT_MAP[lower] ?? "generic";
|
|
29
29
|
}
|
|
30
30
|
// Helper: replace matches while preserving non-matched segments
|
|
31
|
-
function colorize(line, rules) {
|
|
31
|
+
function colorize(line, rules, resetSeq = RESET) {
|
|
32
32
|
// We process rules sequentially; each rule operates on uncolored segments only.
|
|
33
33
|
// Segments already colored are wrapped in \x1b and end with RESET.
|
|
34
34
|
let result = line;
|
|
35
35
|
for (const [re, color] of rules) {
|
|
36
|
-
result = result.replace(re, (match) => `${color}${match}${
|
|
36
|
+
result = result.replace(re, (match) => `${color}${match}${resetSeq}`);
|
|
37
37
|
}
|
|
38
38
|
return result;
|
|
39
39
|
}
|
|
40
40
|
// ── TypeScript / JavaScript ─────────────────────────────────────────
|
|
41
41
|
const TS_KEYWORDS = /\b(const|let|var|function|return|if|else|for|while|do|switch|case|break|continue|new|typeof|instanceof|void|delete|throw|try|catch|finally|import|export|from|default|class|extends|implements|async|await|yield|type|interface|enum|namespace|declare|readonly|abstract|static|get|set|of|in|as|is)\b/g;
|
|
42
|
-
const tsHighlight = (line) => {
|
|
42
|
+
const tsHighlight = (line, colors) => {
|
|
43
|
+
const commentColor = colors?.comment ?? GRAY;
|
|
44
|
+
const rst = colors?.reset ?? RESET;
|
|
43
45
|
// Single-line comment
|
|
44
46
|
const commentIdx = line.indexOf("//");
|
|
45
47
|
if (commentIdx !== -1 && !isInsideString(line, commentIdx)) {
|
|
46
48
|
const code = line.slice(0, commentIdx);
|
|
47
49
|
const comment = line.slice(commentIdx);
|
|
48
|
-
return highlightTSCode(code) + `${
|
|
50
|
+
return highlightTSCode(code, colors) + `${commentColor}${comment}${rst}`;
|
|
49
51
|
}
|
|
50
52
|
// Block comment (whole line)
|
|
51
53
|
if (line.trimStart().startsWith("/*") || line.trimStart().startsWith("*")) {
|
|
52
|
-
return `${
|
|
54
|
+
return `${commentColor}${line}${rst}`;
|
|
53
55
|
}
|
|
54
|
-
return highlightTSCode(line);
|
|
56
|
+
return highlightTSCode(line, colors);
|
|
55
57
|
};
|
|
56
|
-
function highlightTSCode(line) {
|
|
58
|
+
function highlightTSCode(line, colors) {
|
|
59
|
+
const rst = colors?.reset ?? RESET;
|
|
57
60
|
return colorize(line, [
|
|
58
|
-
[/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g, GREEN], // strings
|
|
59
|
-
[/\b\d+(\.\d+)?\b/g, YELLOW], // numbers
|
|
60
|
-
[TS_KEYWORDS, MAGENTA], // keywords
|
|
61
|
-
[/(?<=[:]\s*)\b[A-Z]\w*/g, CYAN], // types after :
|
|
62
|
-
[/(?<=\bas\s+)\b[A-Z]\w*/g, CYAN], // types after as
|
|
63
|
-
]);
|
|
61
|
+
[/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g, colors?.string ?? GREEN], // strings
|
|
62
|
+
[/\b\d+(\.\d+)?\b/g, colors?.number ?? YELLOW], // numbers
|
|
63
|
+
[TS_KEYWORDS, colors?.keyword ?? MAGENTA], // keywords
|
|
64
|
+
[/(?<=[:]\s*)\b[A-Z]\w*/g, colors?.type ?? CYAN], // types after :
|
|
65
|
+
[/(?<=\bas\s+)\b[A-Z]\w*/g, colors?.type ?? CYAN], // types after as
|
|
66
|
+
], rst);
|
|
64
67
|
}
|
|
65
68
|
// ── Python ──────────────────────────────────────────────────────────
|
|
66
69
|
const PY_KEYWORDS = /\b(def|class|if|elif|else|for|while|return|import|from|with|as|try|except|finally|raise|pass|break|continue|yield|lambda|and|or|not|in|is|None|True|False|global|nonlocal|assert|del|async|await)\b/g;
|
|
67
|
-
const pyHighlight = (line) => {
|
|
70
|
+
const pyHighlight = (line, colors) => {
|
|
71
|
+
const commentColor = colors?.comment ?? GRAY;
|
|
72
|
+
const rst = colors?.reset ?? RESET;
|
|
68
73
|
// Comment
|
|
69
74
|
const hashIdx = line.indexOf("#");
|
|
70
75
|
if (hashIdx !== -1 && !isInsideString(line, hashIdx)) {
|
|
71
76
|
const code = line.slice(0, hashIdx);
|
|
72
77
|
const comment = line.slice(hashIdx);
|
|
73
|
-
return highlightPYCode(code) + `${
|
|
78
|
+
return highlightPYCode(code, colors) + `${commentColor}${comment}${rst}`;
|
|
74
79
|
}
|
|
75
80
|
// Decorator
|
|
76
81
|
if (line.trimStart().startsWith("@")) {
|
|
77
|
-
return `${YELLOW}${line}${
|
|
82
|
+
return `${colors?.variable ?? YELLOW}${line}${rst}`;
|
|
78
83
|
}
|
|
79
|
-
return highlightPYCode(line);
|
|
84
|
+
return highlightPYCode(line, colors);
|
|
80
85
|
};
|
|
81
|
-
function highlightPYCode(line) {
|
|
86
|
+
function highlightPYCode(line, colors) {
|
|
87
|
+
const rst = colors?.reset ?? RESET;
|
|
82
88
|
return colorize(line, [
|
|
83
|
-
[/""".*?"""|'''.*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, GREEN], // strings
|
|
84
|
-
[/\b\d+(\.\d+)?\b/g, YELLOW], // numbers
|
|
85
|
-
[PY_KEYWORDS, MAGENTA], // keywords
|
|
86
|
-
]);
|
|
89
|
+
[/""".*?"""|'''.*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, colors?.string ?? GREEN], // strings
|
|
90
|
+
[/\b\d+(\.\d+)?\b/g, colors?.number ?? YELLOW], // numbers
|
|
91
|
+
[PY_KEYWORDS, colors?.keyword ?? MAGENTA], // keywords
|
|
92
|
+
], rst);
|
|
87
93
|
}
|
|
88
94
|
// ── Bash / Shell ────────────────────────────────────────────────────
|
|
89
95
|
const BASH_KEYWORDS = /\b(if|then|else|elif|fi|for|do|done|while|until|case|esac|in|function|select|time|coproc|local|export|declare|unset|readonly|return|exit|source|eval)\b/g;
|
|
90
|
-
const bashHighlight = (line) => {
|
|
96
|
+
const bashHighlight = (line, colors) => {
|
|
97
|
+
const commentColor = colors?.comment ?? GRAY;
|
|
98
|
+
const rst = colors?.reset ?? RESET;
|
|
91
99
|
// Comment
|
|
92
100
|
const hashIdx = line.indexOf("#");
|
|
93
101
|
if (hashIdx === 0 || (hashIdx > 0 && line[hashIdx - 1] === " " && !isInsideString(line, hashIdx))) {
|
|
94
102
|
const code = line.slice(0, hashIdx);
|
|
95
103
|
const comment = line.slice(hashIdx);
|
|
96
|
-
return highlightBashCode(code) + `${
|
|
104
|
+
return highlightBashCode(code, colors) + `${commentColor}${comment}${rst}`;
|
|
97
105
|
}
|
|
98
|
-
return highlightBashCode(line);
|
|
106
|
+
return highlightBashCode(line, colors);
|
|
99
107
|
};
|
|
100
|
-
function highlightBashCode(line) {
|
|
108
|
+
function highlightBashCode(line, colors) {
|
|
109
|
+
const rst = colors?.reset ?? RESET;
|
|
101
110
|
return colorize(line, [
|
|
102
|
-
[/"(?:[^"\\]|\\.)*"|'[^']*'/g, GREEN], // strings
|
|
103
|
-
[/\$\{?\w+\}?/g, CYAN], // variables
|
|
104
|
-
[/\b\d+\b/g, YELLOW], // numbers
|
|
105
|
-
[BASH_KEYWORDS, MAGENTA], // keywords
|
|
111
|
+
[/"(?:[^"\\]|\\.)*"|'[^']*'/g, colors?.string ?? GREEN], // strings
|
|
112
|
+
[/\$\{?\w+\}?/g, colors?.variable ?? CYAN], // variables
|
|
113
|
+
[/\b\d+\b/g, colors?.number ?? YELLOW], // numbers
|
|
114
|
+
[BASH_KEYWORDS, colors?.keyword ?? MAGENTA], // keywords
|
|
106
115
|
[/(?<=\|\s*)\w+/g, BOLD], // commands after pipe
|
|
107
|
-
]);
|
|
116
|
+
], rst);
|
|
108
117
|
}
|
|
109
118
|
// ── JSON ────────────────────────────────────────────────────────────
|
|
110
|
-
const jsonHighlight = (line) => {
|
|
119
|
+
const jsonHighlight = (line, colors) => {
|
|
120
|
+
const rst = colors?.reset ?? RESET;
|
|
111
121
|
return colorize(line, [
|
|
112
|
-
[/"[^"]*"\s*(?=:)/g, CYAN], // keys
|
|
113
|
-
[/:\s*"[^"]*"/g, GREEN], // string values
|
|
114
|
-
[/\b\d+(\.\d+)?([eE][+-]?\d+)?\b/g, YELLOW], // numbers
|
|
115
|
-
[/\b(true|false|null)\b/g, MAGENTA], // literals
|
|
116
|
-
]);
|
|
122
|
+
[/"[^"]*"\s*(?=:)/g, colors?.type ?? CYAN], // keys
|
|
123
|
+
[/:\s*"[^"]*"/g, colors?.string ?? GREEN], // string values
|
|
124
|
+
[/\b\d+(\.\d+)?([eE][+-]?\d+)?\b/g, colors?.number ?? YELLOW], // numbers
|
|
125
|
+
[/\b(true|false|null)\b/g, colors?.keyword ?? MAGENTA], // literals
|
|
126
|
+
], rst);
|
|
117
127
|
};
|
|
118
128
|
// ── CSS / SCSS ──────────────────────────────────────────────────────
|
|
119
|
-
const cssHighlight = (line) => {
|
|
129
|
+
const cssHighlight = (line, colors) => {
|
|
130
|
+
const commentColor = colors?.comment ?? GRAY;
|
|
131
|
+
const selectorColor = colors?.type ?? CYAN;
|
|
132
|
+
const propColor = colors?.keyword ?? MAGENTA;
|
|
133
|
+
const valColor = colors?.string ?? GREEN;
|
|
134
|
+
const rst = colors?.reset ?? RESET;
|
|
120
135
|
const trimmed = line.trimStart();
|
|
121
136
|
// Comment
|
|
122
137
|
if (trimmed.startsWith("/*") || trimmed.startsWith("*") || trimmed.startsWith("//")) {
|
|
123
|
-
return `${
|
|
138
|
+
return `${commentColor}${line}${rst}`;
|
|
124
139
|
}
|
|
125
140
|
// Selector line (no colon, or starts with . # & @ or tag)
|
|
126
141
|
if (/^[.#&@a-zA-Z]/.test(trimmed) && !trimmed.includes(":")) {
|
|
127
|
-
return `${
|
|
142
|
+
return `${selectorColor}${line}${rst}`;
|
|
128
143
|
}
|
|
129
144
|
// Property: value
|
|
130
145
|
const propMatch = line.match(/^(\s*)([\w-]+)(\s*:\s*)(.+)/);
|
|
131
146
|
if (propMatch) {
|
|
132
|
-
return `${propMatch[1]}${
|
|
147
|
+
return `${propMatch[1]}${propColor}${propMatch[2]}${rst}${propMatch[3]}${valColor}${propMatch[4]}${rst}`;
|
|
133
148
|
}
|
|
134
149
|
return line;
|
|
135
150
|
};
|
|
136
151
|
// ── Generic fallback ────────────────────────────────────────────────
|
|
137
|
-
const genericHighlight = (line) => {
|
|
152
|
+
const genericHighlight = (line, colors) => {
|
|
153
|
+
const rst = colors?.reset ?? RESET;
|
|
138
154
|
return colorize(line, [
|
|
139
|
-
[/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, GREEN], // strings
|
|
140
|
-
[/\/\/.*$|#.*$/g, GRAY], // comments
|
|
141
|
-
[/\b\d+(\.\d+)?\b/g, YELLOW], // numbers
|
|
142
|
-
]);
|
|
155
|
+
[/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, colors?.string ?? GREEN], // strings
|
|
156
|
+
[/\/\/.*$|#.*$/g, colors?.comment ?? GRAY], // comments
|
|
157
|
+
[/\b\d+(\.\d+)?\b/g, colors?.number ?? YELLOW], // numbers
|
|
158
|
+
], rst);
|
|
143
159
|
};
|
|
144
160
|
// ── Dispatcher ──────────────────────────────────────────────────────
|
|
145
161
|
const HIGHLIGHTERS = {
|
|
@@ -156,12 +172,12 @@ const HIGHLIGHTERS = {
|
|
|
156
172
|
* Highlight a code string for terminal output.
|
|
157
173
|
* Returns the input with ANSI color codes applied.
|
|
158
174
|
*/
|
|
159
|
-
export function highlightCode(code, language) {
|
|
175
|
+
export function highlightCode(code, language, colors) {
|
|
160
176
|
const lang = EXT_MAP[language.toLowerCase()] ?? language.toLowerCase();
|
|
161
177
|
const hl = HIGHLIGHTERS[lang] ?? genericHighlight;
|
|
162
178
|
return code
|
|
163
179
|
.split("\n")
|
|
164
|
-
.map((line) => hl(line))
|
|
180
|
+
.map((line) => hl(line, colors))
|
|
165
181
|
.join("\n");
|
|
166
182
|
}
|
|
167
183
|
// ── Utilities ───────────────────────────────────────────────────────
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { execSync } from "node:child_process";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import * as os from "node:os";
|
|
4
|
+
import * as fs from "node:fs";
|
|
5
|
+
const WORKTREE_BASE = path.join(os.homedir(), ".phren-agent", "worktrees");
|
|
6
|
+
/** Create a git worktree for an agent. Returns the worktree path. */
|
|
7
|
+
export function createWorktree(cwd, agentId) {
|
|
8
|
+
const safeName = agentId.replace(/[^a-zA-Z0-9-]/g, "-");
|
|
9
|
+
const worktreePath = path.join(WORKTREE_BASE, safeName);
|
|
10
|
+
const branch = `phren-agent/${safeName}`;
|
|
11
|
+
fs.mkdirSync(WORKTREE_BASE, { recursive: true });
|
|
12
|
+
// Create worktree with new branch
|
|
13
|
+
execSync(`git worktree add "${worktreePath}" -b "${branch}"`, { cwd, stdio: "pipe" });
|
|
14
|
+
return { path: worktreePath, branch, agentId };
|
|
15
|
+
}
|
|
16
|
+
/** Check if a worktree has uncommitted changes. */
|
|
17
|
+
export function hasWorktreeChanges(worktreePath) {
|
|
18
|
+
try {
|
|
19
|
+
const status = execSync("git status --porcelain", { cwd: worktreePath, encoding: "utf-8" });
|
|
20
|
+
return status.trim().length > 0;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Remove a worktree and its branch. */
|
|
27
|
+
export function removeWorktree(cwd, worktreePath, branch) {
|
|
28
|
+
try {
|
|
29
|
+
execSync(`git worktree remove "${worktreePath}" --force`, { cwd, stdio: "pipe" });
|
|
30
|
+
}
|
|
31
|
+
catch { /* already gone */ }
|
|
32
|
+
try {
|
|
33
|
+
execSync(`git branch -D "${branch}"`, { cwd, stdio: "pipe" });
|
|
34
|
+
}
|
|
35
|
+
catch { /* branch doesn't exist */ }
|
|
36
|
+
}
|
|
37
|
+
/** Clean up all stale phren-agent worktrees. */
|
|
38
|
+
export function cleanupStaleWorktrees(cwd) {
|
|
39
|
+
try {
|
|
40
|
+
execSync("git worktree prune", { cwd, stdio: "pipe" });
|
|
41
|
+
}
|
|
42
|
+
catch { /* not a git repo */ }
|
|
43
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as path from "path";
|
|
3
|
+
import { fileURLToPath } from "url";
|
|
4
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
5
|
+
const ROOT = path.join(__dirname, "..");
|
|
6
|
+
const PACKAGE_JSON_PATH = path.join(ROOT, "package.json");
|
|
7
|
+
function readPackageJson() {
|
|
8
|
+
return JSON.parse(fs.readFileSync(PACKAGE_JSON_PATH, "utf8"));
|
|
9
|
+
}
|
|
10
|
+
const PACKAGE_JSON = readPackageJson();
|
|
11
|
+
export const VERSION = PACKAGE_JSON.version || "0.0.0";
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { checkShellSafety } from "./shell-safety.js";
|
|
2
2
|
import { validatePath, checkSensitivePath } from "./sandbox.js";
|
|
3
3
|
import { isAllowed } from "./allowlist.js";
|
|
4
|
-
/** Tools that are safe in all modes — read-only, no side effects. */
|
|
4
|
+
/** Tools that are safe in all modes — read-only or agent management, no side effects. */
|
|
5
5
|
const ALWAYS_SAFE_TOOLS = new Set([
|
|
6
6
|
"phren_search",
|
|
7
7
|
"phren_get_tasks",
|
|
8
|
+
"spawn_agent",
|
|
9
|
+
"send_message_to_agent",
|
|
10
|
+
"list_agents",
|
|
8
11
|
]);
|
|
9
12
|
/** Tools that access file paths and need sensitive-path checks. */
|
|
10
13
|
const FILE_TOOLS = new Set([
|
|
@@ -102,6 +105,23 @@ export function checkPermission(config, toolName, input) {
|
|
|
102
105
|
}
|
|
103
106
|
}
|
|
104
107
|
return { verdict: "ask", reason: `Auto-confirm mode requires confirmation for "${toolName}".` };
|
|
108
|
+
case "plan":
|
|
109
|
+
// Plan mode: same as auto-confirm for permissions, but agent loop enables plan-first flow
|
|
110
|
+
if (AUTO_CONFIRM_TOOLS.has(toolName)) {
|
|
111
|
+
return { verdict: "allow", reason: `Plan mode allows "${toolName}".` };
|
|
112
|
+
}
|
|
113
|
+
if (toolName === "shell") {
|
|
114
|
+
const cwd = input.cwd || config.projectRoot;
|
|
115
|
+
const cwdResult = validatePath(cwd, config.projectRoot, config.allowedPaths);
|
|
116
|
+
if (cwdResult.ok) {
|
|
117
|
+
const cmd = input.command || "";
|
|
118
|
+
const safety = checkShellSafety(cmd);
|
|
119
|
+
if (safety.safe) {
|
|
120
|
+
return { verdict: "allow", reason: "Safe shell command within sandbox (plan mode)." };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return { verdict: "ask", reason: `Plan mode requires confirmation for "${toolName}".` };
|
|
105
125
|
case "full-auto":
|
|
106
126
|
// Full-auto: allow everything not denied or warned
|
|
107
127
|
return { verdict: "allow", reason: "Full-auto mode." };
|
|
@@ -3,20 +3,22 @@
|
|
|
3
3
|
* Same flow as Codex CLI, no middleman.
|
|
4
4
|
*/
|
|
5
5
|
import * as crypto from "crypto";
|
|
6
|
-
import * as fs from "fs";
|
|
7
|
-
import * as path from "path";
|
|
8
6
|
import * as http from "http";
|
|
9
|
-
import
|
|
7
|
+
import { authProfilesPath, getCodexAuthProfile, hasCodexAuthProfile, hasCodexCliAuth, removeCodexAuthProfile, upsertCodexAuthProfile, } from "@phren/cli/auth/profiles";
|
|
10
8
|
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
11
9
|
const AUTH_URL = "https://auth.openai.com/oauth/authorize";
|
|
12
10
|
const TOKEN_URL = "https://auth.openai.com/oauth/token";
|
|
13
11
|
const REDIRECT_URI = "http://localhost:1455/auth/callback";
|
|
14
12
|
const CALLBACK_PORT = 1455;
|
|
15
13
|
const SCOPES = "openid profile email offline_access";
|
|
16
|
-
function
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
function parseAccountId(accessToken) {
|
|
15
|
+
try {
|
|
16
|
+
const payload = JSON.parse(Buffer.from(accessToken.split(".")[1], "base64url").toString());
|
|
17
|
+
return payload.sub || payload.account_id;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
20
22
|
}
|
|
21
23
|
function generatePKCE() {
|
|
22
24
|
const bytes = crypto.randomBytes(32);
|
|
@@ -57,21 +59,16 @@ async function exchangeCode(code, codeVerifier) {
|
|
|
57
59
|
}
|
|
58
60
|
const data = await res.json();
|
|
59
61
|
const expiresIn = data.expires_in || 3600;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
try {
|
|
63
|
-
const payload = JSON.parse(Buffer.from(data.access_token.split(".")[1], "base64url").toString());
|
|
64
|
-
accountId = payload.sub || payload.account_id;
|
|
65
|
-
}
|
|
66
|
-
catch { /* skip */ }
|
|
62
|
+
const accessToken = data.access_token;
|
|
63
|
+
const accountId = parseAccountId(accessToken);
|
|
67
64
|
return {
|
|
68
|
-
access_token:
|
|
65
|
+
access_token: accessToken,
|
|
69
66
|
refresh_token: data.refresh_token,
|
|
70
67
|
expires_at: Date.now() + expiresIn * 1000,
|
|
71
68
|
account_id: accountId,
|
|
72
69
|
};
|
|
73
70
|
}
|
|
74
|
-
async function refreshToken(refreshTok) {
|
|
71
|
+
async function refreshToken(refreshTok, existingAccountId) {
|
|
75
72
|
const res = await fetch(TOKEN_URL, {
|
|
76
73
|
method: "POST",
|
|
77
74
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
@@ -87,10 +84,12 @@ async function refreshToken(refreshTok) {
|
|
|
87
84
|
}
|
|
88
85
|
const data = await res.json();
|
|
89
86
|
const expiresIn = data.expires_in || 3600;
|
|
87
|
+
const accessToken = data.access_token;
|
|
90
88
|
return {
|
|
91
|
-
access_token:
|
|
89
|
+
access_token: accessToken,
|
|
92
90
|
refresh_token: data.refresh_token || refreshTok,
|
|
93
91
|
expires_at: Date.now() + expiresIn * 1000,
|
|
92
|
+
account_id: parseAccountId(accessToken) ?? existingAccountId,
|
|
94
93
|
};
|
|
95
94
|
}
|
|
96
95
|
/** Interactive OAuth login — opens browser, waits for callback. */
|
|
@@ -154,44 +153,59 @@ export async function codexLogin() {
|
|
|
154
153
|
console.log("Exchanging code for tokens...");
|
|
155
154
|
const tokens = await exchangeCode(code, codeVerifier);
|
|
156
155
|
// Save tokens
|
|
157
|
-
|
|
158
|
-
|
|
156
|
+
upsertCodexAuthProfile({
|
|
157
|
+
accessToken: tokens.access_token,
|
|
158
|
+
refreshToken: tokens.refresh_token,
|
|
159
|
+
expiresAt: tokens.expires_at,
|
|
160
|
+
accountId: tokens.account_id,
|
|
161
|
+
lastRefresh: new Date().toISOString(),
|
|
162
|
+
source: "phren-oauth",
|
|
163
|
+
});
|
|
164
|
+
console.log(`Logged in! Token saved to ${authProfilesPath()}`);
|
|
159
165
|
}
|
|
160
166
|
// Lock so concurrent callers share a single in-flight refresh
|
|
161
167
|
let refreshPromise = null;
|
|
162
168
|
/** Load stored token, auto-refresh if expiring within 5 minutes. */
|
|
163
169
|
export async function getAccessToken() {
|
|
164
|
-
|
|
165
|
-
if (!
|
|
170
|
+
let profile = getCodexAuthProfile({ allowCliImport: true });
|
|
171
|
+
if (!profile) {
|
|
166
172
|
throw new Error("Not logged in to Codex. Run: phren-agent auth login");
|
|
167
173
|
}
|
|
168
|
-
let tokens = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
169
174
|
// Refresh if expiring within 5 minutes
|
|
170
|
-
if (
|
|
171
|
-
if (!
|
|
175
|
+
if (profile.expiresAt < Date.now() + 5 * 60 * 1000) {
|
|
176
|
+
if (!profile.refreshToken) {
|
|
172
177
|
throw new Error("Token expired and no refresh token. Run: phren-agent auth login");
|
|
173
178
|
}
|
|
174
179
|
if (!refreshPromise) {
|
|
175
180
|
console.error("Refreshing Codex token...");
|
|
176
|
-
refreshPromise = refreshToken(
|
|
181
|
+
refreshPromise = refreshToken(profile.refreshToken, profile.accountId).finally(() => { refreshPromise = null; });
|
|
177
182
|
}
|
|
178
|
-
|
|
179
|
-
|
|
183
|
+
const refreshed = await refreshPromise;
|
|
184
|
+
profile = upsertCodexAuthProfile({
|
|
185
|
+
accessToken: refreshed.access_token,
|
|
186
|
+
refreshToken: refreshed.refresh_token,
|
|
187
|
+
expiresAt: refreshed.expires_at,
|
|
188
|
+
accountId: refreshed.account_id ?? profile.accountId,
|
|
189
|
+
lastRefresh: new Date().toISOString(),
|
|
190
|
+
source: "phren-oauth",
|
|
191
|
+
});
|
|
180
192
|
}
|
|
181
|
-
return { accessToken:
|
|
193
|
+
return { accessToken: profile.accessToken, accountId: profile.accountId };
|
|
182
194
|
}
|
|
183
195
|
/** Check if user has a stored Codex token. */
|
|
184
196
|
export function hasCodexToken() {
|
|
185
|
-
return
|
|
197
|
+
return hasCodexAuthProfile({ allowCliImport: true });
|
|
186
198
|
}
|
|
187
199
|
/** Remove stored token. */
|
|
188
200
|
export function codexLogout() {
|
|
189
|
-
const
|
|
190
|
-
if (
|
|
191
|
-
|
|
192
|
-
console.log("Logged out of Codex.");
|
|
201
|
+
const removed = removeCodexAuthProfile();
|
|
202
|
+
if (!removed) {
|
|
203
|
+
console.log("No local Phren Codex profile found.");
|
|
193
204
|
}
|
|
194
205
|
else {
|
|
195
|
-
console.log("
|
|
206
|
+
console.log("Logged out of Codex in Phren.");
|
|
207
|
+
}
|
|
208
|
+
if (hasCodexCliAuth()) {
|
|
209
|
+
console.log("Codex CLI auth at ~/.codex/auth.json was left untouched.");
|
|
196
210
|
}
|
|
197
211
|
}
|