@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
@@ -4,6 +4,7 @@ import { createSession, runTurn } from "../agent-loop.js";
4
4
  import { emitHerdrHook, setHerdrHookSession } from "../herdr-hooks.js";
5
5
  import { useSlashCommands } from "./hooks/useSlashCommands.js";
6
6
  import { resolveSkillGesture, resolveCustomCommand } from "../commands.js";
7
+ import { isMcpPromptCommand, resolveMcpPromptCommand } from "../mcp-prompts.js";
7
8
  import { decodeDiffPayload, DIFF_MARKER, renderInlineDiff } from "../multi/diff-renderer.js";
8
9
  import { formatToolInput } from "./tool-render.js";
9
10
  import * as os from "os";
@@ -11,7 +12,7 @@ import * as fs from "node:fs";
11
12
  import { execSync } from "node:child_process";
12
13
  import * as path from "node:path";
13
14
  import { loadInputMode, saveInputMode, savePermissionMode, loadTheme, saveTheme, loadInputHistory, saveInputHistory } from "../settings.js";
14
- import { estimateMessageTokens } from "../context/token-counter.js";
15
+ import { contextTokens } from "../context/usage.js";
15
16
  import { READ_ONLY_TOOLS } from "../permissions/checker.js";
16
17
  import { nextPermissionMode } from "./ansi.js";
17
18
  import { App } from "./components/App.js";
