@phren/agent 0.1.15 → 0.3.5
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/README.md +86 -0
- package/dist/agent-loop/index.js +239 -65
- package/dist/agent-loop/stream.js +212 -29
- package/dist/agent-loop/types.js +15 -2
- package/dist/checkpoint.js +103 -22
- package/dist/commands/info.js +30 -15
- package/dist/commands/model.js +6 -2
- package/dist/commands/review.js +183 -0
- package/dist/commands/session.js +70 -7
- package/dist/commands.js +168 -12
- package/dist/config.js +87 -10
- package/dist/context/compactor.js +239 -0
- package/dist/context/pruner.js +39 -13
- package/dist/context/token-counter.js +33 -1
- package/dist/custom-commands.js +69 -0
- package/dist/guards/repeat-tool-reminder.js +75 -0
- package/dist/headless.js +115 -0
- package/dist/herdr-hooks.js +71 -0
- package/dist/index.js +351 -48
- package/dist/mcp-client.js +434 -73
- package/dist/mcp-oauth.js +121 -0
- package/dist/memory/anti-patterns.js +7 -3
- package/dist/memory/auto-capture.js +7 -3
- package/dist/memory/context.js +92 -73
- package/dist/memory/project-context.js +24 -5
- package/dist/memory/provenance.js +15 -0
- package/dist/memory/review-triage.js +166 -0
- package/dist/memory/session.js +36 -1
- package/dist/models.js +152 -19
- package/dist/multi/child-entry.js +65 -10
- package/dist/multi/diff-renderer.js +3 -3
- package/dist/multi/markdown.js +125 -27
- package/dist/multi/provider-manager.js +8 -0
- package/dist/multi/publish.js +72 -0
- package/dist/multi/spawner.js +45 -4
- package/dist/multi/syntax-highlight.js +25 -4
- package/dist/multi/types.js +1 -1
- package/dist/permissions/allowlist.js +86 -13
- package/dist/permissions/checker.js +42 -7
- package/dist/permissions/kernel-sandbox.js +197 -0
- package/dist/permissions/prompt.js +10 -1
- package/dist/permissions/sandbox.js +40 -17
- package/dist/providers/anthropic.js +154 -7
- package/dist/providers/codex-auth.js +28 -0
- package/dist/providers/codex.js +134 -23
- package/dist/providers/history.js +35 -0
- package/dist/providers/ollama.js +37 -6
- package/dist/providers/openai-compat.js +171 -74
- package/dist/providers/openrouter.js +47 -17
- package/dist/providers/replay.js +62 -0
- package/dist/providers/resolve.js +41 -7
- package/dist/providers/retry.js +38 -5
- package/dist/providers/types.js +9 -1
- package/dist/repl.js +47 -5
- package/dist/session/log.js +217 -0
- package/dist/session/persist.js +190 -0
- package/dist/settings.js +42 -26
- package/dist/system-prompt.js +18 -2
- package/dist/tools/apply-patch.js +355 -0
- package/dist/tools/edit-engine.js +287 -0
- package/dist/tools/edit-file.js +86 -27
- package/dist/tools/grep.js +25 -10
- package/dist/tools/lint-test.js +0 -22
- package/dist/tools/mcp-resources.js +51 -6
- package/dist/tools/phren-finding.js +12 -4
- package/dist/tools/phren-search.js +7 -2
- package/dist/tools/read-file.js +37 -9
- package/dist/tools/read-image.js +76 -0
- package/dist/tools/registry.js +27 -5
- package/dist/tools/shell.js +134 -71
- package/dist/tools/skill.js +20 -20
- package/dist/tools/spawn-agent.js +77 -13
- package/dist/tools/update-plan.js +48 -0
- package/dist/tools/web-fetch.js +110 -12
- package/dist/tools/web-search.js +4 -4
- package/dist/tui/components/App.js +98 -26
- package/dist/tui/components/ApprovalPanel.js +8 -0
- package/dist/tui/components/InputArea.js +5 -5
- package/dist/tui/components/ModelPicker.js +43 -0
- package/dist/tui/components/PhrenInput.js +10 -5
- package/dist/tui/components/PlanReview.js +7 -0
- package/dist/tui/components/ShortcutHelp.js +5 -0
- package/dist/tui/components/StatusBar.js +46 -20
- package/dist/tui/components/SteerQueue.js +1 -1
- package/dist/tui/components/ThinkingIndicator.js +6 -4
- package/dist/tui/components/ToolCall.js +10 -4
- package/dist/tui/components/ToolDetail.js +21 -0
- package/dist/tui/help.js +6 -0
- package/dist/tui/hooks/useKeyboardShortcuts.js +15 -1
- package/dist/tui/index.js +0 -1
- package/dist/tui/ink-entry.js +317 -33
- package/dist/tui/tool-render.js +1 -1
- package/dist/user-hooks.js +171 -0
- package/package.json +14 -8
- package/dist/multi/multi-commands.js +0 -170
- package/dist/multi/multi-events.js +0 -98
- package/dist/multi/multi-render.js +0 -147
- package/dist/multi/pane.js +0 -28
- package/dist/multi/tui-multi.js +0 -200
- package/dist/permissions/privacy.js +0 -248
- package/dist/tui/components/AgentMessage.js +0 -5
- package/dist/tui/components/ChatMessage.js +0 -23
- package/dist/tui/components/CodeBlock.js +0 -8
- package/dist/tui/components/Separator.js +0 -7
- package/dist/tui/components/StreamingText.js +0 -5
- package/dist/tui/components/UserMessage.js +0 -5
- package/dist/tui/menu-mode.js +0 -86
- package/dist/tui/mouse.js +0 -71
- package/dist/tui/terminal-control.js +0 -62
- package/dist/tui.js +0 -781
package/dist/index.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { parseArgs, printHelp } from "./config.js";
|
|
2
|
+
import { parseArgs, printHelp, resolveStartupPermissions } from "./config.js";
|
|
3
|
+
import { loadPersistentAllowlist } from "./permissions/allowlist.js";
|
|
3
4
|
import { resolveProvider } from "./providers/resolve.js";
|
|
4
5
|
import { ToolRegistry } from "./tools/registry.js";
|
|
5
6
|
import { readFileTool } from "./tools/read-file.js";
|
|
6
7
|
import { writeFileTool } from "./tools/write-file.js";
|
|
7
|
-
import { editFileTool } from "./tools/edit-file.js";
|
|
8
|
-
import {
|
|
8
|
+
import { editFileTool, multiEditTool } from "./tools/edit-file.js";
|
|
9
|
+
import { applyPatchTool } from "./tools/apply-patch.js";
|
|
10
|
+
import { createShellTool, taskOutputTool, taskStopTool } from "./tools/shell.js";
|
|
9
11
|
import { globTool } from "./tools/glob.js";
|
|
10
12
|
import { grepTool } from "./tools/grep.js";
|
|
13
|
+
import { createReadImageTool } from "./tools/read-image.js";
|
|
14
|
+
import { modelSupportsVision } from "./models.js";
|
|
11
15
|
import { createWebFetchTool } from "./tools/web-fetch.js";
|
|
12
16
|
import { createWebSearchTool } from "./tools/web-search.js";
|
|
13
17
|
import { createPhrenAddTaskTool } from "./tools/phren-add-task.js";
|
|
@@ -16,12 +20,19 @@ import { createPhrenSearchTool } from "./tools/phren-search.js";
|
|
|
16
20
|
import { createPhrenFindingTool } from "./tools/phren-finding.js";
|
|
17
21
|
import { createPhrenGetTasksTool, createPhrenCompleteTaskTool } from "./tools/phren-tasks.js";
|
|
18
22
|
import { gitStatusTool, gitDiffTool, gitCommitTool } from "./tools/git.js";
|
|
23
|
+
import { updatePlanTool } from "./tools/update-plan.js";
|
|
19
24
|
import { listMcpResourcesTool, readMcpResourceTool } from "./tools/mcp-resources.js";
|
|
20
|
-
import { buildPhrenContext, buildContextSnippet } from "./memory/context.js";
|
|
21
|
-
import { startSession, endSession, getPriorSummary, saveSessionMessages, loadLastSessionSnapshot } from "./memory/session.js";
|
|
25
|
+
import { buildPhrenContext, buildContextSnippet, buildProjectInstructions } from "./memory/context.js";
|
|
26
|
+
import { startSession, endSession, getPriorSummary, saveSessionMessages, loadLastSessionSnapshot, writeSessionNote } from "./memory/session.js";
|
|
27
|
+
import { emitHerdrHook, setHerdrHookSession } from "./herdr-hooks.js";
|
|
22
28
|
import { loadProjectContext, evolveProjectContext } from "./memory/project-context.js";
|
|
23
29
|
import { buildSystemPrompt } from "./system-prompt.js";
|
|
24
|
-
import {
|
|
30
|
+
import { loadHooksConfig } from "./user-hooks.js";
|
|
31
|
+
import { loadAndRegisterCustomCommands, getCustomCommandInfos } from "./commands.js";
|
|
32
|
+
import { createSession, runTurn } from "./agent-loop.js";
|
|
33
|
+
import { SessionLog, seedFromMessages } from "./session/log.js";
|
|
34
|
+
import { fileSink, findEventLogById, findLatestEventLog, listEventLogs, persistFork, restoreSessionLog } from "./session/persist.js";
|
|
35
|
+
import { buildHeadlessResult, createHeadlessHooks, headlessExitCode, readStdin } from "./headless.js";
|
|
25
36
|
import { createCostTracker } from "./cost.js";
|
|
26
37
|
import { codexLogin, codexLogout } from "./providers/codex-auth.js";
|
|
27
38
|
import { createCheckpoint } from "./checkpoint.js";
|
|
@@ -103,7 +114,16 @@ export async function runAgentCli(raw) {
|
|
|
103
114
|
console.error("Usage: phren auth <login|logout|status|set-key|clear-key>");
|
|
104
115
|
process.exit(1);
|
|
105
116
|
}
|
|
106
|
-
|
|
117
|
+
let args;
|
|
118
|
+
try {
|
|
119
|
+
args = parseArgs(raw);
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
123
|
+
process.exit(1);
|
|
124
|
+
}
|
|
125
|
+
resolveStartupPermissions(args);
|
|
126
|
+
loadPersistentAllowlist(process.cwd());
|
|
107
127
|
if (args.help) {
|
|
108
128
|
printHelp();
|
|
109
129
|
process.exit(0);
|
|
@@ -112,6 +132,45 @@ export async function runAgentCli(raw) {
|
|
|
112
132
|
console.log(`phren-agent v${VERSION}`);
|
|
113
133
|
process.exit(0);
|
|
114
134
|
}
|
|
135
|
+
// Model switches and spawned children resolve the provider again; they
|
|
136
|
+
// read the endpoint from the environment.
|
|
137
|
+
if (args.baseUrl)
|
|
138
|
+
process.env.PHREN_AGENT_BASE_URL = args.baseUrl;
|
|
139
|
+
if (args.listSessions) {
|
|
140
|
+
const ctx = await buildPhrenContext(args.project);
|
|
141
|
+
if (!ctx) {
|
|
142
|
+
console.error("Sessions are stored in the phren store; none was found.");
|
|
143
|
+
process.exit(1);
|
|
144
|
+
}
|
|
145
|
+
const sessions = listEventLogs(ctx.phrenPath, { project: args.project ?? undefined, limit: 20 });
|
|
146
|
+
if (args.outputFormat === "json") {
|
|
147
|
+
console.log(JSON.stringify(sessions.map(({ file: _file, ...rest }) => ({ ...rest, updatedAt: new Date(rest.mtimeMs).toISOString() })), null, 2));
|
|
148
|
+
}
|
|
149
|
+
else if (sessions.length === 0) {
|
|
150
|
+
console.log("No sessions.");
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
for (const s of sessions) {
|
|
154
|
+
const when = new Date(s.mtimeMs).toISOString().replace("T", " ").slice(0, 16);
|
|
155
|
+
console.log(`${s.sessionId.slice(0, 12)} ${when} ${String(s.messages).padStart(4)} msgs ${s.project ?? "-"} ${s.title}`);
|
|
156
|
+
}
|
|
157
|
+
console.log("\nResume one with: phren-agent --session <id>");
|
|
158
|
+
}
|
|
159
|
+
process.exit(0);
|
|
160
|
+
}
|
|
161
|
+
// Headless with no task argument: read the task from piped stdin.
|
|
162
|
+
if (args.print && !args.task && !process.stdin.isTTY) {
|
|
163
|
+
args.task = (await readStdin()).trim();
|
|
164
|
+
}
|
|
165
|
+
if (args.print) {
|
|
166
|
+
args.interactive = false;
|
|
167
|
+
args.multi = false;
|
|
168
|
+
}
|
|
169
|
+
// `--resume` alone continues the prior session without a placeholder task
|
|
170
|
+
const userTask = args.task;
|
|
171
|
+
if (!args.task && args.resume) {
|
|
172
|
+
args.task = "Continue where the previous session left off.";
|
|
173
|
+
}
|
|
115
174
|
if (!args.task && !args.interactive && !args.multi && !args.team) {
|
|
116
175
|
console.error("Usage: phren-agent <task>\nRun phren-agent --help for more info.");
|
|
117
176
|
process.exit(1);
|
|
@@ -119,7 +178,7 @@ export async function runAgentCli(raw) {
|
|
|
119
178
|
// Resolve LLM provider
|
|
120
179
|
let provider;
|
|
121
180
|
try {
|
|
122
|
-
provider = resolveProvider(args.provider, args.model, args.maxOutput, args.reasoning);
|
|
181
|
+
provider = resolveProvider(args.provider, args.model, args.maxOutput, args.reasoning, { baseUrl: args.baseUrl });
|
|
123
182
|
}
|
|
124
183
|
catch (err) {
|
|
125
184
|
console.error(err instanceof Error ? err.message : String(err));
|
|
@@ -137,19 +196,50 @@ export async function runAgentCli(raw) {
|
|
|
137
196
|
if (args.verbose) {
|
|
138
197
|
process.stderr.write(`Phren: ${phrenCtx.phrenPath} (project: ${phrenCtx.project ?? "none"})\n`);
|
|
139
198
|
}
|
|
199
|
+
// Review-queue surfacing. Interactive sessions get expiry + a triage
|
|
200
|
+
// banner; one-shot runs get a count only and never mutate the queue.
|
|
201
|
+
if (phrenCtx.project) {
|
|
202
|
+
try {
|
|
203
|
+
const { getQueueStatus, formatQueueBanner, formatExpiryNotice, expireStaleItems, resolveExpireDays } = await import("./memory/review-triage.js");
|
|
204
|
+
if (args.interactive || args.multi || args.team) {
|
|
205
|
+
const expireDays = resolveExpireDays();
|
|
206
|
+
const notice = formatExpiryNotice(expireStaleItems(phrenCtx, expireDays));
|
|
207
|
+
if (notice) {
|
|
208
|
+
process.stderr.write(`\x1b[2m[${notice} — older than ${expireDays}d]\x1b[0m\n`);
|
|
209
|
+
}
|
|
210
|
+
const banner = formatQueueBanner(getQueueStatus(phrenCtx, 3));
|
|
211
|
+
if (banner)
|
|
212
|
+
process.stderr.write(`\x1b[33m${banner}\x1b[0m\n`);
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
const { pending } = getQueueStatus(phrenCtx, 0);
|
|
216
|
+
if (pending > 0) {
|
|
217
|
+
process.stderr.write(`\x1b[2m[review queue: ${pending} pending — run phren-agent -i, then /review]\x1b[0m\n`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
catch { /* best effort */ }
|
|
222
|
+
}
|
|
140
223
|
contextSnippet = await buildContextSnippet(phrenCtx, args.task);
|
|
141
224
|
priorSummary = getPriorSummary(phrenCtx);
|
|
142
225
|
sessionId = startSession(phrenCtx);
|
|
226
|
+
// Inside a Herdr pane, tell Phren Hook which event log is this pane's.
|
|
227
|
+
setHerdrHookSession(sessionId);
|
|
228
|
+
emitHerdrHook("SessionStart");
|
|
143
229
|
// Load evolved project context for warm start
|
|
144
230
|
const projectCtx = loadProjectContext(phrenCtx);
|
|
145
231
|
if (projectCtx) {
|
|
146
232
|
contextSnippet += `\n\n## Agent context (${phrenCtx.project})\n\n${projectCtx}`;
|
|
147
233
|
}
|
|
148
234
|
}
|
|
235
|
+
// Without a phren store, the repo's AGENTS.md / CLAUDE.md still apply.
|
|
236
|
+
if (!phrenCtx)
|
|
237
|
+
contextSnippet = buildProjectInstructions();
|
|
238
|
+
loadAndRegisterCustomCommands(process.cwd());
|
|
149
239
|
const systemPrompt = buildSystemPrompt(contextSnippet, priorSummary, {
|
|
150
240
|
name: provider.name,
|
|
151
241
|
model: provider.model,
|
|
152
|
-
});
|
|
242
|
+
}, getCustomCommandInfos());
|
|
153
243
|
// Dry run: print system prompt and exit
|
|
154
244
|
if (args.dryRun) {
|
|
155
245
|
console.log("=== System Prompt ===");
|
|
@@ -160,19 +250,38 @@ export async function runAgentCli(raw) {
|
|
|
160
250
|
}
|
|
161
251
|
// Register tools
|
|
162
252
|
const registry = new ToolRegistry();
|
|
253
|
+
registry.hookConfig = loadHooksConfig(process.cwd());
|
|
163
254
|
registry.setPermissions({
|
|
164
255
|
mode: args.permissions,
|
|
165
256
|
allowedPaths: [],
|
|
166
257
|
projectRoot: process.cwd(),
|
|
258
|
+
sandboxMode: args.sandbox,
|
|
167
259
|
});
|
|
260
|
+
// Nobody can answer a prompt in a headless run or with stdin not a
|
|
261
|
+
// terminal (a readline question on a closed stdin would hang): deny, and
|
|
262
|
+
// say how to allow.
|
|
263
|
+
let permissionDenials = 0;
|
|
264
|
+
if (args.print || (!process.stdin.isTTY && !args.interactive && !args.multi && !args.team)) {
|
|
265
|
+
registry.askUser = async (toolName, _input, reason) => {
|
|
266
|
+
permissionDenials++;
|
|
267
|
+
process.stderr.write(`[denied ${toolName}: ${reason} No one is present to approve; rerun with --permissions auto-confirm or --yolo to allow.]\n`);
|
|
268
|
+
return false;
|
|
269
|
+
};
|
|
270
|
+
}
|
|
168
271
|
registry.register(readFileTool);
|
|
169
272
|
registry.register(writeFileTool);
|
|
170
273
|
registry.register(editFileTool);
|
|
171
|
-
registry.register(
|
|
274
|
+
registry.register(multiEditTool);
|
|
275
|
+
registry.register(applyPatchTool);
|
|
276
|
+
// Live-config factory: /permissions and sandbox mode changes apply per call
|
|
277
|
+
registry.register(createShellTool(() => registry.permissionConfig));
|
|
172
278
|
registry.register(taskOutputTool);
|
|
173
279
|
registry.register(taskStopTool);
|
|
174
280
|
registry.register(globTool);
|
|
175
281
|
registry.register(grepTool);
|
|
282
|
+
if (modelSupportsVision(provider.name, provider.model ?? "")) {
|
|
283
|
+
registry.register(createReadImageTool(provider));
|
|
284
|
+
}
|
|
176
285
|
if (phrenCtx) {
|
|
177
286
|
registry.register(createPhrenSearchTool(phrenCtx));
|
|
178
287
|
registry.register(createPhrenFindingTool(phrenCtx, sessionId));
|
|
@@ -187,6 +296,7 @@ export async function runAgentCli(raw) {
|
|
|
187
296
|
registry.register(gitStatusTool);
|
|
188
297
|
registry.register(gitDiffTool);
|
|
189
298
|
registry.register(gitCommitTool);
|
|
299
|
+
registry.register(updatePlanTool);
|
|
190
300
|
registry.register(listMcpResourcesTool);
|
|
191
301
|
registry.register(readMcpResourceTool);
|
|
192
302
|
// MCP server connections
|
|
@@ -219,6 +329,71 @@ export async function runAgentCli(raw) {
|
|
|
219
329
|
if (lintTestConfig.testCmd)
|
|
220
330
|
process.stderr.write(`Test: ${lintTestConfig.testCmd}\n`);
|
|
221
331
|
}
|
|
332
|
+
/** Durable event log for this run when a phren store is available. */
|
|
333
|
+
const makePersistedLog = () => {
|
|
334
|
+
if (!phrenCtx || !sessionId)
|
|
335
|
+
return undefined;
|
|
336
|
+
return new SessionLog({
|
|
337
|
+
sessionId,
|
|
338
|
+
project: phrenCtx.project ?? undefined,
|
|
339
|
+
cwd: process.cwd(),
|
|
340
|
+
createdAt: new Date().toISOString(),
|
|
341
|
+
}, fileSink(phrenCtx.phrenPath, sessionId));
|
|
342
|
+
};
|
|
343
|
+
/**
|
|
344
|
+
* Resume seed: newest event log preferred, legacy v1 snapshot as fallback.
|
|
345
|
+
* MUST run before makePersistedLog(): creating this run's own (empty) log
|
|
346
|
+
* first would make it the newest discovery candidate and shadow the real
|
|
347
|
+
* previous session.
|
|
348
|
+
*/
|
|
349
|
+
const makeResumedLog = () => {
|
|
350
|
+
if (!phrenCtx || !sessionId)
|
|
351
|
+
return undefined;
|
|
352
|
+
let latest;
|
|
353
|
+
if (args.resumeId) {
|
|
354
|
+
try {
|
|
355
|
+
latest = findEventLogById(phrenCtx.phrenPath, args.resumeId);
|
|
356
|
+
}
|
|
357
|
+
catch (err) {
|
|
358
|
+
process.stderr.write(`Cannot resume: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
359
|
+
process.exit(1);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
else {
|
|
363
|
+
latest = findLatestEventLog(phrenCtx.phrenPath, phrenCtx.project ?? undefined);
|
|
364
|
+
}
|
|
365
|
+
if (latest) {
|
|
366
|
+
try {
|
|
367
|
+
const parent = restoreSessionLog(phrenCtx.phrenPath, latest);
|
|
368
|
+
if (parent.length > 0) {
|
|
369
|
+
if (args.verbose) {
|
|
370
|
+
process.stderr.write(`Resuming session ${parent.header.sessionId.slice(0, 8)} (${parent.header.project ?? "global"}) with ${parent.getMessages().length} messages from its event log\n`);
|
|
371
|
+
}
|
|
372
|
+
// This run gets its own forked log file, seeded with the parent's
|
|
373
|
+
// full history and linked via parentSession.
|
|
374
|
+
return persistFork(phrenCtx.phrenPath, parent, sessionId);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
catch (err) {
|
|
378
|
+
process.stderr.write(`Cannot resume from event log (${err instanceof Error ? err.message : String(err)}); trying legacy snapshot\n`);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
if (args.resumeId)
|
|
382
|
+
return undefined; // a named session never falls back to another one
|
|
383
|
+
const priorSnapshot = loadLastSessionSnapshot(phrenCtx.phrenPath, phrenCtx.project ?? undefined);
|
|
384
|
+
if (priorSnapshot && priorSnapshot.messages.length > 0) {
|
|
385
|
+
if (args.verbose) {
|
|
386
|
+
process.stderr.write(`Resuming session ${priorSnapshot.sessionId.slice(0, 8)} (${priorSnapshot.project ?? "global"}) with ${priorSnapshot.messages.length} messages from a v1 snapshot\n`);
|
|
387
|
+
}
|
|
388
|
+
const log = makePersistedLog();
|
|
389
|
+
if (!log)
|
|
390
|
+
return undefined;
|
|
391
|
+
seedFromMessages(log, priorSnapshot.messages);
|
|
392
|
+
return log;
|
|
393
|
+
}
|
|
394
|
+
return undefined;
|
|
395
|
+
};
|
|
396
|
+
const resumedLog = args.resume ? makeResumedLog() : undefined;
|
|
222
397
|
const agentConfig = {
|
|
223
398
|
provider,
|
|
224
399
|
registry,
|
|
@@ -230,6 +405,9 @@ export async function runAgentCli(raw) {
|
|
|
230
405
|
plan: args.plan,
|
|
231
406
|
lintTestConfig,
|
|
232
407
|
sessionId,
|
|
408
|
+
hookConfig: registry.hookConfig,
|
|
409
|
+
sessionLog: resumedLog ?? makePersistedLog(),
|
|
410
|
+
...(args.noLlmCompact ? { compaction: { enabled: false } } : {}),
|
|
233
411
|
};
|
|
234
412
|
// Interactive mode — Ink TUI with built-in spawner (--multi and --team also route here)
|
|
235
413
|
if (args.interactive || args.multi || args.team) {
|
|
@@ -239,24 +417,54 @@ export async function runAgentCli(raw) {
|
|
|
239
417
|
session = await (await import("./repl.js")).startRepl(agentConfig);
|
|
240
418
|
}
|
|
241
419
|
else {
|
|
420
|
+
// The phren splash (mascot + wordmark reveal) before the TUI mounts.
|
|
421
|
+
// Cosmetic only: any failure is swallowed, and PHREN_INTRO=off skips it.
|
|
422
|
+
if (process.env.PHREN_INTRO !== "off") {
|
|
423
|
+
try {
|
|
424
|
+
const { playSplash } = await import("@phren/cli/shell/intro");
|
|
425
|
+
const model = provider.model;
|
|
426
|
+
await playSplash({
|
|
427
|
+
version: VERSION,
|
|
428
|
+
tagline: `agent · ${provider.name}${model ? ` · ${model}` : ""}`,
|
|
429
|
+
hint: "starting agent…",
|
|
430
|
+
reveal: true,
|
|
431
|
+
dwellMs: 600,
|
|
432
|
+
fullscreen: true,
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
catch { /* best effort */ }
|
|
436
|
+
}
|
|
242
437
|
// Ink TUI with spawner — LLM can spawn agents via spawn_agent tool
|
|
243
438
|
const { AgentSpawner } = await import("./multi/spawner.js");
|
|
244
439
|
const { createSpawnAgentTool, createSendMessageTool, createListAgentsTool } = await import("./tools/spawn-agent.js");
|
|
245
|
-
const spawner = new AgentSpawner();
|
|
246
|
-
registry.register(createSpawnAgentTool(spawner));
|
|
440
|
+
const spawner = new AgentSpawner({ costTracker, getPermissionDefaults: () => registry.permissionConfig });
|
|
441
|
+
registry.register(createSpawnAgentTool(spawner, () => registry.permissionConfig));
|
|
247
442
|
registry.register(createSendMessageTool(spawner));
|
|
248
443
|
registry.register(createListAgentsTool(spawner));
|
|
249
|
-
|
|
444
|
+
// Publish this process's agents so a phren graph in another terminal can
|
|
445
|
+
// show them. Best-effort and silent: it is a courtesy to another tool.
|
|
446
|
+
const { createAgentPublisher } = await import("./multi/publish.js");
|
|
447
|
+
const publisher = createAgentPublisher(phrenCtx?.phrenPath);
|
|
448
|
+
const republish = () => publisher.publish(spawner.listAgents());
|
|
449
|
+
spawner.on("status", republish);
|
|
450
|
+
spawner.on("done", republish);
|
|
451
|
+
republish();
|
|
452
|
+
try {
|
|
453
|
+
session = await (await import("./tui/ink-entry.js")).startInkTui(agentConfig, spawner);
|
|
454
|
+
}
|
|
455
|
+
finally {
|
|
456
|
+
publisher.stop();
|
|
457
|
+
}
|
|
250
458
|
await spawner.shutdown();
|
|
251
459
|
}
|
|
252
460
|
// Flush anti-patterns at session end
|
|
253
461
|
if (phrenCtx) {
|
|
254
462
|
try {
|
|
255
|
-
await session.antiPatterns.flushAntiPatterns(phrenCtx);
|
|
463
|
+
await session.antiPatterns.flushAntiPatterns(phrenCtx, sessionId);
|
|
256
464
|
}
|
|
257
465
|
catch { /* best effort */ }
|
|
258
466
|
try {
|
|
259
|
-
await evolveProjectContext(phrenCtx, provider, session.messages);
|
|
467
|
+
await evolveProjectContext(phrenCtx, provider, session.messages, { sessionId });
|
|
260
468
|
}
|
|
261
469
|
catch { /* best effort */ }
|
|
262
470
|
}
|
|
@@ -264,6 +472,13 @@ export async function runAgentCli(raw) {
|
|
|
264
472
|
const lastText = session.messages.length > 0 ? "Interactive session ended" : "Empty session";
|
|
265
473
|
endSession(phrenCtx, sessionId, lastText);
|
|
266
474
|
saveSessionMessages(phrenCtx.phrenPath, sessionId, session.messages, phrenCtx.project ?? undefined);
|
|
475
|
+
if (session.messages.length > 0) {
|
|
476
|
+
writeSessionNote(phrenCtx, {
|
|
477
|
+
sessionId,
|
|
478
|
+
task: "interactive session",
|
|
479
|
+
outcome: `${session.messages.length} messages, ${session.toolCalls} tool calls`,
|
|
480
|
+
});
|
|
481
|
+
}
|
|
267
482
|
}
|
|
268
483
|
mcpCleanup?.();
|
|
269
484
|
return;
|
|
@@ -289,65 +504,153 @@ export async function runAgentCli(raw) {
|
|
|
289
504
|
process.exit(130);
|
|
290
505
|
});
|
|
291
506
|
// One-shot mode
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
else {
|
|
317
|
-
process.stderr.write("No previous session to resume.\n");
|
|
318
|
-
result = await runAgent(args.task, agentConfig);
|
|
319
|
-
}
|
|
507
|
+
// Subagent tools are available by default (disable with --no-subagents);
|
|
508
|
+
// children run headless with auto-confirm permissions and exit when the
|
|
509
|
+
// parent's IPC channel closes.
|
|
510
|
+
let oneShotSpawner;
|
|
511
|
+
if (!args.noSubagents) {
|
|
512
|
+
const { AgentSpawner } = await import("./multi/spawner.js");
|
|
513
|
+
const { createSpawnAgentTool, createSendMessageTool, createListAgentsTool } = await import("./tools/spawn-agent.js");
|
|
514
|
+
oneShotSpawner = new AgentSpawner({ costTracker, getPermissionDefaults: () => registry.permissionConfig });
|
|
515
|
+
registry.register(createSpawnAgentTool(oneShotSpawner, () => registry.permissionConfig));
|
|
516
|
+
registry.register(createSendMessageTool(oneShotSpawner));
|
|
517
|
+
registry.register(createListAgentsTool(oneShotSpawner));
|
|
518
|
+
}
|
|
519
|
+
const startedAt = Date.now();
|
|
520
|
+
const headlessHooks = args.print
|
|
521
|
+
? createHeadlessHooks({ format: args.outputFormat, verbose: args.verbose, write: (line) => process.stdout.write(`${line}\n`) })
|
|
522
|
+
: undefined;
|
|
523
|
+
const modelId = provider.model ?? null;
|
|
524
|
+
const emitHeadless = (result) => {
|
|
525
|
+
if (args.outputFormat === "text") {
|
|
526
|
+
if (result.result)
|
|
527
|
+
process.stdout.write(result.result.endsWith("\n") ? result.result : `${result.result}\n`);
|
|
528
|
+
if (result.is_error)
|
|
529
|
+
process.stderr.write(`[${result.subtype}${result.error ? `: ${result.error}` : ""}]\n`);
|
|
320
530
|
}
|
|
321
531
|
else {
|
|
322
|
-
|
|
532
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
323
533
|
}
|
|
534
|
+
};
|
|
535
|
+
if (args.print && args.outputFormat === "stream-json") {
|
|
536
|
+
process.stdout.write(`${JSON.stringify({
|
|
537
|
+
type: "system",
|
|
538
|
+
subtype: "init",
|
|
539
|
+
session_id: sessionId,
|
|
540
|
+
provider: provider.name,
|
|
541
|
+
model: modelId,
|
|
542
|
+
cwd,
|
|
543
|
+
permission_mode: args.permissions,
|
|
544
|
+
tools: registry.toolNames(),
|
|
545
|
+
})}\n`);
|
|
546
|
+
}
|
|
547
|
+
let exitCode = 0;
|
|
548
|
+
try {
|
|
549
|
+
const contextLimit = provider.contextWindow ?? 200_000;
|
|
550
|
+
if (args.resume && !resumedLog) {
|
|
551
|
+
process.stderr.write("No previous session to resume.\n");
|
|
552
|
+
}
|
|
553
|
+
// A resumed session continues with the task given on the command line,
|
|
554
|
+
// or with a generic "continue" when none was.
|
|
555
|
+
const prompt = resumedLog && !userTask
|
|
556
|
+
? "Continuing where we left off. Please review the conversation and continue with the task."
|
|
557
|
+
: args.task;
|
|
558
|
+
const session = createSession(contextLimit, { log: resumedLog ?? agentConfig.sessionLog });
|
|
559
|
+
emitHerdrHook("UserPromptSubmit");
|
|
560
|
+
const turnResult = await runTurn(prompt, session, agentConfig, headlessHooks).finally(() => emitHerdrHook("Stop"));
|
|
561
|
+
const result = {
|
|
562
|
+
finalText: turnResult.text,
|
|
563
|
+
turns: turnResult.turns,
|
|
564
|
+
toolCalls: turnResult.toolCalls,
|
|
565
|
+
totalCost: agentConfig.costTracker?.formatCost(),
|
|
566
|
+
messages: session.messages,
|
|
567
|
+
session,
|
|
568
|
+
};
|
|
324
569
|
if (args.verbose) {
|
|
325
570
|
const costStr = result.totalCost ? `, ${result.totalCost}` : "";
|
|
326
571
|
process.stderr.write(`\nDone: ${result.turns} turns, ${result.toolCalls} tool calls${costStr}\n`);
|
|
327
572
|
}
|
|
328
|
-
|
|
573
|
+
if (args.print) {
|
|
574
|
+
const headless = buildHeadlessResult({
|
|
575
|
+
text: turnResult.text,
|
|
576
|
+
stopReason: turnResult.stopReason,
|
|
577
|
+
turns: turnResult.turns,
|
|
578
|
+
toolCalls: turnResult.toolCalls,
|
|
579
|
+
startedAt,
|
|
580
|
+
sessionId,
|
|
581
|
+
provider: provider.name,
|
|
582
|
+
model: modelId,
|
|
583
|
+
costTracker,
|
|
584
|
+
permissionDenials,
|
|
585
|
+
});
|
|
586
|
+
emitHeadless(headless);
|
|
587
|
+
exitCode = headlessExitCode(headless);
|
|
588
|
+
}
|
|
589
|
+
else if (process.stdout.isTTY) {
|
|
590
|
+
process.stdout.write("\x07"); // bell on completion; never into a pipe
|
|
591
|
+
}
|
|
329
592
|
// End session with summary + memory intelligence
|
|
330
593
|
if (phrenCtx && sessionId) {
|
|
331
594
|
const summary = result.finalText.slice(0, 500);
|
|
332
595
|
endSession(phrenCtx, sessionId, summary);
|
|
333
596
|
// Save messages for resume
|
|
334
597
|
saveSessionMessages(phrenCtx.phrenPath, sessionId, result.messages, phrenCtx.project ?? undefined);
|
|
335
|
-
//
|
|
598
|
+
// Flush anti-patterns (interactive mode does this too; one-shot was missing it)
|
|
599
|
+
try {
|
|
600
|
+
await result.session.antiPatterns.flushAntiPatterns(phrenCtx, sessionId);
|
|
601
|
+
}
|
|
602
|
+
catch { /* best effort */ }
|
|
603
|
+
// Evolve project context via lightweight LLM reflection (also routes
|
|
604
|
+
// extracted knowledge through the graduated confidence pipeline)
|
|
336
605
|
try {
|
|
337
|
-
await evolveProjectContext(phrenCtx, provider, result.messages);
|
|
606
|
+
await evolveProjectContext(phrenCtx, provider, result.messages, { sessionId });
|
|
338
607
|
}
|
|
339
608
|
catch { /* best effort */ }
|
|
609
|
+
// Mirror the session into a searchable (non-injectable) note
|
|
610
|
+
writeSessionNote(phrenCtx, { sessionId, task: args.task, outcome: result.finalText });
|
|
340
611
|
}
|
|
341
612
|
}
|
|
342
613
|
catch (err) {
|
|
343
|
-
|
|
614
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
615
|
+
if (args.print) {
|
|
616
|
+
emitHeadless(buildHeadlessResult({
|
|
617
|
+
text: "",
|
|
618
|
+
stopReason: "error",
|
|
619
|
+
turns: 0,
|
|
620
|
+
toolCalls: 0,
|
|
621
|
+
startedAt,
|
|
622
|
+
sessionId,
|
|
623
|
+
provider: provider.name,
|
|
624
|
+
model: modelId,
|
|
625
|
+
costTracker,
|
|
626
|
+
permissionDenials,
|
|
627
|
+
error: message,
|
|
628
|
+
}));
|
|
629
|
+
if (args.outputFormat !== "text") {
|
|
630
|
+
// The error is in the JSON; keep stderr for humans too.
|
|
631
|
+
process.stderr.write(`${message}\n`);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
else {
|
|
635
|
+
console.error(message);
|
|
636
|
+
}
|
|
344
637
|
if (phrenCtx && sessionId) {
|
|
345
638
|
endSession(phrenCtx, sessionId, `Error: ${err instanceof Error ? err.message : String(err)}`);
|
|
346
639
|
}
|
|
640
|
+
try {
|
|
641
|
+
await oneShotSpawner?.shutdown();
|
|
642
|
+
}
|
|
643
|
+
catch { /* children exit with the IPC channel */ }
|
|
347
644
|
mcpCleanup?.();
|
|
348
645
|
process.exit(1);
|
|
349
646
|
}
|
|
647
|
+
try {
|
|
648
|
+
await oneShotSpawner?.shutdown();
|
|
649
|
+
}
|
|
650
|
+
catch { /* children exit with the IPC channel */ }
|
|
350
651
|
mcpCleanup?.();
|
|
652
|
+
if (exitCode !== 0)
|
|
653
|
+
process.exit(exitCode);
|
|
351
654
|
}
|
|
352
655
|
// When run directly (phren-agent binary), parse from process.argv
|
|
353
656
|
const isDirectRun = process.argv[1]?.endsWith("/agent/index.js") ||
|