@phren/agent 0.3.20 → 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 (48) hide show
  1. package/dist/agent-loop/index.js +113 -19
  2. package/dist/agent-loop/stream.js +3 -1
  3. package/dist/attach-images.js +57 -0
  4. package/dist/commands/info.js +6 -2
  5. package/dist/commands/model.js +55 -13
  6. package/dist/commands/session.js +79 -18
  7. package/dist/commands.js +9 -2
  8. package/dist/config.js +45 -0
  9. package/dist/context/clear-tool-results.js +43 -0
  10. package/dist/context/compactor.js +8 -2
  11. package/dist/context/usage.js +26 -0
  12. package/dist/cost.js +10 -3
  13. package/dist/headless.js +41 -0
  14. package/dist/index.js +180 -56
  15. package/dist/mcp-client.js +38 -1
  16. package/dist/mcp-prompts.js +94 -0
  17. package/dist/multi/child-entry.js +3 -1
  18. package/dist/multi/spawner.js +27 -15
  19. package/dist/permissions/allowlist.js +19 -4
  20. package/dist/permissions/checker.js +37 -20
  21. package/dist/permissions/kernel-sandbox.js +32 -10
  22. package/dist/permissions/rules.js +173 -0
  23. package/dist/permissions/shell-classify.js +173 -0
  24. package/dist/plan.js +6 -2
  25. package/dist/repl.js +16 -1
  26. package/dist/session/persist.js +9 -4
  27. package/dist/settings.js +14 -0
  28. package/dist/structured-output.js +85 -0
  29. package/dist/system-prompt.js +117 -14
  30. package/dist/tools/apply-patch.js +15 -1
  31. package/dist/tools/edit-file.js +8 -1
  32. package/dist/tools/file-state.js +88 -0
  33. package/dist/tools/glob.js +53 -35
  34. package/dist/tools/grep.js +139 -53
  35. package/dist/tools/lint-test.js +24 -0
  36. package/dist/tools/read-file.js +2 -0
  37. package/dist/tools/registry.js +8 -1
  38. package/dist/tools/search-support.js +141 -0
  39. package/dist/tools/shell.js +3 -1
  40. package/dist/tools/spawn-agent.js +15 -3
  41. package/dist/tools/syntax-check.js +116 -0
  42. package/dist/tools/write-file.js +11 -3
  43. package/dist/tui/components/App.js +5 -4
  44. package/dist/tui/components/Banner.js +1 -1
  45. package/dist/tui/components/ListPicker.js +32 -0
  46. package/dist/tui/ink-entry.js +57 -16
  47. package/dist/user-hooks.js +26 -4
  48. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
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";
5
+ import { loadPermissionRules } from "./permissions/rules.js";
4
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";
@@ -28,19 +30,24 @@ import { livePreview, previewPath, removeStalePreviews } from "./session/preview
28
30
  import { startSession, endSession, getPriorSummary, saveSessionMessages, loadLastSessionSnapshot, writeSessionNote } from "./memory/session.js";
29
31
  import { emitHerdrHook, setHerdrHookSession } from "./herdr-hooks.js";
30
32
  import { loadProjectContext, evolveProjectContext } from "./memory/project-context.js";
31
- import { buildSystemPrompt } from "./system-prompt.js";
32
- import { loadHooksConfig } from "./user-hooks.js";
33
- 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";
34
38
  import { createSession, runTurn } from "./agent-loop.js";
35
39
  import { SessionLog, seedFromMessages } from "./session/log.js";
36
40
  import { fileSink, findEventLogById, findLatestEventLog, listEventLogs, persistFork, restoreSessionLog } from "./session/persist.js";
37
- import { buildHeadlessResult, createHeadlessHooks, headlessExitCode, readStdin } from "./headless.js";
41
+ import { buildHeadlessResult, createHeadlessHooks, headlessExitCode, parseStreamJsonInput, readLines, readStdin } from "./headless.js";
38
42
  import { createCostTracker } from "./cost.js";
39
43
  import { scopeModelOverrides } from "./model-overrides.js";
40
44
  import { codexLogin, codexLogout } from "./providers/codex-auth.js";