@@ -152,6 +153,9 @@ export async function startInkTui(config, spawner) {
152
153
  const completedMessages = [];
153
154
  let streamingText = "";
154
155
  let reasoningText = "";
156
+ // Length of streamingText when the current model call began, so a retried
157
+ // call can drop only its own partial text.
158
+ let streamMark = 0;
155
159
  let thinking = false;
156
160
  let thinkStartTime = 0;
157
161
  let thinkElapsed = null;
@@ -159,6 +163,8 @@ export async function startInkTui(config, spawner) {
159
163
  let activeTool = null;
160
164
  let modelPicker = null;
161
165
  let modelPickerResolve = null;
166
+ let listPicker = null;
167
+ let listPickerResolve = null;
162
168
  const toolHistory = [];
163
169
  let toolDetailIndex = null;
164
170
  let planReview = null;
@@ -171,7 +177,7 @@ export async function startInkTui(config, spawner) {
171
177
  const cost = tracker
172
178
  ? tracker.metered
173
179
  ? `$${tracker.totalCost < 0.01 ? tracker.totalCost.toFixed(4) : tracker.totalCost.toFixed(2)}`
174
- : `${tracker.totalInputTokens + tracker.totalOutputTokens} tok`
180
+ : `${tracker.totalInputTokens + tracker.totalCacheReadTokens + tracker.totalOutputTokens} tok`
175
181
  : "";
176
182
  return {
177
183
  provider: config.provider.name,
@@ -185,13 +191,18 @@ export async function startInkTui(config, spawner) {
185
191
  contextWindow: contextLimit,
186
192
  contextTokens: currentContextTokens(),
187
193
  reasoningEffort: config.provider.reasoningEffort,
194
+ chat: config.mode === "chat",
188
195
  };
189
196
  }
190
- let contextMemo = { count: -1, tokens: 0 };
197
+ let contextMemo = { count: -1, logLength: -1, tokens: 0 };
191
198
  function currentContextTokens() {
192
199
  const count = session.messages.length;
193
- if (contextMemo.count !== count) {
194
- contextMemo = { count, tokens: estimateMessageTokens(session.messages) };
200
+ if (contextMemo.count !== count || contextMemo.logLength !== session.log.length) {
201
+ contextMemo = {
202
+ count,
203
+ logLength: session.log.length,
204
+ tokens: contextTokens(config.systemPrompt, session.messages, session.log, session.reportedContext),
205
+ };
195
206
  }
196
207
  return contextMemo.tokens;
197
208
  }
@@ -224,7 +235,27 @@ export async function startInkTui(config, spawner) {
224
235
  const displayActiveTool = agentConvo ? agentConvo.activeTool : activeTool;
225
236
  const displayThinking = agentConvo ? false : thinking;
226
237
  const displayRunning = agentConvo ? (spawner?.getAgent(selectedAgentId)?.status === "running" || false) : running;
227
- rerender(_jsx(App, { state: getAppState(), completedMessages: displayMessages, streamingText: displayStreaming, reasoningText: agentConvo ? "" : reasoningText, completedToolCalls: displayToolCalls, activeTool: displayActiveTool, thinking: displayThinking, thinkStartTime: thinkStartTime, thinkElapsed: agentConvo ? null : thinkElapsed, steerQueue: agentConvo ? [] : [...steerQueueBuf], running: displayRunning, showBanner: !selectedAgentId, inputHistory: [...inputHistory], verbose: verbose, theme: theme, onSubmit: handleSubmit, onPermissionCycle: handlePermissionCycle, onCancelTurn: handleCancelTurn, onExit: handleExit, agents: agentTabs.length > 0 ? [{ id: "__main__", name: "phren", status: running ? "running" : "idle", color: "magentaBright" }, ...agentTabs] : undefined, selectedAgentId: selectedAgentId ?? (agentTabs.length > 0 ? "__main__" : undefined), onCancelAgent: handleCancelAgent, onSelectAgent: (id) => handleSelectAgent(id === "__main__" ? null : id), approval: approvalInfo, modelPicker: modelPicker, onModelPickerMove: moveModelPicker, onModelPickerReasoning: adjustModelReasoning, onModelPickerSelect: selectModelPicker, onModelPickerCancel: () => closeModelPicker(null), onInspectTool: openToolDetail, toolDetail: toolDetailIndex !== null ? { call: toolHistory[toolDetailIndex], index: toolDetailIndex, total: toolHistory.length } : null, onToolDetailMove: moveToolDetail, onToolDetailClose: closeToolDetail, planReview: planReview }));
238
+ rerender(_jsx(App, { state: getAppState(), completedMessages: displayMessages, streamingText: displayStreaming, reasoningText: agentConvo ? "" : reasoningText, completedToolCalls: displayToolCalls, activeTool: displayActiveTool, thinking: displayThinking, thinkStartTime: thinkStartTime, thinkElapsed: agentConvo ? null : thinkElapsed, steerQueue: agentConvo ? [] : [...steerQueueBuf], running: displayRunning, showBanner: !selectedAgentId, inputHistory: [...inputHistory], verbose: verbose, theme: theme, onSubmit: handleSubmit, onPermissionCycle: handlePermissionCycle, onCancelTurn: handleCancelTurn, onExit: handleExit, agents: agentTabs.length > 0 ? [{ id: "__main__", name: "phren", status: running ? "running" : "idle", color: "magentaBright" }, ...agentTabs] : undefined, selectedAgentId: selectedAgentId ?? (agentTabs.length > 0 ? "__main__" : undefined), onCancelAgent: handleCancelAgent, onSelectAgent: (id) => handleSelectAgent(id === "__main__" ? null : id), approval: approvalInfo, modelPicker: modelPicker, listPicker: listPicker, onListPickerMove: (delta) => {
239
+ if (!listPicker)
240
+ return;
241
+ const count = listPicker.items.length;
242
+ listPicker = { ...listPicker, cursor: (listPicker.cursor + delta + count) % count };
243
+ update();
244
+ }, onListPickerSelect: () => closeListPicker(listPicker?.cursor ?? null), onListPickerCancel: () => closeListPicker(null), onModelPickerMove: moveModelPicker, onModelPickerReasoning: adjustModelReasoning, onModelPickerSelect: selectModelPicker, onModelPickerCancel: () => closeModelPicker(null), onInspectTool: openToolDetail, toolDetail: toolDetailIndex !== null ? { call: toolHistory[toolDetailIndex], index: toolDetailIndex, total: toolHistory.length } : null, onToolDetailMove: moveToolDetail, onToolDetailClose: closeToolDetail, planReview: planReview }));
245
+ }
246
+ function openListPicker(title, items) {
247
+ if (items.length === 0)
248
+ return Promise.resolve(null);
249
+ listPicker = { title, items, cursor: 0 };
250
+ update();
251
+ return new Promise((resolve) => { listPickerResolve = resolve; });
252
+ }
253
+ function closeListPicker(index) {
254
+ listPicker = null;
255
+ const resolve = listPickerResolve;
256
+ listPickerResolve = null;
257
+ update();
258
+ resolve?.(index);
228
259
  }
229
260
  function openModelPicker() {
230
261
  const providerName = config.provider.name;
@@ -365,17 +396,22 @@ export async function startInkTui(config, spawner) {
365
396
  }
366
397
  },
367
398
  onModelChange: async (result) => {
368
- try {
369
- const { resolveProvider } = await import("../providers/resolve.js");
370
- const newProvider = resolveProvider(config.provider.name, result.model, undefined, result.reasoning ?? undefined);
371
- config.provider = newProvider;
372
- const { buildSystemPrompt } = await import("../system-prompt.js");
373
- config.systemPrompt = buildSystemPrompt(config.systemPrompt.split("\n## Last session")[0], null, { name: newProvider.name, model: result.model });
374
- update();
375
- }
376
- catch { /* keep current provider */ }
399
+ // A failure (no key for that provider, an unknown name) is reported
400
+ // by the command; the current provider stays.
401
+ const { resolveProvider } = await import("../providers/resolve.js");
402
+ const newProvider = resolveProvider(result.provider ?? config.provider.name, result.model || undefined, undefined, result.reasoning ?? undefined);
403
+ config.provider = newProvider;
404
+ config.costTracker?.reprice(newProvider.model ?? newProvider.name, newProvider.name, newProvider.baseUrl);
405
+ const { buildSystemPrompt } = await import("../system-prompt.js");
406
+ config.systemPrompt = config.rebuildSystemPrompt
407
+ ? config.rebuildSystemPrompt({ name: newProvider.name, model: newProvider.model })
408
+ : buildSystemPrompt(config.systemPrompt.split("\n## Last session")[0], null, { name: newProvider.name, model: newProvider.model });
409
+ update();
410
+ return newProvider;
377
411
  },
378
412
  pickModel: openModelPicker,
413
+ pickFromList: openListPicker,
414
+ promote: config.promote,
379
415
  },
380
416
  onOutput: (text) => {
381
417
  completedMessages.push({ id: nextId(), kind: "status", text });
@@ -547,6 +583,17 @@ export async function startInkTui(config, spawner) {
547
583
  update();
548
584
  return;
549
585
  }
586
+ // An MCP prompt: fetch it from its server, then send what it says.
587
+ if (isMcpPromptCommand(line)) {
588
+ const command = line.split(/\s+/)[0];
589
+ completedMessages.push({ id: nextId(), kind: "status", text: `↳ fetching MCP prompt ${command}` });
590
+ update();
591
+ resolveMcpPromptCommand(line).then((task) => handleSubmit(task.startsWith("/") ? ` ${task}` : task), (err) => {
592
+ completedMessages.push({ id: nextId(), kind: "status", text: err instanceof Error ? err.message : String(err) });
593
+ update();
594
+ });
595
+ return;
596
+ }
550
597
  // Slash commands — capture stderr output and display as status message
551
598
  if (line.startsWith("/")) {
552
599
  // /skill-name gesture: rewrite into a run_skill task and fall through
@@ -612,6 +659,14 @@ export async function startInkTui(config, spawner) {
612
659
  onTextDone: () => {
613
660
  // streaming complete — finalized in runAgentTurn
614
661
  },
662
+ onAssistantMessage: () => {
663
+ streamMark = streamingText.length;
664
+ },
665
+ onStreamRetry: () => {
666
+ streamingText = streamingText.slice(0, streamMark);
667
+ reasoningText = "";
668
+ scheduleUpdate();
669
+ },
615
670
  onTextBlock: (text) => {
616
671
  thinking = false;
617
672
  streamingText += text;
@@ -664,6 +719,7 @@ export async function startInkTui(config, spawner) {
664
719
  thinkElapsed = null;
665
720
  streamingText = "";
666
721
  reasoningText = "";
722
+ streamMark = 0;
667
723
  currentToolCalls = [];
668
724
  activeTool = null;
669
725
  const pastVerb = PAST_VERBS[Math.floor(Math.random() * PAST_VERBS.length)];
@@ -695,6 +751,7 @@ export async function startInkTui(config, spawner) {
695
751
  }
696
752
  streamingText = "";
697
753
  reasoningText = "";
754
+ streamMark = 0;
698
755
  currentToolCalls = [];
699
756
  activeTool = null;
700
757
  running = false;
@@ -783,6 +840,13 @@ export async function startInkTui(config, spawner) {
783
840
  if (selectedAgentId === agentId)
784
841
  update();
785
842
  });
843
+ spawner.on("stream_retry", (agentId, discard) => {
844
+ // The agent's model call is being retried: drop the abandoned attempt's text.
845
+ const convo = getOrCreateConvo(agentId);
846
+ convo.streamingText = convo.streamingText.slice(0, Math.max(0, convo.streamingText.length - discard));
847
+ if (selectedAgentId === agentId)
848
+ update();
849
+ });
786
850
  spawner.on("text_block", (agentId, text) => {
787
851
  const convo = getOrCreateConvo(agentId);
788
852
  convo.streamingText += text;
@@ -7,7 +7,11 @@ export const HOOK_EVENT_NAMES = [
7
7
  "PostToolUse",
8
8
  "UserPromptSubmit",
9
9
  "Stop",
10
+ "SessionStart",
11
+ "PreCompact",
10
12
  ];
13
+ /** Exit code that blocks, as in Claude Code. */
14
+ export const BLOCKING_EXIT_CODE = 2;
11
15
  const DEFAULT_TIMEOUT_MS = 10_000;
12
16
  const MAX_OUTPUT_CHARS = 16_384;
13
17
  function isHookCommand(value) {
@@ -144,10 +148,15 @@ export async function runPreToolUseHooks(config, toolName, input, options = {})
144
148
  }
145
149
  return { denied: false, message: "" };
146
150
  }
151
+ /**
152
+ * PostToolUse hooks run after the tool; one that exits 2 sends its stderr back
153
+ * to the model with the tool's result (a formatter or linter complaining).
154
+ * Returns that feedback, or "".
155
+ */
147
156
  export async function runPostToolUseHooks(config, toolName, input, output, isError, options = {}) {
148
157
  const hooks = (config?.PostToolUse ?? []).filter((hook) => matchesTool(hook.matcher, toolName));
149
158
  if (hooks.length === 0)
150
- return;
159
+ return "";
151
160
  const payload = {
152
161
  hook_event_name: "PostToolUse",
153
162
  tool_name: toolName,
@@ -156,16 +165,29 @@ export async function runPostToolUseHooks(config, toolName, input, output, isErr
156
165
  is_error: isError,
157
166
  cwd: options.cwd ?? process.cwd(),
158
167
  };
168
+ const feedback = [];
159
169
  for (const hook of hooks) {
160
- await runHook(hook, payload, options);
170
+ const result = await runHook(hook, payload, options);
171
+ if (result.exitCode === BLOCKING_EXIT_CODE && result.stderr.trim())
172
+ feedback.push(result.stderr.trim());
161
173
  }
174
+ return feedback.join("\n");
162
175
  }
163
176
  export async function runLifecycleHooks(config, event, payload = {}, options = {}) {
164
177
  const hooks = config?.[event] ?? [];
178
+ const outcome = { blocked: false, reason: "", context: "" };
165
179
  if (hooks.length === 0)
166
- return;
180
+ return outcome;
167
181
  const body = { hook_event_name: event, ...payload, cwd: options.cwd ?? process.cwd() };
182
+ const context = [];
168
183
  for (const hook of hooks) {
169
- await runHook(hook, body, options);
184
+ const result = await runHook(hook, body, options);
185
+ if (result.exitCode === BLOCKING_EXIT_CODE) {
186
+ return { blocked: true, reason: result.stderr.trim() || `Blocked by ${event} hook: ${hook.command}`, context: context.join("\n") };
187
+ }
188
+ if (result.exitCode === 0 && result.stdout.trim())
189
+ context.push(result.stdout.trim());
170
190
  }
191
+ outcome.context = context.join("\n");
192
+ return outcome;
171
193
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/agent",
3
- "version": "0.3.19",
3
+ "version": "0.3.21",
4
4
  "description": "phren's coding agent: starts every session knowing your project's memory, tasks and decisions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -15,9 +15,10 @@
15
15
  ],
16
16
  "dependencies": {
17
17
  "@modelcontextprotocol/sdk": "^1.30.1",
18
+ "ajv": "^8.20.0",
18
19
  "ink": "^7.1.1",
19
20
  "react": "^19.3.0",
20
- "@phren/cli": "0.3.19"
21
+ "@phren/cli": "0.3.21"
21
22
  },
22
23
  "engines": {
23
24
  "node": ">=20.0.0"
@@ -1,24 +0,0 @@
1
- import { estimateTokens, estimateMessageTokens } from "../context/token-counter.js";
2
- export function createFlushConfig(contextLimit) {
3
- return { contextLimit, triggered: false };
4
- }
5
- const FLUSH_PROMPT = "Before continuing, briefly summarize the key decisions, patterns, and discoveries from this conversation so far. " +
6
- "Focus on non-obvious findings that would be valuable to remember in future sessions. " +
7
- "Be concise — 3-5 bullet points maximum.";
8
- /**
9
- * Check if a context flush should be injected.
10
- * Returns the flush message to inject, or null if not needed.
11
- * Only triggers once per session.
12
- */
13
- export function checkFlushNeeded(systemPrompt, messages, config) {
14
- if (config.triggered)
15
- return null;
16
- const systemTokens = estimateTokens(systemPrompt);
17
- const msgTokens = estimateMessageTokens(messages);
18
- const usage = (systemTokens + msgTokens) / config.contextLimit;
19
- if (usage >= 0.75) {
20
- config.triggered = true;
21
- return FLUSH_PROMPT;
22
- }
23
- return null;
24
- }