@phren/agent 0.3.18 → 0.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cost.js CHANGED
@@ -1,25 +1,73 @@
1
1
  /** Cost tracking for LLM API usage. */
2
2
  import { lookupPricing } from "./models.js";
3
- export function createCostTracker(model, budget = null, provider) {
4
- const { pricing, metered } = lookupPricing(model, provider);
3
+ import { overridesFor } from "./model-overrides.js";
4
+ /**
5
+ * Price a model and endpoint. The --price-* flags (when this is the model
6
+ * they were given for), then PHREN_AGENT_PRICE_IN/OUT/CACHE (USD per 1M),
7
+ * take precedence over the catalog.
8
+ */
9
+ export function resolvePricing(model, provider, baseUrl) {
10
+ const looked = lookupPricing(model, provider, baseUrl);
11
+ const env = (key) => {
12
+ const raw = process.env[key];
13
+ if (raw === undefined || raw === "")
14
+ return undefined;
15
+ const value = Number(raw);
16
+ return Number.isFinite(value) && value >= 0 ? value : undefined;
17
+ };
18
+ const flags = overridesFor(model);
19
+ const input = flags.priceIn ?? env("PHREN_AGENT_PRICE_IN");
20
+ const output = flags.priceOut ?? env("PHREN_AGENT_PRICE_OUT");
21
+ const cacheRead = flags.priceCache ?? env("PHREN_AGENT_PRICE_CACHE");
22
+ if (input === undefined && output === undefined && cacheRead === undefined)
23
+ return looked;
24
+ // An explicit price means the user is paying per token, even on a route
25
+ // the catalog calls included.
26
+ const cache = cacheRead ?? looked.pricing.cacheReadPer1M;
27
+ return {
28
+ pricing: {
29
+ inputPer1M: input ?? looked.pricing.inputPer1M,
30
+ outputPer1M: output ?? looked.pricing.outputPer1M,
31
+ ...(cache !== undefined ? { cacheReadPer1M: cache } : {}),
32
+ },
33
+ metered: true,
34
+ };
35
+ }
36
+ /** Prompt-cache writes cost this much more than ordinary input. */
37
+ export const CACHE_WRITE_MULTIPLIER = 1.25;
38
+ export function createCostTracker(model, budget = null, provider, baseUrl) {
39
+ const { pricing, metered } = resolvePricing(model, provider, baseUrl);
40
+ // Without a cache price, hits bill as ordinary input (no discount assumed).
41
+ const cacheReadPer1M = pricing.cacheReadPer1M ?? pricing.inputPer1M;
42
+ // Cache writes bill at 1.25x input (Anthropic's 5-minute cache, the one
43
+ // the agent asks for); providers that cache implicitly report none.
44
+ const cacheWritePer1M = pricing.inputPer1M * CACHE_WRITE_MULTIPLIER;
45
+ const price = (input, output, cacheRead, cacheWrite) => (input / 1_000_000) * pricing.inputPer1M +
46
+ (output / 1_000_000) * pricing.outputPer1M +
47
+ (cacheRead / 1_000_000) * cacheReadPer1M +
48
+ (cacheWrite / 1_000_000) * cacheWritePer1M;
5
49
  const tracker = {
6
50
  totalInputTokens: 0,
7
51
  totalOutputTokens: 0,
52
+ totalCacheReadTokens: 0,
53
+ totalCacheWriteTokens: 0,
8
54
  totalCost: 0,
9
55
  budget,
10
56
  metered,
11
- recordUsage(inputTokens, outputTokens) {
57
+ recordUsage(inputTokens, outputTokens, cacheReadTokens = 0, cacheWriteTokens = 0) {
12
58
  tracker.totalInputTokens += inputTokens;
13
59
  tracker.totalOutputTokens += outputTokens;
14
- tracker.totalCost +=
15
- (inputTokens / 1_000_000) * pricing.inputPer1M +
16
- (outputTokens / 1_000_000) * pricing.outputPer1M;
60
+ tracker.totalCacheReadTokens += cacheReadTokens;
61
+ tracker.totalCacheWriteTokens += cacheWriteTokens;
62
+ tracker.totalCost += price(inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens);
17
63
  },
18
64
  isOverBudget() {
19
65
  return tracker.metered && budget !== null && tracker.totalCost >= budget;
20
66
  },
21
67
  formatCost() {
22
- const tokens = `${tracker.totalInputTokens + tracker.totalOutputTokens} tokens`;
68
+ const total = tracker.totalInputTokens + tracker.totalOutputTokens + tracker.totalCacheReadTokens + tracker.totalCacheWriteTokens;
69
+ const cached = tracker.totalCacheReadTokens > 0 ? `, ${tracker.totalCacheReadTokens} cached` : "";
70
+ const tokens = `${total} tokens${cached}`;
23
71
  if (!tracker.metered) {
24
72
  return `included (${tokens})`;
25
73
  }
@@ -29,11 +77,10 @@ export function createCostTracker(model, budget = null, provider) {
29
77
  const budgetStr = budget !== null ? ` / $${budget.toFixed(2)} budget` : "";
30
78
  return `${cost} (${tokens}${budgetStr})`;
31
79
  },
32
- formatTurnCost(inputTokens, outputTokens) {
80
+ formatTurnCost(inputTokens, outputTokens, cacheReadTokens = 0, cacheWriteTokens = 0) {
33
81
  if (!tracker.metered)
34
82
  return "included";
35
- const turnCost = (inputTokens / 1_000_000) * pricing.inputPer1M +
36
- (outputTokens / 1_000_000) * pricing.outputPer1M;
83
+ const turnCost = price(inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens);
37
84
  return turnCost < 0.01
38
85
  ? `$${turnCost.toFixed(4)}`
39
86
  : `$${turnCost.toFixed(2)}`;
@@ -41,3 +88,7 @@ export function createCostTracker(model, budget = null, provider) {
41
88
  };
42
89
  return tracker;
43
90
  }
91
+ /** Record one response's usage, every bucket included. */
92
+ export function recordTokenUsage(tracker, usage) {
93
+ tracker.recordUsage(usage.input_tokens, usage.output_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens);
94
+ }
package/dist/headless.js CHANGED
@@ -19,7 +19,12 @@ export function buildHeadlessResult(opts) {
19
19
  session_id: opts.sessionId,
20
20
  provider: opts.provider,
21
21
  model: opts.model,
22
- usage: { input_tokens: tracker?.totalInputTokens ?? 0, output_tokens: tracker?.totalOutputTokens ?? 0 },
22
+ usage: {
23
+ input_tokens: tracker?.totalInputTokens ?? 0,
24
+ output_tokens: tracker?.totalOutputTokens ?? 0,
25
+ cache_read_input_tokens: tracker?.totalCacheReadTokens ?? 0,
26
+ cache_creation_input_tokens: tracker?.totalCacheWriteTokens ?? 0,
27
+ },
23
28
  total_cost_usd: tracker?.metered ? Number(tracker.totalCost.toFixed(6)) : null,
24
29
  permission_denials: opts.permissionDenials,
25
30
  ...(opts.error ? { error: opts.error } : {}),
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs, printHelp, resolveStartupPermissions } from "./config.js";
3
3
  import { loadPersistentAllowlist } from "./permissions/allowlist.js";
4
- import { resolveProvider } from "./providers/resolve.js";
4
+ import { keepSessionEndpoint, resolveProvider } from "./providers/resolve.js";
5
5
  import { ToolRegistry } from "./tools/registry.js";
6
6
  import { readFileTool } from "./tools/read-file.js";
7
7
  import { writeFileTool } from "./tools/write-file.js";
@@ -23,6 +23,8 @@ import { gitStatusTool, gitDiffTool, gitCommitTool } from "./tools/git.js";
23
23
  import { updatePlanTool } from "./tools/update-plan.js";
24
24
  import { listMcpResourcesTool, readMcpResourceTool } from "./tools/mcp-resources.js";
25
25
  import { buildPhrenContext, buildContextSnippet, buildProjectInstructions } from "./memory/context.js";
26
+ import { buildChatMemory, buildChatSystemPrompt } from "./memory/chat.js";
27
+ import { livePreview, previewPath, removeStalePreviews } from "./session/preview.js";
26
28
  import { startSession, endSession, getPriorSummary, saveSessionMessages, loadLastSessionSnapshot, writeSessionNote } from "./memory/session.js";
27
29
  import { emitHerdrHook, setHerdrHookSession } from "./herdr-hooks.js";
28
30
  import { loadProjectContext, evolveProjectContext } from "./memory/project-context.js";
@@ -34,6 +36,7 @@ import { SessionLog, seedFromMessages } from "./session/log.js";
34
36
  import { fileSink, findEventLogById, findLatestEventLog, listEventLogs, persistFork, restoreSessionLog } from "./session/persist.js";
35
37
  import { buildHeadlessResult, createHeadlessHooks, headlessExitCode, readStdin } from "./headless.js";
36
38
  import { createCostTracker } from "./cost.js";
39
+ import { scopeModelOverrides } from "./model-overrides.js";
37
40
  import { codexLogin, codexLogout } from "./providers/codex-auth.js";
38
41
  import { createCheckpoint } from "./checkpoint.js";
39
42
  import { detectLintCommand, detectTestCommand } from "./tools/lint-test.js";
@@ -132,8 +135,9 @@ export async function runAgentCli(raw) {
132
135
  console.log(`phren-agent v${VERSION}`);
133
136
  process.exit(0);
134
137
  }
135
- // Model switches and spawned children resolve the provider again; they
136
- // read the endpoint from the environment.
138
+ // Model switches resolve the provider again; they read the endpoint from
139
+ // the environment. The window and prices stay with the model they were
140
+ // given for (scopeModelOverrides, below).
137
141
  if (args.baseUrl)
138
142
  process.env.PHREN_AGENT_BASE_URL = args.baseUrl;
139
143
  if (args.listSessions) {
@@ -166,6 +170,11 @@ export async function runAgentCli(raw) {
166
170
  args.interactive = false;
167
171
  args.multi = false;
168
172
  }
173
+ const chat = args.mode === "chat";
174
+ if (chat && (args.multi || args.team)) {
175
+ console.error("--mode chat is a single conversation; it cannot run with --multi or --team.");
176
+ process.exit(1);
177
+ }
169
178
  // `--resume` alone continues the prior session without a placeholder task
170
179
  const userTask = args.task;
171
180
  if (!args.task && args.resume) {
@@ -178,12 +187,19 @@ export async function runAgentCli(raw) {
178
187
  // Resolve LLM provider
179
188
  let provider;
180
189
  try {
181
- provider = resolveProvider(args.provider, args.model, args.maxOutput, args.reasoning, { baseUrl: args.baseUrl });
190
+ provider = resolveProvider(args.provider, args.model, args.maxOutput, args.reasoning, { baseUrl: args.baseUrl, contextWindow: args.contextWindow });
182
191
  }
183
192
  catch (err) {
184
193
  console.error(err instanceof Error ? err.message : String(err));
185
194
  process.exit(1);
186
195
  }
196
+ keepSessionEndpoint(provider);
197
+ scopeModelOverrides(provider.model ?? args.model ?? provider.name, {
198
+ contextWindow: args.contextWindow,
199
+ priceIn: args.priceIn,
200
+ priceOut: args.priceOut,
201
+ priceCache: args.priceCache,
202
+ });
187
203
  if (args.verbose) {
188
204
  process.stderr.write(`Provider: ${provider.name}\n`);
189
205
  }
@@ -198,7 +214,8 @@ export async function runAgentCli(raw) {
198
214
  }
199
215
  // Review-queue surfacing. Interactive sessions get expiry + a triage
200
216
  // banner; one-shot runs get a count only and never mutate the queue.
201
- if (phrenCtx.project) {
217
+ // A quick chat skips it: it cannot act on the queue.
218
+ if (phrenCtx.project && !chat) {
202
219
  try {
203
220
  const { getQueueStatus, formatQueueBanner, formatExpiryNotice, expireStaleItems, resolveExpireDays } = await import("./memory/review-triage.js");
204
221
  if (args.interactive || args.multi || args.team) {
@@ -220,26 +237,31 @@ export async function runAgentCli(raw) {
220
237
  }
221
238
  catch { /* best effort */ }
222
239
  }
223
- contextSnippet = await buildContextSnippet(phrenCtx, args.task);
224
- priorSummary = getPriorSummary(phrenCtx);
240
+ // A quick chat reads its memory from files below; the agent's snippet
241
+ // builds the search index, which is what makes a first answer slow.
242
+ if (!chat) {
243
+ contextSnippet = await buildContextSnippet(phrenCtx, args.task);
244
+ priorSummary = getPriorSummary(phrenCtx);
245
+ }
225
246
  sessionId = startSession(phrenCtx);
226
247
  // Inside a Herdr pane, tell Phren Hook which event log is this pane's.
227
248
  setHerdrHookSession(sessionId);
228
249
  emitHerdrHook("SessionStart");
229
250
  // Load evolved project context for warm start
230
- const projectCtx = loadProjectContext(phrenCtx);
251
+ const projectCtx = chat ? null : loadProjectContext(phrenCtx);
231
252
  if (projectCtx) {
232
253
  contextSnippet += `\n\n## Agent context (${phrenCtx.project})\n\n${projectCtx}`;
233
254
  }
234
255
  }
235
256
  // Without a phren store, the repo's AGENTS.md / CLAUDE.md still apply.
236
- if (!phrenCtx)
257
+ if (!phrenCtx && !chat)
237
258
  contextSnippet = buildProjectInstructions();
238
259
  loadAndRegisterCustomCommands(process.cwd());
239
- const systemPrompt = buildSystemPrompt(contextSnippet, priorSummary, {
240
- name: provider.name,
241
- model: provider.model,
242
- }, getCustomCommandInfos());
260
+ const chatMemory = chat ? buildChatMemory(phrenCtx) : "";
261
+ const providerInfo = { name: provider.name, model: provider.model };
262
+ const systemPrompt = chat
263
+ ? buildChatSystemPrompt(chatMemory, providerInfo)
264
+ : buildSystemPrompt(contextSnippet, priorSummary, providerInfo, getCustomCommandInfos());
243
265
  // Dry run: print system prompt and exit
244
266
  if (args.dryRun) {
245
267
  console.log("=== System Prompt ===");
@@ -268,61 +290,70 @@ export async function runAgentCli(raw) {
268
290
  return false;
269
291
  };
270
292
  }
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
293
+ // The agent's tools. A quick chat starts with none and gets them on /promote.
303
294
  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);
317
- }
295
+ const registerAgentTools = async () => {
296
+ registry.register(readFileTool);
297
+ registry.register(writeFileTool);
298
+ registry.register(editFileTool);
299
+ registry.register(multiEditTool);
300
+ registry.register(applyPatchTool);
301
+ // Live-config factory: /permissions and sandbox mode changes apply per call
302
+ registry.register(createShellTool(() => registry.permissionConfig));
303
+ registry.register(taskOutputTool);
304
+ registry.register(taskStopTool);
305
+ registry.register(globTool);
306
+ registry.register(grepTool);
307
+ if (modelSupportsVision(provider.name, provider.model ?? "")) {
308
+ registry.register(createReadImageTool(provider));
309
+ }
310
+ if (phrenCtx) {
311
+ registry.register(createPhrenSearchTool(phrenCtx));
312
+ registry.register(createPhrenFindingTool(phrenCtx, sessionId));
313
+ registry.register(createPhrenGetTasksTool(phrenCtx));
314
+ registry.register(createPhrenCompleteTaskTool(phrenCtx, sessionId));
315
+ registry.register(createPhrenAddTaskTool(phrenCtx, sessionId));
316
+ registry.register(createSkillTool(phrenCtx));
317
+ }
318
+ // Web tools
319
+ registry.register(createWebFetchTool());
320
+ registry.register(createWebSearchTool());
321
+ registry.register(gitStatusTool);
322
+ registry.register(gitDiffTool);
323
+ registry.register(gitCommitTool);
324
+ registry.register(updatePlanTool);
325
+ registry.register(listMcpResourcesTool);
326
+ registry.register(readMcpResourceTool);
327
+ // MCP server connections
328
+ const mcpServers = {};
329
+ if (args.mcpConfig) {
330
+ Object.assign(mcpServers, loadMcpConfig(args.mcpConfig));
331
+ }
332
+ for (let idx = 0; idx < args.mcp.length; idx++) {
333
+ const entry = parseMcpInline(args.mcp[idx]);
334
+ mcpServers[`mcp-${idx}`] = entry;
335
+ }
336
+ if (Object.keys(mcpServers).length > 0) {
337
+ const { tools: mcpTools, cleanup } = await connectMcpServers(mcpServers, args.verbose);
338
+ mcpCleanup = cleanup;
339
+ for (const tool of mcpTools)
340
+ registry.register(tool);
341
+ }
342
+ };
343
+ if (!chat)
344
+ await registerAgentTools();
318
345
  // Build cost tracker from model info
319
346
  const modelName = provider.model ?? args.model ?? provider.name;
320
- const costTracker = createCostTracker(modelName, args.budget, provider.name);
347
+ const costTracker = createCostTracker(modelName, args.budget, provider.name, provider.baseUrl);
321
348
  // Build lint/test config from CLI flags or auto-detect
322
349
  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;
350
+ const detectLintTest = () => {
351
+ const lintCmd = args.lintCmd ?? detectLintCommand(cwd);
352
+ const testCmd = args.testCmd ?? detectTestCommand(cwd);
353
+ return (lintCmd || testCmd) ? { lintCmd: lintCmd ?? undefined, testCmd: testCmd ?? undefined } : undefined;
354
+ };
355
+ // A chat edits nothing, so it has nothing to check.
356
+ const lintTestConfig = chat ? undefined : detectLintTest();
326
357
  if (args.verbose && lintTestConfig) {
327
358
  if (lintTestConfig.lintCmd)
328
359
  process.stderr.write(`Lint: ${lintTestConfig.lintCmd}\n`);
@@ -394,6 +425,8 @@ export async function runAgentCli(raw) {
394
425
  return undefined;
395
426
  };
396
427
  const resumedLog = args.resume ? makeResumedLog() : undefined;
428
+ /** Spawner tools, once an interactive session has a spawner. */
429
+ let registerSpawnerTools;
397
430
  const agentConfig = {
398
431
  provider,
399
432
  registry,
@@ -408,7 +441,51 @@ export async function runAgentCli(raw) {
408
441
  hookConfig: registry.hookConfig,
409
442
  sessionLog: resumedLog ?? makePersistedLog(),
410
443
  ...(args.noLlmCompact ? { compaction: { enabled: false } } : {}),
444
+ mode: args.mode,
411
445
  };
446
+ // The phone reads the reply being written from a sidecar of the event log.
447
+ if (phrenCtx && agentConfig.sessionLog && (args.interactive || args.multi || args.team)) {
448
+ const phrenPath = phrenCtx.phrenPath;
449
+ removeStalePreviews(phrenPath);
450
+ agentConfig.livePreview = (id) => id.startsWith("mem-") ? undefined : livePreview(previewPath(phrenPath, id));
451
+ }
452
+ if (chat) {
453
+ agentConfig.rebuildSystemPrompt = (info) => buildChatSystemPrompt(chatMemory, info);
454
+ // Same conversation, same log: only the tools and the prompt change.
455
+ // Nothing about the session changes until every step has succeeded; a
456
+ // failure (an MCP server that won't start) leaves it a working chat.
457
+ agentConfig.promote = async () => {
458
+ if (agentConfig.mode !== "chat")
459
+ return "Already an agent session.";
460
+ const before = new Set(registry.toolNames());
461
+ try {
462
+ await registerAgentTools();
463
+ registerSpawnerTools?.();
464
+ let snippet = phrenCtx ? await buildContextSnippet(phrenCtx, "") : buildProjectInstructions();
465
+ const projectCtx = phrenCtx ? loadProjectContext(phrenCtx) : null;
466
+ if (phrenCtx && projectCtx)
467
+ 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());
472
+ const lintTestConfig = detectLintTest();
473
+ agentConfig.mode = "agent";
474
+ agentConfig.rebuildSystemPrompt = undefined;
475
+ agentConfig.systemPrompt = systemPrompt;
476
+ agentConfig.lintTestConfig = lintTestConfig;
477
+ }
478
+ catch (err) {
479
+ for (const name of registry.toolNames())
480
+ if (!before.has(name))
481
+ registry.remove(name);
482
+ mcpCleanup?.();
483
+ mcpCleanup = undefined;
484
+ throw err;
485
+ }
486
+ return `Promoted to a phren agent with ${registry.toolNames().length} tools; the conversation continues.`;
487
+ };
488
+ }
412
489
  // Interactive mode — Ink TUI with built-in spawner (--multi and --team also route here)
413
490
  if (args.interactive || args.multi || args.team) {
414
491
  const isTTY = process.stdout.isTTY && process.stdin.isTTY;
@@ -419,7 +496,7 @@ export async function runAgentCli(raw) {
419
496
  else {
420
497
  // The phren splash (mascot + wordmark reveal) before the TUI mounts.
421
498
  // Cosmetic only: any failure is swallowed, and PHREN_INTRO=off skips it.
422
- if (process.env.PHREN_INTRO !== "off") {
499
+ if (process.env.PHREN_INTRO !== "off" && !chat) {
423
500
  try {
424
501
  const { playSplash } = await import("@phren/cli/shell/intro");
425
502
  const model = provider.model;
@@ -437,10 +514,14 @@ export async function runAgentCli(raw) {
437
514
  // Ink TUI with spawner — LLM can spawn agents via spawn_agent tool
438
515
  const { AgentSpawner } = await import("./multi/spawner.js");
439
516
  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));
517
+ const spawner = new AgentSpawner({ costTracker, getPermissionDefaults: () => registry.permissionConfig, getParentProvider: () => agentConfig.provider });
518
+ registerSpawnerTools = () => {
519
+ registry.register(createSpawnAgentTool(spawner, () => registry.permissionConfig));
520
+ registry.register(createSendMessageTool(spawner));
521
+ registry.register(createListAgentsTool(spawner));
522
+ };
523
+ if (!chat)
524
+ registerSpawnerTools();
444
525
  // Publish this process's agents so a phren graph in another terminal can
445
526
  // show them. Best-effort and silent: it is a courtesy to another tool.
446
527
  const { createAgentPublisher } = await import("./multi/publish.js");
@@ -457,8 +538,9 @@ export async function runAgentCli(raw) {
457
538
  }
458
539
  await spawner.shutdown();
459
540
  }
460
- // Flush anti-patterns at session end
461
- if (phrenCtx) {
541
+ // Flush anti-patterns at session end. A chat that stayed one ran no
542
+ // tools and gets no reflection call.
543
+ if (phrenCtx && agentConfig.mode !== "chat") {
462
544
  try {
463
545
  await session.antiPatterns.flushAntiPatterns(phrenCtx, sessionId);
464
546
  }
@@ -484,7 +566,7 @@ export async function runAgentCli(raw) {
484
566
  return;
485
567
  }
486
568
  // Create initial checkpoint before agent starts
487
- const initCheckpoint = createCheckpoint(cwd, "pre-agent");
569
+ const initCheckpoint = chat ? null : createCheckpoint(cwd, "pre-agent");
488
570
  if (args.verbose && initCheckpoint) {
489
571
  process.stderr.write(`Checkpoint: ${initCheckpoint.slice(0, 8)}\n`);
490
572
  }
@@ -508,10 +590,10 @@ export async function runAgentCli(raw) {
508
590
  // children run headless with auto-confirm permissions and exit when the
509
591
  // parent's IPC channel closes.
510
592
  let oneShotSpawner;
511
- if (!args.noSubagents) {
593
+ if (!args.noSubagents && !chat) {
512
594
  const { AgentSpawner } = await import("./multi/spawner.js");
513
595
  const { createSpawnAgentTool, createSendMessageTool, createListAgentsTool } = await import("./tools/spawn-agent.js");
514
- oneShotSpawner = new AgentSpawner({ costTracker, getPermissionDefaults: () => registry.permissionConfig });
596
+ oneShotSpawner = new AgentSpawner({ costTracker, getPermissionDefaults: () => registry.permissionConfig, getParentProvider: () => agentConfig.provider });
515
597
  registry.register(createSpawnAgentTool(oneShotSpawner, () => registry.permissionConfig));
516
598
  registry.register(createSendMessageTool(oneShotSpawner));
517
599
  registry.register(createListAgentsTool(oneShotSpawner));
@@ -595,17 +677,19 @@ export async function runAgentCli(raw) {
595
677
  endSession(phrenCtx, sessionId, summary);
596
678
  // Save messages for resume
597
679
  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 });
680
+ if (!chat) {
681
+ // Flush anti-patterns (interactive mode does this too; one-shot was missing it)
682
+ try {
683
+ await result.session.antiPatterns.flushAntiPatterns(phrenCtx, sessionId);
684
+ }
685
+ catch { /* best effort */ }
686
+ // Evolve project context via lightweight LLM reflection (also routes
687
+ // extracted knowledge through the graduated confidence pipeline)
688
+ try {
689
+ await evolveProjectContext(phrenCtx, provider, result.messages, { sessionId });
690
+ }
691
+ catch { /* best effort */ }
607
692
  }
608
- catch { /* best effort */ }
609
693
  // Mirror the session into a searchable (non-injectable) note
610
694
  writeSessionNote(phrenCtx, { sessionId, task: args.task, outcome: result.finalText });
611
695
  }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Quick chat: the system prompt for `--mode chat`. No tools, so everything the
3
+ * model knows from phren is read up front, from files only (no index build,
4
+ * no search), to keep the first answer about a second away.
5
+ */
6
+ import * as fs from "fs";
7
+ import { storeAwareProjectPath } from "@phren/cli/store-routing";
8
+ import { readFindings } from "@phren/cli/data/access";
9
+ import { readTruths } from "./context.js";
10
+ /** Budget for the whole memory section; a chat prompt stays small. */
11
+ export const CHAT_MEMORY_MAX_CHARS = 12_000;
12
+ const RECENT_FINDINGS = 8;
13
+ function readSummary(ctx, project) {
14
+ try {
15
+ const file = storeAwareProjectPath(ctx.phrenPath, project, "summary.md");
16
+ if (!file || !fs.existsSync(file))
17
+ return "";
18
+ // The archive block's markers are for the summarizer, not the model.
19
+ return fs.readFileSync(file, "utf-8").replace(/<!--[\s\S]*?-->\n?/g, "").trim();
20
+ }
21
+ catch {
22
+ return "";
23
+ }
24
+ }
25
+ /** Read-only phren memory for a quick chat: truths, the project summary and its newest findings. */
26
+ export function buildChatMemory(ctx) {
27
+ if (!ctx)
28
+ return "";
29
+ const sections = [];
30
+ const global = readTruths(ctx.phrenPath, "global");
31
+ if (global.length > 0)
32
+ sections.push(`## Pinned truths (global)\n\n${global.join("\n")}`);
33
+ if (ctx.project && ctx.project !== "global") {
34
+ const truths = readTruths(ctx.phrenPath, ctx.project);
35
+ if (truths.length > 0)
36
+ sections.push(`## Pinned truths (${ctx.project})\n\n${truths.join("\n")}`);
37
+ const summary = readSummary(ctx, ctx.project);
38
+ if (summary)
39
+ sections.push(`## Project summary (${ctx.project})\n\n${summary}`);
40
+ try {
41
+ const result = readFindings(ctx.phrenPath, ctx.project);
42
+ if (result.ok && result.data) {
43
+ const recent = result.data
44
+ .filter((f) => f.status === "active" && f.tier !== "archived")
45
+ .slice(-RECENT_FINDINGS)
46
+ .map((f) => `- ${f.text}`);
47
+ if (recent.length > 0)
48
+ sections.push(`## Recent findings (${ctx.project})\n\n${recent.join("\n")}`);
49
+ }
50
+ }
51
+ catch { /* silent */ }
52
+ }
53
+ let memory = sections.join("\n\n");
54
+ if (memory.length > CHAT_MEMORY_MAX_CHARS)
55
+ memory = `${memory.slice(0, CHAT_MEMORY_MAX_CHARS)}\n\n[memory truncated]`;
56
+ return memory;
57
+ }
58
+ export function buildChatSystemPrompt(memory, providerInfo) {
59
+ const modelNote = providerInfo ? ` You are running on ${providerInfo.name}${providerInfo.model ? ` (model: ${providerInfo.model})` : ""}.` : "";
60
+ const parts = [
61
+ `You are phren, in quick chat with the owner.${modelNote}`,
62
+ "",
63
+ "Answer directly and conversationally, like a chat assistant. Lead with the answer; keep it short unless asked for depth. Replies may be read aloud, so prefer plain sentences over tables and long code.",
64
+ "",
65
+ "You have no tools in this chat: you cannot read files, run commands, search the web or change phren memory. What phren remembers is below. If a request needs tools, say so in one line and suggest /promote, which continues this conversation as a phren agent with tools.",
66
+ ];
67
+ if (memory)
68
+ parts.push("", "# What phren remembers (read-only)", "", memory);
69
+ return parts.join("\n");
70
+ }
@@ -36,7 +36,7 @@ export async function buildPhrenContext(projectOverride) {
36
36
  }
37
37
  }
38
38
  /** Read truths.md pinned entries for a project. */
39
- function readTruths(phrenPath, project) {
39
+ export function readTruths(phrenPath, project) {
40
40
  try {
41
41
  // Store-aware: upsertCanonical writes via storeAwareProjectPath, so team-store
42
42
  // truths live under the store root, not necessarily <phrenPath>/<project>/.
@@ -0,0 +1,17 @@
1
+ let scoped;
2
+ /** Pin the overrides to `model`, or clear them when none are set. */
3
+ export function scopeModelOverrides(model, overrides) {
4
+ const set = Object.values(overrides).some((v) => v !== undefined);
5
+ scoped = model && set ? { model, ...overrides } : undefined;
6
+ }
7
+ /** The overrides that apply to `model`; none for any other model. */
8
+ export function overridesFor(model) {
9
+ if (!scoped || model !== scoped.model)
10
+ return {};
11
+ const { model: _model, ...overrides } = scoped;
12
+ return overrides;
13
+ }
14
+ /** The current scope, for a subagent's spawn payload. */
15
+ export function scopedModelOverrides() {
16
+ return scoped ? { ...scoped } : undefined;
17
+ }