41
45
  import { createCheckpoint } from "./checkpoint.js";
42
- import { detectLintCommand, detectTestCommand } from "./tools/lint-test.js";
43
- 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";
44
51
  import { VERSION } from "./package-metadata.js";
45
52
  import { authProfilesPath, getAuthStatusEntries, removeApiKeyProfile, upsertApiKeyProfile, } from "@phren/cli/auth/profiles";
46
53
  function parseApiKeyProvider(raw) {
@@ -141,12 +148,11 @@ export async function runAgentCli(raw) {
141
148
  if (args.baseUrl)
142
149
  process.env.PHREN_AGENT_BASE_URL = args.baseUrl;
143
150
  if (args.listSessions) {
151
+ // Without a phren store, sessions live in ~/.phren-agent, listed for this directory.
144
152
  const ctx = await buildPhrenContext(args.project);
145
- if (!ctx) {
146
- console.error("Sessions are stored in the phren store; none was found.");
147
- process.exit(1);
148
- }
149
- 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 });
150
156
  if (args.outputFormat === "json") {
151
157
  console.log(JSON.stringify(sessions.map(({ file: _file, ...rest }) => ({ ...rest, updatedAt: new Date(rest.mtimeMs).toISOString() })), null, 2));
152
158
  }
@@ -162,8 +168,28 @@ export async function runAgentCli(raw) {
162
168
  }
163
169
  process.exit(0);
164
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
+ }
165
191
  // Headless with no task argument: read the task from piped stdin.
