@phren/agent 0.3.19 → 0.3.21

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 (67) hide show
  1. package/dist/agent-loop/index.js +185 -47
  2. package/dist/agent-loop/stream.js +74 -66
  3. package/dist/agent-loop/types.js +2 -3
  4. package/dist/attach-images.js +57 -0
  5. package/dist/bin.js +7 -2
  6. package/dist/commands/info.js +7 -3
  7. package/dist/commands/model.js +55 -13
  8. package/dist/commands/session.js +79 -18
  9. package/dist/commands.js +24 -3
  10. package/dist/config.js +89 -10
  11. package/dist/context/clear-tool-results.js +43 -0
  12. package/dist/context/compactor.js +13 -3
  13. package/dist/context/pruner.js +29 -11
  14. package/dist/context/usage.js +26 -0
  15. package/dist/cost.js +68 -10
  16. package/dist/headless.js +47 -1
  17. package/dist/index.js +335 -127
  18. package/dist/mcp-client.js +38 -1
  19. package/dist/mcp-prompts.js +94 -0
  20. package/dist/memory/chat.js +70 -0
  21. package/dist/memory/context.js +1 -1
  22. package/dist/model-overrides.js +17 -0
  23. package/dist/models-list.js +73 -0
  24. package/dist/models.js +42 -15
  25. package/dist/multi/child-entry.js +18 -28
  26. package/dist/multi/ipc-hooks.js +34 -0
  27. package/dist/multi/spawner.js +49 -3
  28. package/dist/permissions/allowlist.js +19 -4
  29. package/dist/permissions/checker.js +37 -20
  30. package/dist/permissions/kernel-sandbox.js +32 -10
  31. package/dist/permissions/rules.js +173 -0
  32. package/dist/permissions/shell-classify.js +173 -0
  33. package/dist/plan.js +6 -2
  34. package/dist/providers/anthropic.js +119 -75
  35. package/dist/providers/codex.js +10 -9
  36. package/dist/providers/ollama.js +5 -2
  37. package/dist/providers/openai-compat.js +219 -92
  38. package/dist/providers/openrouter.js +12 -7
  39. package/dist/providers/resolve.js +47 -1
  40. package/dist/providers/retry.js +20 -7
  41. package/dist/providers/types.js +31 -0
  42. package/dist/repl.js +17 -1
  43. package/dist/session/persist.js +9 -4
  44. package/dist/session/preview.js +99 -0
  45. package/dist/settings.js +14 -0
  46. package/dist/structured-output.js +85 -0
  47. package/dist/system-prompt.js +117 -14
  48. package/dist/tools/apply-patch.js +15 -1
  49. package/dist/tools/edit-file.js +8 -1
  50. package/dist/tools/file-state.js +88 -0
  51. package/dist/tools/glob.js +53 -35
  52. package/dist/tools/grep.js +139 -53
  53. package/dist/tools/lint-test.js +24 -0
  54. package/dist/tools/read-file.js +2 -0
  55. package/dist/tools/registry.js +8 -1
  56. package/dist/tools/search-support.js +141 -0
  57. package/dist/tools/shell.js +266 -41
  58. package/dist/tools/spawn-agent.js +15 -3
  59. package/dist/tools/syntax-check.js +116 -0
  60. package/dist/tools/write-file.js +11 -3
  61. package/dist/tui/components/App.js +5 -4
  62. package/dist/tui/components/Banner.js +1 -1
  63. package/dist/tui/components/ListPicker.js +32 -0
  64. package/dist/tui/ink-entry.js +79 -15
  65. package/dist/user-hooks.js +26 -4
  66. package/package.json +3 -2
  67. package/dist/memory/context-flush.js +0 -24
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { parseArgs, printHelp, resolveStartupPermissions } from "./config.js";
2
+ import { agentUserDir, parseArgs, printHelp, resolveStartupPermissions } from "./config.js";
3
+ import { randomUUID } from "crypto";
3
4
  import { loadPersistentAllowlist } from "./permissions/allowlist.js";
4
- import { resolveProvider } from "./providers/resolve.js";
5
+ import { loadPermissionRules } from "./permissions/rules.js";
6
+ import { keepSessionEndpoint, resolveProvider } from "./providers/resolve.js";
5
7
  import { ToolRegistry } from "./tools/registry.js";
6
8
  import { readFileTool } from "./tools/read-file.js";
7
9
  import { writeFileTool } from "./tools/write-file.js";
@@ -23,21 +25,29 @@ import { gitStatusTool, gitDiffTool, gitCommitTool } from "./tools/git.js";
23
25
  import { updatePlanTool } from "./tools/update-plan.js";
24
26
  import { listMcpResourcesTool, readMcpResourceTool } from "./tools/mcp-resources.js";
25
27
  import { buildPhrenContext, buildContextSnippet, buildProjectInstructions } from "./memory/context.js";
28
+ import { buildChatMemory, buildChatSystemPrompt } from "./memory/chat.js";
29
+ import { livePreview, previewPath, removeStalePreviews } from "./session/preview.js";
26
30
  import { startSession, endSession, getPriorSummary, saveSessionMessages, loadLastSessionSnapshot, writeSessionNote } from "./memory/session.js";
27
31
  import { emitHerdrHook, setHerdrHookSession } from "./herdr-hooks.js";
28
32
  import { loadProjectContext, evolveProjectContext } from "./memory/project-context.js";