166
- if (args.print && !args.task && !process.stdin.isTTY) {
192
+ if (args.print && !streamInput && !args.task && !process.stdin.isTTY) {
167
193
  args.task = (await readStdin()).trim();
168
194
  }
169
195
  if (args.print) {
@@ -180,7 +206,7 @@ export async function runAgentCli(raw) {
180
206
  if (!args.task && args.resume) {
181
207
  args.task = "Continue where the previous session left off.";
182
208
  }
183
- if (!args.task && !args.interactive && !args.multi && !args.team) {
209
+ if (!args.task && !streamInput && !args.interactive && !args.multi && !args.team) {
184
210
  console.error("Usage: phren-agent <task>\nRun phren-agent --help for more info.");
185
211
  process.exit(1);
186
212
  }
@@ -259,25 +285,34 @@ export async function runAgentCli(raw) {
259
285
  loadAndRegisterCustomCommands(process.cwd());
260
286
  const chatMemory = chat ? buildChatMemory(phrenCtx) : "";
261
287
  const providerInfo = { name: provider.name, model: provider.model };
262
- const systemPrompt = chat
263
- ? buildChatSystemPrompt(chatMemory, providerInfo)
264
- : buildSystemPrompt(contextSnippet, priorSummary, providerInfo, getCustomCommandInfos());
265
- // Dry run: print system prompt and exit
266
- if (args.dryRun) {
267
- console.log("=== System Prompt ===");
268
- console.log(systemPrompt);
269
- console.log("\n=== Task ===");
270
- console.log(args.task);
271
- process.exit(0);
272
- }
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
+ });
273
300
  // Register tools
274
301
  const registry = new ToolRegistry();
275
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
+ }
276
309
  registry.setPermissions({
277
310
  mode: args.permissions,
278
311
  allowedPaths: [],
279
312
  projectRoot: process.cwd(),
280
313
  sandboxMode: args.sandbox,
314
+ ...(args.noNetwork ? { network: "off" } : {}),
315
+ rules: loadPermissionRules(process.cwd(), { allow: args.allowedTools, deny: args.disallowedTools }),
281
316
  });
282
317
  // Nobody can answer a prompt in a headless run or with stdin not a
283
318
  // terminal (a readline question on a closed stdin would hang): deny, and
@@ -286,7 +321,7 @@ export async function runAgentCli(raw) {
286
321
  if (args.print || (!process.stdin.isTTY && !args.interactive && !args.multi && !args.team)) {
287
322
  registry.askUser = async (toolName, _input, reason) => {
288
323
  permissionDenials++;
289
- 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`);
290
325
  return false;
291
326
  };
292
327
  }
@@ -326,6 +361,15 @@ export async function runAgentCli(raw) {
326
361
  registry.register(readMcpResourceTool);
327
362
  // MCP server connections
328
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
+ }
329
373
  if (args.mcpConfig) {
330
374
  Object.assign(mcpServers, loadMcpConfig(args.mcpConfig));
331
375
  }
@@ -333,15 +377,31 @@ export async function runAgentCli(raw) {
333
377
  const entry = parseMcpInline(args.mcp[idx]);
334
378
  mcpServers[`mcp-${idx}`] = entry;
335
379
  }
336
- if (Object.keys(mcpServers).length > 0) {
380
+ if (Object.keys(mcpServers).length > 0 && !args.dryRun) {
381
+ mcpServerNames.push(...Object.keys(mcpServers));
337
382
  const { tools: mcpTools, cleanup } = await connectMcpServers(mcpServers, args.verbose);
338
383
  mcpCleanup = cleanup;
339
384
  for (const tool of mcpTools)
340
385
  registry.register(tool);
386
+ // Their prompts become /mcp__server__prompt commands.
387
+ await loadMcpPrompts();
388
+ addCommandNames(mcpPromptCommandNames());
341
389
  }
342
390
  };
343
391
  if (!chat)
344
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);
404
+ }
345
405
  // Build cost tracker from model info
346
406
  const modelName = provider.model ?? args.model ?? provider.name;
347
407
  const costTracker = createCostTracker(modelName, args.budget, provider.name, provider.baseUrl);
@@ -350,7 +410,10 @@ export async function runAgentCli(raw) {
350
410
  const detectLintTest = () => {
351
411
  const lintCmd = args.lintCmd ?? detectLintCommand(cwd);
352
412
  const testCmd = args.testCmd ?? detectTestCommand(cwd);
353
- return (lintCmd || testCmd) ? { lintCmd: lintCmd ?? undefined, testCmd: testCmd ?? undefined } : undefined;
413
+ const typecheckCmd = args.typecheckCmd ?? detectTypecheckCommand(cwd);
414
+ return (lintCmd || testCmd || typecheckCmd)
415
+ ? { lintCmd: lintCmd ?? undefined, testCmd: testCmd ?? undefined, typecheckCmd: typecheckCmd ?? undefined }
416
+ : undefined;
354
417
  };
355
418
  // A chat edits nothing, so it has nothing to check.
356
419
  const lintTestConfig = chat ? undefined : detectLintTest();
@@ -360,16 +423,19 @@ export async function runAgentCli(raw) {
360
423
  if (lintTestConfig.testCmd)
361
424
  process.stderr.write(`Test: ${lintTestConfig.testCmd}\n`);
362
425
  }
363
- /** 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. */
364
432
  const makePersistedLog = () => {
365
- if (!phrenCtx || !sessionId)
366
- return undefined;
367
433
  return new SessionLog({
368
- sessionId,
369
- project: phrenCtx.project ?? undefined,
434
+ sessionId: logSessionId,
435
+ project: phrenCtx?.project ?? undefined,
370
436
  cwd: process.cwd(),
371
437
  createdAt: new Date().toISOString(),
372
- }, fileSink(phrenCtx.phrenPath, sessionId));
438
+ }, fileSink(sessionRoot, logSessionId));
373
439
  };
374
440
  /**
375
441
  * Resume seed: newest event log preferred, legacy v1 snapshot as fallback.
@@ -378,12 +444,10 @@ export async function runAgentCli(raw) {
378
444
  * previous session.
379
445
  */
380
446
  const makeResumedLog = () => {
381
- if (!phrenCtx || !sessionId)
382
- return undefined;
383
447
  let latest;
384
448
  if (args.resumeId) {
385
449
  try {
386
- latest = findEventLogById(phrenCtx.phrenPath, args.resumeId);
450
+ latest = findEventLogById(sessionRoot, args.resumeId);
387
451
  }
388
452
  catch (err) {
389
453
  process.stderr.write(`Cannot resume: ${err instanceof Error ? err.message : String(err)}\n`);
@@ -391,25 +455,27 @@ export async function runAgentCli(raw) {
391
455
  }
392
456
  }
393
457
  else {
394
- latest = findLatestEventLog(phrenCtx.phrenPath, phrenCtx.project ?? undefined);
458
+ latest = phrenCtx
459
+ ? findLatestEventLog(sessionRoot, phrenCtx.project ?? undefined)
460
+ : findLatestEventLog(sessionRoot, undefined, process.cwd());
395
461
  }
396
462
  if (latest) {
397
463
  try {
398
- const parent = restoreSessionLog(phrenCtx.phrenPath, latest);
464
+ const parent = restoreSessionLog(sessionRoot, latest);
399
465
  if (parent.length > 0) {
400
466
  if (args.verbose) {
401
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`);
402
468
  }
403
469
  // This run gets its own forked log file, seeded with the parent's
404
470
  // full history and linked via parentSession.
405
- return persistFork(phrenCtx.phrenPath, parent, sessionId);
471
+ return persistFork(sessionRoot, parent, logSessionId);
406
472
  }
407
473
  }
408
474
  catch (err) {
409
475
  process.stderr.write(`Cannot resume from event log (${err instanceof Error ? err.message : String(err)}); trying legacy snapshot\n`);
410
476
  }
411
477
  }
412
- if (args.resumeId)
478
+ if (args.resumeId || !phrenCtx)
413
479
  return undefined; // a named session never falls back to another one
414
480
  const priorSnapshot = loadLastSessionSnapshot(phrenCtx.phrenPath, phrenCtx.project ?? undefined);
415
481
  if (priorSnapshot && priorSnapshot.messages.length > 0) {
@@ -417,8 +483,6 @@ export async function runAgentCli(raw) {
417
483
  process.stderr.write(`Resuming session ${priorSnapshot.sessionId.slice(0, 8)} (${priorSnapshot.project ?? "global"}) with ${priorSnapshot.messages.length} messages from a v1 snapshot\n`);
418
484
  }
419
485
  const log = makePersistedLog();
420
- if (!log)
421
- return undefined;
422
486
  seedFromMessages(log, priorSnapshot.messages);
423
487
  return log;
424
488
  }
@@ -449,6 +513,8 @@ export async function runAgentCli(raw) {
449
513
  removeStalePreviews(phrenPath);
450
514
  agentConfig.livePreview = (id) => id.startsWith("mem-") ? undefined : livePreview(previewPath(phrenPath, id));
451
515
  }
516
+ if (!chat)
517
+ agentConfig.rebuildSystemPrompt = agentPrompt;
452
518
  if (chat) {
453
519
  agentConfig.rebuildSystemPrompt = (info) => buildChatSystemPrompt(chatMemory, info);
454
520
  // Same conversation, same log: only the tools and the prompt change.
@@ -465,13 +531,13 @@ export async function runAgentCli(raw) {
465
531
  const projectCtx = phrenCtx ? loadProjectContext(phrenCtx) : null;
466
532
  if (phrenCtx && projectCtx)
467
533
  snippet += `\n\n## Agent context (${phrenCtx.project})\n\n${projectCtx}`;
468
- const systemPrompt = buildSystemPrompt(snippet, null, {
469
- name: agentConfig.provider.name,
470
- model: agentConfig.provider.model,
471
- }, getCustomCommandInfos());
534
+ promptContext = snippet;
535
+ promptSummary = null;
536
+ const info = { name: agentConfig.provider.name, model: agentConfig.provider.model };
537
+ const systemPrompt = agentPrompt(info);
472
538
  const lintTestConfig = detectLintTest();
473
539
  agentConfig.mode = "agent";
474
- agentConfig.rebuildSystemPrompt = undefined;
540
+ agentConfig.rebuildSystemPrompt = agentPrompt;
475
541
  agentConfig.systemPrompt = systemPrompt;
476
542
  agentConfig.lintTestConfig = lintTestConfig;
477
543
  }
@@ -520,8 +586,10 @@ export async function runAgentCli(raw) {
520
586
  registry.register(createSendMessageTool(spawner));
521
587
  registry.register(createListAgentsTool(spawner));
522
588
  };
523
- if (!chat)
589
+ if (!chat) {
524
590
  registerSpawnerTools();
591
+ agentConfig.systemPrompt = agentPrompt(providerInfo);
592
+ }
525
593
  // Publish this process's agents so a phren graph in another terminal can
526
594
  // show them. Best-effort and silent: it is a courtesy to another tool.
527
595
  const { createAgentPublisher } = await import("./multi/publish.js");
@@ -597,6 +665,7 @@ export async function runAgentCli(raw) {
597
665
  registry.register(createSpawnAgentTool(oneShotSpawner, () => registry.permissionConfig));
598
666
  registry.register(createSendMessageTool(oneShotSpawner));
599
667
  registry.register(createListAgentsTool(oneShotSpawner));
668
+ agentConfig.systemPrompt = agentPrompt(providerInfo);
600
669
  }
601
670
  const startedAt = Date.now();
602
671
  const headlessHooks = args.print
@@ -618,7 +687,7 @@ export async function runAgentCli(raw) {
618
687
  process.stdout.write(`${JSON.stringify({
619
688
  type: "system",
620
689
  subtype: "init",
621
- session_id: sessionId,
690
+ session_id: logSessionId,
622
691
  provider: provider.name,
623
692
  model: modelId,
624
693
  cwd,
@@ -634,12 +703,54 @@ export async function runAgentCli(raw) {
634
703
  }
635
704
  // A resumed session continues with the task given on the command line,
636
705
  // or with a generic "continue" when none was.
637
- const prompt = resumedLog && !userTask
706
+ const given = resumedLog && !userTask
638
707
  ? "Continuing where we left off. Please review the conversation and continue with the task."
639
708
  : args.task;
709
+ // `phren agent "/mcp__server__prompt …"` sends what the MCP prompt says.
710
+ const prompt = isMcpPromptCommand(given) ? await resolveMcpPromptCommand(given) : given;
640
711
  const session = createSession(contextLimit, { log: resumedLog ?? agentConfig.sessionLog });
641
- emitHerdrHook("UserPromptSubmit");
642
- 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
+ }
643
754
  const result = {
644
755
  finalText: turnResult.text,
645
756
  turns: turnResult.turns,
@@ -652,19 +763,32 @@ export async function runAgentCli(raw) {
652
763
  const costStr = result.totalCost ? `, ${result.totalCost}` : "";
653
764
  process.stderr.write(`\nDone: ${result.turns} turns, ${result.toolCalls} tool calls${costStr}\n`);
654
765
  }
655
- 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;
656
772
  const headless = buildHeadlessResult({
657
773
  text: turnResult.text,
658
774
  stopReason: turnResult.stopReason,
659
775
  turns: turnResult.turns,
660
776
  toolCalls: turnResult.toolCalls,
661
777
  startedAt,
662
- sessionId,
778
+ sessionId: logSessionId,
663
779
  provider: provider.name,
664
780
  model: modelId,
665
781
  costTracker,
666
782
  permissionDenials,
667
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
+ }
668
792
  emitHeadless(headless);
669
793
  exitCode = headlessExitCode(headless);
670
794
  }
@@ -703,7 +827,7 @@ export async function runAgentCli(raw) {
703
827
  turns: 0,
704
828
  toolCalls: 0,
705
829
  startedAt,
706
- sessionId,
830
+ sessionId: logSessionId,
707
831
  provider: provider.name,
708
832
  model: modelId,
709
833
  costTracker,
@@ -7,6 +7,7 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
7
7
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
8
  import { spawn } from "child_process";
9
9
  import * as fs from "fs";
10
+ import * as path from "path";
10
11
  import * as readline from "readline";
11
12
  import { McpOAuthProvider } from "./mcp-oauth.js";
12
13
  import { VERSION } from "./package-metadata.js";
@@ -383,6 +384,20 @@ function formatToolResult(result) {
383
384
  })
384
385
  .join("\n");
385
386
  }
387
+ /**
388
+ * Longest MCP tool result the model gets, in chars (about 25k tokens, Claude
389
+ * Code's default). One server answering with a whole database dump must not
390
+ * fill the context. PHREN_AGENT_MCP_MAX_OUTPUT_CHARS changes it.
391
+ */
392
+ function maxMcpOutputChars() {
393
+ const raw = Number(process.env.PHREN_AGENT_MCP_MAX_OUTPUT_CHARS);
394
+ return Number.isFinite(raw) && raw > 0 ? raw : 100_000;
395
+ }
396
+ export function capMcpOutput(text, max = maxMcpOutputChars()) {
397
+ if (text.length <= max)
398
+ return text;
399
+ return `${text.slice(0, max)}\n\n[MCP output truncated: ${text.length} chars, showing the first ${max}. Ask the tool for less, with a filter or a page, if it takes one.]`;
400
+ }
386
401
  /** Wrap an MCP tool as an AgentTool. */
387
402
  function wrapMcpTool(conn, def) {
388
403
  return {
@@ -392,7 +407,7 @@ function wrapMcpTool(conn, def) {
392
407
  async execute(input, signal) {
393
408
  try {
394
409
  const result = await conn.callTool(def.name, input, signal);
395
- const text = formatToolResult(result);
410
+ const text = capMcpOutput(formatToolResult(result));
396
411
  return result?.isError ? { output: text, is_error: true } : { output: text };
397
412
  }
398
413
  catch (err) {
@@ -485,6 +500,28 @@ export async function connectMcpServers(servers, verbose = false) {
485
500
  },
486
501
  };
487
502
  }
503
+ /**
504
+ * The MCP servers a session gets without flags: the user's
505
+ * `~/.phren-agent/mcp.json`, then the project's `.mcp.json` (Claude Code's
506
+ * file) and `.phren-agent/mcp.json`. A project file starts commands from
507
+ * whatever repository is checked out, so it loads only for a project the
508
+ * user trusted (`--trust-project-mcp`, remembered); otherwise it is reported
509
+ * in `untrusted`.
510
+ */
511
+ export function loadDefaultMcpConfig(cwd, opts) {
512
+ const servers = { ...loadMcpConfig(path.join(opts.home, ".phren-agent", "mcp.json")) };
513
+ const untrusted = [];
514
+ for (const file of [path.join(cwd, ".mcp.json"), path.join(cwd, ".phren-agent", "mcp.json")]) {
515
+ const found = loadMcpConfig(file);
516
+ if (Object.keys(found).length === 0)
517
+ continue;
518
+ if (opts.trusted)
519
+ Object.assign(servers, found);
520
+ else
521
+ untrusted.push({ file, names: Object.keys(found) });
522
+ }
523
+ return { servers, untrusted };
524
+ }
488
525
  /** Load MCP server config from a JSON file (same format as Claude Code's mcpServers). */
489
526
  export function loadMcpConfig(configPath) {
490
527
  if (!fs.existsSync(configPath))
@@ -0,0 +1,94 @@
1
+ /**
2
+ * MCP prompts as slash commands, the way Claude Code offers them:
3
+ * `/mcp__<server>__<prompt> [args]` fetches the prompt from its server and
4
+ * sends what it returns as the next message.
5
+ *
6
+ * Arguments are positional, in the order the prompt declares them; the last
7
+ * one takes the rest of the line, so a single free-text argument needs no
8
+ * quoting.
9
+ */
10
+ import { mcpRegistry } from "./mcp-client.js";
11
+ const PREFIX = "/mcp__";
12
+ let known = [];
13
+ /** Ask every connected server for its prompts; a server without prompts is skipped. */
14
+ export async function loadMcpPrompts() {
15
+ const out = [];
16
+ for (const server of mcpRegistry.listServers()) {
17
+ try {
18
+ out.push(...await mcpRegistry.listPrompts(server));
19
+ }
20
+ catch {
21
+ // Prompts are optional in MCP; "method not found" is normal.
22
+ }
23
+ }
24
+ known = out;
25
+ return out;
26
+ }
27
+ export function mcpPromptCommandName(prompt) {
28
+ return `${PREFIX}${prompt.server}__${prompt.name}`;
29
+ }
30
+ /** Slash command names for the prompts found by loadMcpPrompts, for completion and help. */
31
+ export function mcpPromptCommandNames() {
32
+ return known.map(mcpPromptCommandName);
33
+ }
34
+ export function isMcpPromptCommand(input) {
35
+ return input.startsWith(PREFIX);
36
+ }
37
+ /** Map the words after the command onto the prompt's declared arguments. */
38
+ export function promptArguments(prompt, rest) {
39
+ const names = (prompt.arguments ?? []).map((a) => a.name);
40
+ const args = {};
41
+ let remaining = rest.trim();
42
+ names.forEach((name, i) => {
43
+ if (!remaining)
44
+ return;
45
+ if (i === names.length - 1) {
46
+ args[name] = remaining;
47
+ remaining = "";
48
+ return;
49
+ }
50
+ const match = /^(\S+)\s*([\s\S]*)$/.exec(remaining);
51
+ args[name] = match[1];
52
+ remaining = match[2];
53
+ });
54
+ return args;
55
+ }
56
+ function contentText(content) {
57
+ const blocks = Array.isArray(content) ? content : [content];
58
+ return blocks
59
+ .map((b) => (typeof b.text === "string" ? b.text : b.resource?.text ?? (b.resource?.uri ? `[resource ${b.resource.uri}]` : "")))
60
+ .filter(Boolean)
61
+ .join("\n");
62
+ }
63
+ /**
64
+ * The message an `/mcp__server__prompt …` line becomes. Throws with a message
65
+ * fit for the user when the prompt is unknown, an argument is missing, or the
66
+ * server fails.
67
+ */
68
+ export async function resolveMcpPromptCommand(input) {
69
+ const trimmed = input.trim();
70
+ const command = trimmed.split(/\s+/, 1)[0];
71
+ const rest = trimmed.slice(command.length);
72
+ const prompt = known.find((p) => mcpPromptCommandName(p) === command);
73
+ if (!prompt)
74
+ throw new Error(`No MCP prompt ${command}.${known.length > 0 ? ` Known: ${mcpPromptCommandNames().join(", ")}` : " No connected server offers prompts."}`);
75
+ const args = promptArguments(prompt, rest);
76
+ const missing = (prompt.arguments ?? []).filter((a) => a.required && !args[a.name]).map((a) => a.name);
77
+ if (missing.length > 0)
78
+ throw new Error(`${command} needs: ${(prompt.arguments ?? []).map((a) => (a.required ? a.name : `[${a.name}]`)).join(" ")}`);
79
+ const result = await mcpRegistry.getPrompt(prompt.server, prompt.name, args);
80
+ const text = (result.messages ?? [])
81
+ .map((m) => {
82
+ const body = contentText(m.content);
83
+ return m.role === "assistant" && body ? `(assistant) ${body}` : body;
84
+ })
85
+ .filter(Boolean)
86
+ .join("\n\n");
87
+ if (!text)
88
+ throw new Error(`${command} returned no text.`);
89
+ return text;
90
+ }
91
+ /** Test seam. */
92
+ export function setMcpPrompts(prompts) {
93
+ known = prompts;
94
+ }
@@ -67,7 +67,7 @@ async function initAgentState(payload) {
67
67
  const { model: overridden, ...overrides } = payload.modelOverrides;
68
68
  scopeModelOverrides(overridden, overrides);
69
69
  }
70
- const provider = resolveProvider(providerName, model, undefined, undefined, { baseUrl: payload.baseUrl });
70
+ const provider = resolveProvider(providerName, model, undefined, payload.reasoning, { baseUrl: payload.baseUrl });
71
71
  // Child agents get a lightweight prompt — no "search memory first" forcing
72
72
  const systemPrompt = buildChildPrompt(_task);
73
73
  // Quick phren init — just resolve context, skip slow FTS5 search
@@ -83,6 +83,8 @@ async function initAgentState(payload) {
83
83
  allowedPaths: payload.allowedPaths ?? [],
84
84
  projectRoot: payload.worktreePath ?? cwd,
85
85
  sandboxMode: payload.sandboxMode,
86
+ network: payload.network,
87
+ rules: payload.rules,
86
88
  });
87
89
  // Headless child: an "ask" verdict has no human to answer it, and the
88
90
  // default readline prompt would hang forever on a closed stdin. Deny with