29
- import { buildSystemPrompt } from "./system-prompt.js";
30
- import { loadHooksConfig } from "./user-hooks.js";
31
- import { loadAndRegisterCustomCommands, getCustomCommandInfos } from "./commands.js";
33
+ import { buildSystemPrompt, buildEnvironmentBlock } from "./system-prompt.js";
34
+ import { loadHooksConfig, runLifecycleHooks } from "./user-hooks.js";
35
+ import { addCommandNames, loadAndRegisterCustomCommands, getCustomCommandInfos } from "./commands.js";
36
+ import { loadJsonSchema, produceStructuredOutput } from "./structured-output.js";
37
+ import { isMcpPromptCommand, loadMcpPrompts, mcpPromptCommandNames, resolveMcpPromptCommand } from "./mcp-prompts.js";
32
38
  import { createSession, runTurn } from "./agent-loop.js";
33
39
  import { SessionLog, seedFromMessages } from "./session/log.js";
34
40
  import { fileSink, findEventLogById, findLatestEventLog, listEventLogs, persistFork, restoreSessionLog } from "./session/persist.js";
35
- import { buildHeadlessResult, createHeadlessHooks, headlessExitCode, readStdin } from "./headless.js";
41
+ import { buildHeadlessResult, createHeadlessHooks, headlessExitCode, parseStreamJsonInput, readLines, readStdin } from "./headless.js";
36
42
  import { createCostTracker } from "./cost.js";
43
+ import { scopeModelOverrides } from "./model-overrides.js";
37
44
  import { codexLogin, codexLogout } from "./providers/codex-auth.js";
38
45
  import { createCheckpoint } from "./checkpoint.js";
39
- import { detectLintCommand, detectTestCommand } from "./tools/lint-test.js";
40
- import { connectMcpServers, loadMcpConfig, parseMcpInline } from "./mcp-client.js";
46
+ import { detectLintCommand, detectTypecheckCommand, detectTestCommand } from "./tools/lint-test.js";
47
+ import { connectMcpServers, loadDefaultMcpConfig, loadMcpConfig, parseMcpInline } from "./mcp-client.js";
48
+ import { isMcpProjectTrusted, trustMcpProject } from "./settings.js";
49
+ import * as os from "os";
50
+ import * as path from "path";
41
51
  import { VERSION } from "./package-metadata.js";
42
52
  import { authProfilesPath, getAuthStatusEntries, removeApiKeyProfile, upsertApiKeyProfile, } from "@phren/cli/auth/profiles";
43
53
  function parseApiKeyProvider(raw) {
@@ -132,17 +142,17 @@ export async function runAgentCli(raw) {
132
142
  console.log(`phren-agent v${VERSION}`);
133
143
  process.exit(0);
134
144
  }
135
- // Model switches and spawned children resolve the provider again; they
136
- // read the endpoint from the environment.
145
+ // Model switches resolve the provider again; they read the endpoint from
146
+ // the environment. The window and prices stay with the model they were
147
+ // given for (scopeModelOverrides, below).
137
148
  if (args.baseUrl)
138
149
  process.env.PHREN_AGENT_BASE_URL = args.baseUrl;
139
150
  if (args.listSessions) {
151
+ // Without a phren store, sessions live in ~/.phren-agent, listed for this directory.
140
152
  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 });
153
+ const sessions = ctx
154
+ ? listEventLogs(ctx.phrenPath, { project: args.project ?? undefined, limit: 20 })
155
+ : listEventLogs(agentUserDir(), { cwd: process.cwd(), limit: 20 });
146
156
  if (args.outputFormat === "json") {
147
157
  console.log(JSON.stringify(sessions.map(({ file: _file, ...rest }) => ({ ...rest, updatedAt: new Date(rest.mtimeMs).toISOString() })), null, 2));
148
158
  }
@@ -158,32 +168,64 @@ export async function runAgentCli(raw) {
158
168
  }
159
169
  process.exit(0);
160
170
  }
171
+ const streamInput = args.inputFormat === "stream-json";
172
+ // --json-schema: compiled up front, so a bad schema fails before any work.
173
+ let jsonSchema;
174
+ if (args.jsonSchema) {
175
+ if (streamInput) {
176
+ console.error("--json-schema answers one task; it cannot run with --input-format stream-json.");
177
+ process.exit(1);
178
+ }
179
+ try {
180
+ jsonSchema = loadJsonSchema(args.jsonSchema);
181
+ }
182
+ catch (err) {
183
+ console.error(err instanceof Error ? err.message : String(err));
184
+ process.exit(1);
185
+ }
186
+ }
187
+ if (streamInput && args.outputFormat !== "stream-json") {
188
+ console.error("--input-format stream-json needs --output-format stream-json.");
189
+ process.exit(1);
190
+ }
161
191
  // Headless with no task argument: read the task from piped stdin.
162
- if (args.print && !args.task && !process.stdin.isTTY) {
192
+ if (args.print && !streamInput && !args.task && !process.stdin.isTTY) {
163
193
  args.task = (await readStdin()).trim();
164
194
  }
165
195
  if (args.print) {
166
196
  args.interactive = false;
167
197
  args.multi = false;
168
198
  }
199
+ const chat = args.mode === "chat";
200
+ if (chat && (args.multi || args.team)) {
201
+ console.error("--mode chat is a single conversation; it cannot run with --multi or --team.");
202
+ process.exit(1);
203
+ }
169
204
  // `--resume` alone continues the prior session without a placeholder task
170
205
  const userTask = args.task;
171
206
  if (!args.task && args.resume) {
172
207
  args.task = "Continue where the previous session left off.";
173
208
  }
174
- if (!args.task && !args.interactive && !args.multi && !args.team) {
209
+ if (!args.task && !streamInput && !args.interactive && !args.multi && !args.team) {
175
210
  console.error("Usage: phren-agent <task>\nRun phren-agent --help for more info.");
176
211
  process.exit(1);
177
212
  }
178
213
  // Resolve LLM provider
179
214
  let provider;
180
215
  try {
181
- provider = resolveProvider(args.provider, args.model, args.maxOutput, args.reasoning, { baseUrl: args.baseUrl });
216
+ provider = resolveProvider(args.provider, args.model, args.maxOutput, args.reasoning, { baseUrl: args.baseUrl, contextWindow: args.contextWindow });
182
217
  }
183
218
  catch (err) {
184
219
  console.error(err instanceof Error ? err.message : String(err));
185
220
  process.exit(1);
186
221
  }
222
+ keepSessionEndpoint(provider);
223
+ scopeModelOverrides(provider.model ?? args.model ?? provider.name, {
224
+ contextWindow: args.contextWindow,
225
+ priceIn: args.priceIn,
226
+ priceOut: args.priceOut,
227
+ priceCache: args.priceCache,
228
+ });
187
229
  if (args.verbose) {
188
230
  process.stderr.write(`Provider: ${provider.name}\n`);
189
231
  }
@@ -198,7 +240,8 @@ export async function runAgentCli(raw) {
198
240
  }
199
241
  // Review-queue surfacing. Interactive sessions get expiry + a triage
200
242
  // banner; one-shot runs get a count only and never mutate the queue.
201
- if (phrenCtx.project) {
243
+ // A quick chat skips it: it cannot act on the queue.
244
+ if (phrenCtx.project && !chat) {
202
245
  try {
203
246
  const { getQueueStatus, formatQueueBanner, formatExpiryNotice, expireStaleItems, resolveExpireDays } = await import("./memory/review-triage.js");
204
247
  if (args.interactive || args.multi || args.team) {
@@ -220,42 +263,56 @@ export async function runAgentCli(raw) {
220
263
  }
221
264
  catch { /* best effort */ }
222
265
  }
223
- contextSnippet = await buildContextSnippet(phrenCtx, args.task);
224
- priorSummary = getPriorSummary(phrenCtx);
266
+ // A quick chat reads its memory from files below; the agent's snippet
267
+ // builds the search index, which is what makes a first answer slow.
268
+ if (!chat) {
269
+ contextSnippet = await buildContextSnippet(phrenCtx, args.task);
270
+ priorSummary = getPriorSummary(phrenCtx);
271
+ }
225
272
  sessionId = startSession(phrenCtx);
226
273
  // Inside a Herdr pane, tell Phren Hook which event log is this pane's.
227
274
  setHerdrHookSession(sessionId);
228
275
  emitHerdrHook("SessionStart");
229
276
  // Load evolved project context for warm start
230
- const projectCtx = loadProjectContext(phrenCtx);
277
+ const projectCtx = chat ? null : loadProjectContext(phrenCtx);
231
278
  if (projectCtx) {
232
279
  contextSnippet += `\n\n## Agent context (${phrenCtx.project})\n\n${projectCtx}`;
233
280
  }
234
281
  }
235
282
  // Without a phren store, the repo's AGENTS.md / CLAUDE.md still apply.
236
- if (!phrenCtx)
283
+ if (!phrenCtx && !chat)
237
284
  contextSnippet = buildProjectInstructions();
238
285
  loadAndRegisterCustomCommands(process.cwd());
239
- const systemPrompt = buildSystemPrompt(contextSnippet, priorSummary, {
240
- name: provider.name,
241
- model: provider.model,
242
- }, getCustomCommandInfos());
243
- // Dry run: print system prompt and exit
244
- if (args.dryRun) {
245
- console.log("=== System Prompt ===");
246
- console.log(systemPrompt);
247
- console.log("\n=== Task ===");
248
- console.log(args.task);
249
- process.exit(0);
250
- }
286
+ const chatMemory = chat ? buildChatMemory(phrenCtx) : "";
287
+ const providerInfo = { name: provider.name, model: provider.model };
288
+ // The environment block is built once so the prompt stays byte-stable
289
+ // across rebuilds (provider prompt caching).
290
+ const environment = buildEnvironmentBlock(process.cwd());
291
+ let promptContext = contextSnippet;
292
+ let promptSummary = priorSummary;
293
+ const mcpServerNames = [];
294
+ // Built from the tools registered right now: call again after registering more.
295
+ const agentPrompt = (info) => buildSystemPrompt(promptContext, promptSummary, info, getCustomCommandInfos(), {
296
+ toolNames: registry.toolNames(),
297
+ mcpServers: mcpServerNames,
298
+ environment,
299
+ });
251
300
  // Register tools
252
301
  const registry = new ToolRegistry();
253
302
  registry.hookConfig = loadHooksConfig(process.cwd());
303
+ // SessionStart hooks: what they print joins the system prompt's context.
304
+ if (registry.hookConfig && !args.dryRun) {
305
+ const started = await runLifecycleHooks(registry.hookConfig, "SessionStart", { source: args.resume ? "resume" : "startup" });
306
+ if (started.context && !chat)
307
+ promptContext += `\n\n## SessionStart hook\n${started.context}`;
308
+ }
254
309
  registry.setPermissions({
255
310
  mode: args.permissions,
256
311
  allowedPaths: [],
257
312
  projectRoot: process.cwd(),
258
313
  sandboxMode: args.sandbox,
314
+ ...(args.noNetwork ? { network: "off" } : {}),
315
+ rules: loadPermissionRules(process.cwd(), { allow: args.allowedTools, deny: args.disallowedTools }),
259
316
  });
260
317
  // Nobody can answer a prompt in a headless run or with stdin not a
261
318
  // terminal (a readline question on a closed stdin would hang): deny, and
@@ -264,81 +321,121 @@ export async function runAgentCli(raw) {
264
321
  if (args.print || (!process.stdin.isTTY && !args.interactive && !args.multi && !args.team)) {
265
322
  registry.askUser = async (toolName, _input, reason) => {
266
323
  permissionDenials++;
267
- process.stderr.write(`[denied ${toolName}: ${reason} No one is present to approve; rerun with --permissions auto-confirm or --yolo to allow.]\n`);
324
+ process.stderr.write(`[denied ${toolName}: ${reason} No one is present to approve; allow it with --allowedTools "${toolName}", --permissions auto-confirm or --yolo.]\n`);
268
325
  return false;
269
326
  };
270
327
  }
271
- registry.register(readFileTool);
272
- registry.register(writeFileTool);
273
- registry.register(editFileTool);
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));
278
- registry.register(taskOutputTool);
279
- registry.register(taskStopTool);
280
- registry.register(globTool);
281
- registry.register(grepTool);
282
- if (modelSupportsVision(provider.name, provider.model ?? "")) {
283
- registry.register(createReadImageTool(provider));
284
- }
285
- if (phrenCtx) {
286
- registry.register(createPhrenSearchTool(phrenCtx));
287
- registry.register(createPhrenFindingTool(phrenCtx, sessionId));
288
- registry.register(createPhrenGetTasksTool(phrenCtx));
289
- registry.register(createPhrenCompleteTaskTool(phrenCtx, sessionId));
290
- registry.register(createPhrenAddTaskTool(phrenCtx, sessionId));
291
- registry.register(createSkillTool(phrenCtx));
292
- }
293
- // Web tools
294
- registry.register(createWebFetchTool());
295
- registry.register(createWebSearchTool());
296
- registry.register(gitStatusTool);
297
- registry.register(gitDiffTool);
298
- registry.register(gitCommitTool);
299
- registry.register(updatePlanTool);
300
- registry.register(listMcpResourcesTool);
301
- registry.register(readMcpResourceTool);
302
- // MCP server connections
328
+ // The agent's tools. A quick chat starts with none and gets them on /promote.
303
329
  let mcpCleanup;
304
- const mcpServers = {};
305
- if (args.mcpConfig) {
306
- Object.assign(mcpServers, loadMcpConfig(args.mcpConfig));
307
- }
308
- for (let idx = 0; idx < args.mcp.length; idx++) {
309
- const entry = parseMcpInline(args.mcp[idx]);
310
- mcpServers[`mcp-${idx}`] = entry;
311
- }
312
- if (Object.keys(mcpServers).length > 0) {
313
- const { tools: mcpTools, cleanup } = await connectMcpServers(mcpServers, args.verbose);
314
- mcpCleanup = cleanup;
315
- for (const tool of mcpTools)
316
- registry.register(tool);
330
+ const registerAgentTools = async () => {
331
+ registry.register(readFileTool);
332
+ registry.register(writeFileTool);
333
+ registry.register(editFileTool);
334
+ registry.register(multiEditTool);
335
+ registry.register(applyPatchTool);
336
+ // Live-config factory: /permissions and sandbox mode changes apply per call
337
+ registry.register(createShellTool(() => registry.permissionConfig));
338
+ registry.register(taskOutputTool);
339
+ registry.register(taskStopTool);
340
+ registry.register(globTool);
341
+ registry.register(grepTool);
342
+ if (modelSupportsVision(provider.name, provider.model ?? "")) {
343
+ registry.register(createReadImageTool(provider));
344
+ }
345
+ if (phrenCtx) {
346
+ registry.register(createPhrenSearchTool(phrenCtx));
347
+ registry.register(createPhrenFindingTool(phrenCtx, sessionId));
348
+ registry.register(createPhrenGetTasksTool(phrenCtx));
349
+ registry.register(createPhrenCompleteTaskTool(phrenCtx, sessionId));
350
+ registry.register(createPhrenAddTaskTool(phrenCtx, sessionId));
351
+ registry.register(createSkillTool(phrenCtx));
352
+ }
353
+ // Web tools
354
+ registry.register(createWebFetchTool());
355
+ registry.register(createWebSearchTool());
356
+ registry.register(gitStatusTool);
357
+ registry.register(gitDiffTool);
358
+ registry.register(gitCommitTool);
359
+ registry.register(updatePlanTool);
360
+ registry.register(listMcpResourcesTool);
361
+ registry.register(readMcpResourceTool);
362
+ // MCP server connections
363
+ const mcpServers = {};
364
+ if (!args.strictMcpConfig) {
365
+ if (args.trustProjectMcp)
366
+ trustMcpProject(process.cwd());
367
+ const defaults = loadDefaultMcpConfig(process.cwd(), { home: os.homedir(), trusted: isMcpProjectTrusted(process.cwd()) });
368
+ Object.assign(mcpServers, defaults.servers);
369
+ for (const { file, names } of defaults.untrusted) {
370
+ process.stderr.write(`\x1b[2m[${path.relative(process.cwd(), file)} defines MCP servers (${names.join(", ")}) that were not started; run with --trust-project-mcp to load this project's servers]\x1b[0m\n`);
371
+ }
372
+ }
373
+ if (args.mcpConfig) {
374
+ Object.assign(mcpServers, loadMcpConfig(args.mcpConfig));
375
+ }
376
+ for (let idx = 0; idx < args.mcp.length; idx++) {
377
+ const entry = parseMcpInline(args.mcp[idx]);
378
+ mcpServers[`mcp-${idx}`] = entry;
379
+ }
380
+ if (Object.keys(mcpServers).length > 0 && !args.dryRun) {
381
+ mcpServerNames.push(...Object.keys(mcpServers));
382
+ const { tools: mcpTools, cleanup } = await connectMcpServers(mcpServers, args.verbose);
383
+ mcpCleanup = cleanup;
384
+ for (const tool of mcpTools)
385
+ registry.register(tool);
386
+ // Their prompts become /mcp__server__prompt commands.
387
+ await loadMcpPrompts();
388
+ addCommandNames(mcpPromptCommandNames());
389
+ }
390
+ };
391
+ if (!chat)
392
+ await registerAgentTools();
393
+ // The prompt lists the registered tools, so it is built after they are.
394
+ const systemPrompt = chat
395
+ ? buildChatSystemPrompt(chatMemory, providerInfo)
396
+ : agentPrompt(providerInfo);
397
+ // Dry run: print system prompt and exit
398
+ if (args.dryRun) {
399
+ console.log("=== System Prompt ===");
400
+ console.log(systemPrompt);
401
+ console.log("\n=== Task ===");
402
+ console.log(args.task);
403
+ process.exit(0);
317
404
  }
318
405
  // Build cost tracker from model info
319
406
  const modelName = provider.model ?? args.model ?? provider.name;
320
- const costTracker = createCostTracker(modelName, args.budget, provider.name);
407
+ const costTracker = createCostTracker(modelName, args.budget, provider.name, provider.baseUrl);
321
408
  // Build lint/test config from CLI flags or auto-detect
322
409
  const cwd = process.cwd();
323
- const lintCmd = args.lintCmd ?? detectLintCommand(cwd);
324
- const testCmd = args.testCmd ?? detectTestCommand(cwd);
325
- const lintTestConfig = (lintCmd || testCmd) ? { lintCmd: lintCmd ?? undefined, testCmd: testCmd ?? undefined } : undefined;
410
+ const detectLintTest = () => {
411
+ const lintCmd = args.lintCmd ?? detectLintCommand(cwd);
412
+ const testCmd = args.testCmd ?? detectTestCommand(cwd);
413
+ const typecheckCmd = args.typecheckCmd ?? detectTypecheckCommand(cwd);
414
+ return (lintCmd || testCmd || typecheckCmd)
415
+ ? { lintCmd: lintCmd ?? undefined, testCmd: testCmd ?? undefined, typecheckCmd: typecheckCmd ?? undefined }
416
+ : undefined;
417
+ };
418
+ // A chat edits nothing, so it has nothing to check.
419
+ const lintTestConfig = chat ? undefined : detectLintTest();
326
420
  if (args.verbose && lintTestConfig) {
327
421
  if (lintTestConfig.lintCmd)
328
422
  process.stderr.write(`Lint: ${lintTestConfig.lintCmd}\n`);
329
423
  if (lintTestConfig.testCmd)
330
424
  process.stderr.write(`Test: ${lintTestConfig.testCmd}\n`);
331
425
  }
332
- /** Durable event log for this run when a phren store is available. */
426
+ // The durable event log lives in the phren store, or in ~/.phren-agent
427
+ // without one, so a session can be resumed either way. Without a store the
428
+ // session has no phren session id, only this log's.
429
+ const sessionRoot = phrenCtx?.phrenPath ?? agentUserDir();
430
+ const logSessionId = sessionId ?? randomUUID();
431
+ /** Durable event log for this run. */
333
432
  const makePersistedLog = () => {
334
- if (!phrenCtx || !sessionId)
335
- return undefined;
336
433
  return new SessionLog({
337
- sessionId,
338
- project: phrenCtx.project ?? undefined,
434
+ sessionId: logSessionId,
435
+ project: phrenCtx?.project ?? undefined,
339
436
  cwd: process.cwd(),
340
437
  createdAt: new Date().toISOString(),
341
- }, fileSink(phrenCtx.phrenPath, sessionId));
438
+ }, fileSink(sessionRoot, logSessionId));
342
439
  };
343
440
  /**
344
441
  * Resume seed: newest event log preferred, legacy v1 snapshot as fallback.
@@ -347,12 +444,10 @@ export async function runAgentCli(raw) {
347
444
  * previous session.
348
445
  */
349
446
  const makeResumedLog = () => {
350
- if (!phrenCtx || !sessionId)
351
- return undefined;
352
447
  let latest;
353
448
  if (args.resumeId) {
354
449
  try {
355
- latest = findEventLogById(phrenCtx.phrenPath, args.resumeId);
450
+ latest = findEventLogById(sessionRoot, args.resumeId);
356
451
  }
357
452
  catch (err) {
358
453
  process.stderr.write(`Cannot resume: ${err instanceof Error ? err.message : String(err)}\n`);
@@ -360,25 +455,27 @@ export async function runAgentCli(raw) {
360
455
  }
361
456
  }
362
457
  else {
363
- latest = findLatestEventLog(phrenCtx.phrenPath, phrenCtx.project ?? undefined);
458
+ latest = phrenCtx
459
+ ? findLatestEventLog(sessionRoot, phrenCtx.project ?? undefined)
460
+ : findLatestEventLog(sessionRoot, undefined, process.cwd());
364
461
  }
365
462
  if (latest) {
366
463
  try {
367
- const parent = restoreSessionLog(phrenCtx.phrenPath, latest);
464
+ const parent = restoreSessionLog(sessionRoot, latest);
368
465
  if (parent.length > 0) {
369
466
  if (args.verbose) {
370
467
  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
468
  }
372
469
  // This run gets its own forked log file, seeded with the parent's
373
470
  // full history and linked via parentSession.
374
- return persistFork(phrenCtx.phrenPath, parent, sessionId);
471
+ return persistFork(sessionRoot, parent, logSessionId);
375
472
  }
376
473
  }
377
474
  catch (err) {
378
475
  process.stderr.write(`Cannot resume from event log (${err instanceof Error ? err.message : String(err)}); trying legacy snapshot\n`);
379
476
  }
380
477
  }
381
- if (args.resumeId)
478
+ if (args.resumeId || !phrenCtx)
382
479
  return undefined; // a named session never falls back to another one
383
480
  const priorSnapshot = loadLastSessionSnapshot(phrenCtx.phrenPath, phrenCtx.project ?? undefined);
384
481
  if (priorSnapshot && priorSnapshot.messages.length > 0) {
@@ -386,14 +483,14 @@ export async function runAgentCli(raw) {
386
483
  process.stderr.write(`Resuming session ${priorSnapshot.sessionId.slice(0, 8)} (${priorSnapshot.project ?? "global"}) with ${priorSnapshot.messages.length} messages from a v1 snapshot\n`);
387
484
  }
388
485
  const log = makePersistedLog();
389
- if (!log)
390
- return undefined;
391
486
  seedFromMessages(log, priorSnapshot.messages);
392
487
  return log;
393
488
  }
394
489
  return undefined;
395
490
  };
396
491
  const resumedLog = args.resume ? makeResumedLog() : undefined;
492
+ /** Spawner tools, once an interactive session has a spawner. */
493
+ let registerSpawnerTools;
397
494
  const agentConfig = {
398
495
  provider,
399
496
  registry,
@@ -408,7 +505,53 @@ export async function runAgentCli(raw) {
408
505
  hookConfig: registry.hookConfig,
409
506
  sessionLog: resumedLog ?? makePersistedLog(),
410
507
  ...(args.noLlmCompact ? { compaction: { enabled: false } } : {}),
508
+ mode: args.mode,
411
509
  };
510
+ // The phone reads the reply being written from a sidecar of the event log.
511
+ if (phrenCtx && agentConfig.sessionLog && (args.interactive || args.multi || args.team)) {
512
+ const phrenPath = phrenCtx.phrenPath;
513
+ removeStalePreviews(phrenPath);
514
+ agentConfig.livePreview = (id) => id.startsWith("mem-") ? undefined : livePreview(previewPath(phrenPath, id));
515
+ }
516
+ if (!chat)
517
+ agentConfig.rebuildSystemPrompt = agentPrompt;
518
+ if (chat) {
519
+ agentConfig.rebuildSystemPrompt = (info) => buildChatSystemPrompt(chatMemory, info);
520
+ // Same conversation, same log: only the tools and the prompt change.
521
+ // Nothing about the session changes until every step has succeeded; a
522
+ // failure (an MCP server that won't start) leaves it a working chat.
523
+ agentConfig.promote = async () => {
524
+ if (agentConfig.mode !== "chat")
525
+ return "Already an agent session.";
526
+ const before = new Set(registry.toolNames());
527
+ try {
528
+ await registerAgentTools();
529
+ registerSpawnerTools?.();
530
+ let snippet = phrenCtx ? await buildContextSnippet(phrenCtx, "") : buildProjectInstructions();
531
+ const projectCtx = phrenCtx ? loadProjectContext(phrenCtx) : null;
532
+ if (phrenCtx && projectCtx)
533
+ snippet += `\n\n## Agent context (${phrenCtx.project})\n\n${projectCtx}`;
534
+ promptContext = snippet;
535
+ promptSummary = null;
536
+ const info = { name: agentConfig.provider.name, model: agentConfig.provider.model };
537
+ const systemPrompt = agentPrompt(info);
538
+ const lintTestConfig = detectLintTest();
539
+ agentConfig.mode = "agent";
540
+ agentConfig.rebuildSystemPrompt = agentPrompt;
541
+ agentConfig.systemPrompt = systemPrompt;
542
+ agentConfig.lintTestConfig = lintTestConfig;
543
+ }
544
+ catch (err) {
545
+ for (const name of registry.toolNames())
546
+ if (!before.has(name))
547
+ registry.remove(name);
548
+ mcpCleanup?.();
549
+ mcpCleanup = undefined;
550
+ throw err;
551
+ }
552
+ return `Promoted to a phren agent with ${registry.toolNames().length} tools; the conversation continues.`;
553
+ };
554
+ }
412
555
  // Interactive mode — Ink TUI with built-in spawner (--multi and --team also route here)
413
556
  if (args.interactive || args.multi || args.team) {
414
557
  const isTTY = process.stdout.isTTY && process.stdin.isTTY;
@@ -419,7 +562,7 @@ export async function runAgentCli(raw) {
419
562
  else {
420
563
  // The phren splash (mascot + wordmark reveal) before the TUI mounts.
421
564
  // Cosmetic only: any failure is swallowed, and PHREN_INTRO=off skips it.
422
- if (process.env.PHREN_INTRO !== "off") {
565
+ if (process.env.PHREN_INTRO !== "off" && !chat) {
423
566
  try {
424
567
  const { playSplash } = await import("@phren/cli/shell/intro");
425
568
  const model = provider.model;
@@ -437,10 +580,16 @@ export async function runAgentCli(raw) {
437
580
  // Ink TUI with spawner — LLM can spawn agents via spawn_agent tool
438
581
  const { AgentSpawner } = await import("./multi/spawner.js");
439
582
  const { createSpawnAgentTool, createSendMessageTool, createListAgentsTool } = await import("./tools/spawn-agent.js");
440
- const spawner = new AgentSpawner({ costTracker, getPermissionDefaults: () => registry.permissionConfig });
441
- registry.register(createSpawnAgentTool(spawner, () => registry.permissionConfig));
442
- registry.register(createSendMessageTool(spawner));
443
- registry.register(createListAgentsTool(spawner));
583
+ const spawner = new AgentSpawner({ costTracker, getPermissionDefaults: () => registry.permissionConfig, getParentProvider: () => agentConfig.provider });
584
+ registerSpawnerTools = () => {
585
+ registry.register(createSpawnAgentTool(spawner, () => registry.permissionConfig));
586
+ registry.register(createSendMessageTool(spawner));
587
+ registry.register(createListAgentsTool(spawner));
588
+ };
589
+ if (!chat) {
590
+ registerSpawnerTools();
591
+ agentConfig.systemPrompt = agentPrompt(providerInfo);
592
+ }
444
593
  // Publish this process's agents so a phren graph in another terminal can
445
594
  // show them. Best-effort and silent: it is a courtesy to another tool.
446
595
  const { createAgentPublisher } = await import("./multi/publish.js");
@@ -457,8 +606,9 @@ export async function runAgentCli(raw) {
457
606
  }
458
607
  await spawner.shutdown();
459
608
  }
460
- // Flush anti-patterns at session end
461
- if (phrenCtx) {
609
+ // Flush anti-patterns at session end. A chat that stayed one ran no
610
+ // tools and gets no reflection call.
611
+ if (phrenCtx && agentConfig.mode !== "chat") {
462
612
  try {
463
613
  await session.antiPatterns.flushAntiPatterns(phrenCtx, sessionId);
464
614
  }
@@ -484,7 +634,7 @@ export async function runAgentCli(raw) {
484
634
  return;
485
635
  }
486
636
  // Create initial checkpoint before agent starts
487
- const initCheckpoint = createCheckpoint(cwd, "pre-agent");
637
+ const initCheckpoint = chat ? null : createCheckpoint(cwd, "pre-agent");
488
638
  if (args.verbose && initCheckpoint) {
489
639
  process.stderr.write(`Checkpoint: ${initCheckpoint.slice(0, 8)}\n`);
490
640
  }
@@ -508,13 +658,14 @@ export async function runAgentCli(raw) {
508
658
  // children run headless with auto-confirm permissions and exit when the
509
659
  // parent's IPC channel closes.
510
660
  let oneShotSpawner;
511
- if (!args.noSubagents) {
661
+ if (!args.noSubagents && !chat) {
512
662
  const { AgentSpawner } = await import("./multi/spawner.js");
513
663
  const { createSpawnAgentTool, createSendMessageTool, createListAgentsTool } = await import("./tools/spawn-agent.js");
514
- oneShotSpawner = new AgentSpawner({ costTracker, getPermissionDefaults: () => registry.permissionConfig });
664
+ oneShotSpawner = new AgentSpawner({ costTracker, getPermissionDefaults: () => registry.permissionConfig, getParentProvider: () => agentConfig.provider });
515
665
  registry.register(createSpawnAgentTool(oneShotSpawner, () => registry.permissionConfig));
516
666
  registry.register(createSendMessageTool(oneShotSpawner));
517
667
  registry.register(createListAgentsTool(oneShotSpawner));
668
+ agentConfig.systemPrompt = agentPrompt(providerInfo);
518
669
  }
519
670
  const startedAt = Date.now();
520
671
  const headlessHooks = args.print
@@ -536,7 +687,7 @@ export async function runAgentCli(raw) {
536
687
  process.stdout.write(`${JSON.stringify({
537
688
  type: "system",
538
689
  subtype: "init",
539
- session_id: sessionId,
690
+ session_id: logSessionId,
540
691
  provider: provider.name,
541
692
  model: modelId,
542
693
  cwd,
@@ -552,12 +703,54 @@ export async function runAgentCli(raw) {
552
703
  }
553
704
  // A resumed session continues with the task given on the command line,
554
705
  // or with a generic "continue" when none was.
555
- const prompt = resumedLog && !userTask
706
+ const given = resumedLog && !userTask
556
707
  ? "Continuing where we left off. Please review the conversation and continue with the task."
557
708
  : args.task;
709
+ // `phren agent "/mcp__server__prompt …"` sends what the MCP prompt says.
710
+ const prompt = isMcpPromptCommand(given) ? await resolveMcpPromptCommand(given) : given;
558
711
  const session = createSession(contextLimit, { log: resumedLog ?? agentConfig.sessionLog });
559
- emitHerdrHook("UserPromptSubmit");
560
- const turnResult = await runTurn(prompt, session, agentConfig, headlessHooks).finally(() => emitHerdrHook("Stop"));
712
+ // One turn for the task, or one per user message with --input-format
713
+ // stream-json, all on the same session; each gets its own result line.
714
+ const taskGiven = !!args.task;
715
+ async function* prompts() {
716
+ if (!streamInput) {
717
+ yield prompt;
718
+ return;
719
+ }
720
+ if (taskGiven)
721
+ yield prompt;
722
+ for await (const line of readLines(process.stdin)) {
723
+ const parsed = parseStreamJsonInput(line);
724
+ if ("error" in parsed) {
725
+ process.stderr.write(`[skipped an input line: ${parsed.error}]\n`);
726
+ continue;
727
+ }
728
+ yield parsed.prompt;
729
+ }
730
+ }
731
+ let turnResult = { text: "", turns: 0, toolCalls: 0, stopReason: "end_turn" };
732
+ let turnStartedAt = startedAt;
733
+ for await (const next of prompts()) {
734
+ emitHerdrHook("UserPromptSubmit");
735
+ turnResult = await runTurn(next, session, agentConfig, headlessHooks).finally(() => emitHerdrHook("Stop"));
736
+ if (args.print && streamInput) {
737
+ const headless = buildHeadlessResult({
738
+ text: turnResult.text,
739
+ stopReason: turnResult.stopReason,
740
+ turns: turnResult.turns,
741
+ toolCalls: turnResult.toolCalls,
742
+ startedAt: turnStartedAt,
743
+ sessionId: logSessionId,
744
+ provider: provider.name,
745
+ model: modelId,
746
+ costTracker,
747
+ permissionDenials,
748
+ });
749
+ emitHeadless(headless);
750
+ exitCode = headlessExitCode(headless);
751
+ turnStartedAt = Date.now();
752
+ }
753
+ }
561
754
  const result = {
562
755
  finalText: turnResult.text,
563
756
  turns: turnResult.turns,
@@ -570,19 +763,32 @@ export async function runAgentCli(raw) {
570
763
  const costStr = result.totalCost ? `, ${result.totalCost}` : "";
571
764
  process.stderr.write(`\nDone: ${result.turns} turns, ${result.toolCalls} tool calls${costStr}\n`);
572
765
  }
573
- if (args.print) {
766
+ if (args.print && !streamInput) {
767
+ // --json-schema: a finished task ends with a value matching it (its
768
+ // request counts in the result's usage and cost).
769
+ const structured = jsonSchema && turnResult.stopReason === "end_turn"
770
+ ? await produceStructuredOutput(agentConfig.provider, agentConfig.systemPrompt, session.messages, registry.getDefinitions(), jsonSchema, { costTracker })
771
+ : undefined;
574
772
  const headless = buildHeadlessResult({
575
773
  text: turnResult.text,
576
774
  stopReason: turnResult.stopReason,
577
775
  turns: turnResult.turns,
578
776
  toolCalls: turnResult.toolCalls,
579
777
  startedAt,
580
- sessionId,
778
+ sessionId: logSessionId,
581
779
  provider: provider.name,
582
780
  model: modelId,
583
781
  costTracker,
584
782
  permissionDenials,
585
783
  });
784
+ if (structured && "value" in structured) {
785
+ headless.structured_output = structured.value;
786
+ if (args.outputFormat === "text")
787
+ headless.result = JSON.stringify(structured.value, null, 2);
788
+ }
789
+ else if (structured) {
790
+ Object.assign(headless, { subtype: "error_structured_output", is_error: true, error: structured.error });
791
+ }
586
792
  emitHeadless(headless);
587
793
  exitCode = headlessExitCode(headless);
588
794
  }
@@ -595,17 +801,19 @@ export async function runAgentCli(raw) {
595
801
  endSession(phrenCtx, sessionId, summary);
596
802
  // Save messages for resume
597
803
  saveSessionMessages(phrenCtx.phrenPath, sessionId, result.messages, phrenCtx.project ?? undefined);
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)
605
- try {
606
- await evolveProjectContext(phrenCtx, provider, result.messages, { sessionId });
804
+ if (!chat) {
805
+ // Flush anti-patterns (interactive mode does this too; one-shot was missing it)
806
+ try {
807
+ await result.session.antiPatterns.flushAntiPatterns(phrenCtx, sessionId);
808
+ }
809
+ catch { /* best effort */ }
810
+ // Evolve project context via lightweight LLM reflection (also routes
811
+ // extracted knowledge through the graduated confidence pipeline)
812
+ try {
813
+ await evolveProjectContext(phrenCtx, provider, result.messages, { sessionId });
814
+ }
815
+ catch { /* best effort */ }
607
816
  }
608
- catch { /* best effort */ }
609
817
  // Mirror the session into a searchable (non-injectable) note
610
818
  writeSessionNote(phrenCtx, { sessionId, task: args.task, outcome: result.finalText });
611
819
  }
@@ -619,7 +827,7 @@ export async function runAgentCli(raw) {
619
827
  turns: 0,
620
828
  toolCalls: 0,
621
829
  startedAt,
622
- sessionId,
830
+ sessionId: logSessionId,
623
831
  provider: provider.name,
624
832
  model: modelId,
625
833
  costTracker,