@phren/agent 0.1.15 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +86 -0
  2. package/dist/agent-loop/index.js +239 -65
  3. package/dist/agent-loop/stream.js +212 -29
  4. package/dist/agent-loop/types.js +15 -2
  5. package/dist/checkpoint.js +103 -22
  6. package/dist/commands/info.js +30 -15
  7. package/dist/commands/model.js +6 -2
  8. package/dist/commands/review.js +183 -0
  9. package/dist/commands/session.js +70 -7
  10. package/dist/commands.js +168 -12
  11. package/dist/config.js +87 -10
  12. package/dist/context/compactor.js +239 -0
  13. package/dist/context/pruner.js +39 -13
  14. package/dist/context/token-counter.js +33 -1
  15. package/dist/custom-commands.js +69 -0
  16. package/dist/guards/repeat-tool-reminder.js +75 -0
  17. package/dist/headless.js +115 -0
  18. package/dist/herdr-hooks.js +71 -0
  19. package/dist/index.js +351 -48
  20. package/dist/mcp-client.js +434 -73
  21. package/dist/mcp-oauth.js +121 -0
  22. package/dist/memory/anti-patterns.js +7 -3
  23. package/dist/memory/auto-capture.js +7 -3
  24. package/dist/memory/context.js +92 -73
  25. package/dist/memory/project-context.js +24 -5
  26. package/dist/memory/provenance.js +15 -0
  27. package/dist/memory/review-triage.js +166 -0
  28. package/dist/memory/session.js +36 -1
  29. package/dist/models.js +152 -19
  30. package/dist/multi/child-entry.js +65 -10
  31. package/dist/multi/diff-renderer.js +3 -3
  32. package/dist/multi/markdown.js +125 -27
  33. package/dist/multi/provider-manager.js +8 -0
  34. package/dist/multi/publish.js +72 -0
  35. package/dist/multi/spawner.js +45 -4
  36. package/dist/multi/syntax-highlight.js +25 -4
  37. package/dist/multi/types.js +1 -1
  38. package/dist/permissions/allowlist.js +86 -13
  39. package/dist/permissions/checker.js +42 -7
  40. package/dist/permissions/kernel-sandbox.js +197 -0
  41. package/dist/permissions/prompt.js +10 -1
  42. package/dist/permissions/sandbox.js +40 -17
  43. package/dist/providers/anthropic.js +154 -7
  44. package/dist/providers/codex-auth.js +28 -0
  45. package/dist/providers/codex.js +134 -23
  46. package/dist/providers/history.js +35 -0
  47. package/dist/providers/ollama.js +37 -6
  48. package/dist/providers/openai-compat.js +171 -74
  49. package/dist/providers/openrouter.js +47 -17
  50. package/dist/providers/replay.js +62 -0
  51. package/dist/providers/resolve.js +41 -7
  52. package/dist/providers/retry.js +38 -5
  53. package/dist/providers/types.js +9 -1
  54. package/dist/repl.js +47 -5
  55. package/dist/session/log.js +217 -0
  56. package/dist/session/persist.js +190 -0
  57. package/dist/settings.js +42 -26
  58. package/dist/system-prompt.js +18 -2
  59. package/dist/tools/apply-patch.js +355 -0
  60. package/dist/tools/edit-engine.js +287 -0
  61. package/dist/tools/edit-file.js +86 -27
  62. package/dist/tools/grep.js +25 -10
  63. package/dist/tools/lint-test.js +0 -22
  64. package/dist/tools/mcp-resources.js +51 -6
  65. package/dist/tools/phren-finding.js +12 -4
  66. package/dist/tools/phren-search.js +7 -2
  67. package/dist/tools/read-file.js +37 -9
  68. package/dist/tools/read-image.js +76 -0
  69. package/dist/tools/registry.js +27 -5
  70. package/dist/tools/shell.js +134 -71
  71. package/dist/tools/skill.js +20 -20
  72. package/dist/tools/spawn-agent.js +77 -13
  73. package/dist/tools/update-plan.js +48 -0
  74. package/dist/tools/web-fetch.js +110 -12
  75. package/dist/tools/web-search.js +4 -4
  76. package/dist/tui/components/App.js +98 -26
  77. package/dist/tui/components/ApprovalPanel.js +8 -0
  78. package/dist/tui/components/InputArea.js +5 -5
  79. package/dist/tui/components/ModelPicker.js +43 -0
  80. package/dist/tui/components/PhrenInput.js +10 -5
  81. package/dist/tui/components/PlanReview.js +7 -0
  82. package/dist/tui/components/ShortcutHelp.js +5 -0
  83. package/dist/tui/components/StatusBar.js +46 -20
  84. package/dist/tui/components/SteerQueue.js +1 -1
  85. package/dist/tui/components/ThinkingIndicator.js +6 -4
  86. package/dist/tui/components/ToolCall.js +10 -4
  87. package/dist/tui/components/ToolDetail.js +21 -0
  88. package/dist/tui/help.js +6 -0
  89. package/dist/tui/hooks/useKeyboardShortcuts.js +15 -1
  90. package/dist/tui/index.js +0 -1
  91. package/dist/tui/ink-entry.js +317 -33
  92. package/dist/tui/tool-render.js +1 -1
  93. package/dist/user-hooks.js +171 -0
  94. package/package.json +14 -8
  95. package/dist/multi/multi-commands.js +0 -170
  96. package/dist/multi/multi-events.js +0 -98
  97. package/dist/multi/multi-render.js +0 -147
  98. package/dist/multi/pane.js +0 -28
  99. package/dist/multi/tui-multi.js +0 -200
  100. package/dist/permissions/privacy.js +0 -248
  101. package/dist/tui/components/AgentMessage.js +0 -5
  102. package/dist/tui/components/ChatMessage.js +0 -23
  103. package/dist/tui/components/CodeBlock.js +0 -8
  104. package/dist/tui/components/Separator.js +0 -7
  105. package/dist/tui/components/StreamingText.js +0 -5
  106. package/dist/tui/components/UserMessage.js +0 -5
  107. package/dist/tui/menu-mode.js +0 -86
  108. package/dist/tui/mouse.js +0 -71
  109. package/dist/tui/terminal-control.js +0 -62
  110. package/dist/tui.js +0 -781
@@ -1,75 +1,200 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { render } from "ink";
3
3
  import { createSession, runTurn } from "../agent-loop.js";
4
+ import { emitHerdrHook, setHerdrHookSession } from "../herdr-hooks.js";
4
5
  import { useSlashCommands } from "./hooks/useSlashCommands.js";
6
+ import { resolveSkillGesture, resolveCustomCommand } from "../commands.js";
5
7
  import { decodeDiffPayload, DIFF_MARKER, renderInlineDiff } from "../multi/diff-renderer.js";
6
8
  import { formatToolInput } from "./tool-render.js";
7
9
  import * as os from "os";
10
+ import * as fs from "node:fs";
8
11
  import { execSync } from "node:child_process";
9
12
  import * as path from "node:path";
10
- import { loadInputMode, saveInputMode, savePermissionMode } from "../settings.js";
13
+ import { loadInputMode, saveInputMode, savePermissionMode, loadTheme, saveTheme, loadInputHistory, saveInputHistory } from "../settings.js";
14
+ import { estimateMessageTokens } from "../context/token-counter.js";
15
+ import { READ_ONLY_TOOLS } from "../permissions/checker.js";
11
16
  import { nextPermissionMode } from "./ansi.js";
12
17
  import { App } from "./components/App.js";
13
18
  import { createRequire } from "node:module";
19
+ import { randomUUID } from "node:crypto";
20
+ import { persistFork } from "../session/persist.js";
14
21
  import { getTheme, THEME_NAMES } from "./themes.js";
22
+ import { getAvailableModels } from "../multi/model-picker.js";
23
+ import { REASONING_LEVELS } from "../models.js";
15
24
  const _require = createRequire(import.meta.url);
16
25
  const AGENT_VERSION = _require("../../package.json").version;
17
26
  export async function startInkTui(config, spawner) {
18
27
  const contextLimit = config.provider.contextWindow ?? 200_000;
19
- const session = createSession(contextLimit);
28
+ const session = createSession(contextLimit, { log: config.sessionLog });
20
29
  const startTime = Date.now();
21
30
  let inputMode = loadInputMode();
22
31
  let pendingInput = null;
23
32
  const steerQueueBuf = [];
24
- const inputHistory = [];
33
+ const inputHistory = loadInputHistory();
25
34
  let running = false;
26
35
  let verbose = false;
27
- let theme = getTheme();
36
+ let theme = getTheme(loadTheme());
28
37
  let msgCounter = 0;
29
38
  // Autopilot (full-auto) requires --yolo flag to be cycleable via Shift+Tab
30
39
  const yoloEnabled = config.registry.permissionConfig.mode === "full-auto";
31
40
  const permissionQueue = [];
32
- // Ink-compatible askUser: shows prompt in chat, queues for y/n in input
41
+ let approvalInfo = null;
42
+ const PERMISSION_TIMEOUT_MS = (() => {
43
+ const raw = Number(process.env.PHREN_PERMISSION_TIMEOUT_MS);
44
+ return Number.isFinite(raw) && raw > 0 ? raw : 600_000;
45
+ })();
46
+ const READ_TOOLS = READ_ONLY_TOOLS;
47
+ function capLines(text, max) {
48
+ const lines = text.split("\n");
49
+ return lines.length > max ? lines.slice(0, max).join("\n") + "\n\u2026" : text;
50
+ }
51
+ function renderDiffCapped(oldContent, newContent, filePath) {
52
+ const limit = 2_000;
53
+ const cap = (content) => {
54
+ const lines = content.split("\n");
55
+ return lines.length > limit ? lines.slice(0, limit).join("\n") + `\n\u2026 (${lines.length - limit} more lines)` : content;
56
+ };
57
+ const width = Math.max(40, (process.stdout.columns || 80) - 6);
58
+ return renderInlineDiff(cap(oldContent), cap(newContent), filePath, theme.diff, width);
59
+ }
60
+ function previewDiff(toolName, input) {
61
+ const filePath = input.path;
62
+ if (typeof filePath !== "string" || !filePath)
63
+ return undefined;
64
+ const abs = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
65
+ let oldContent = "";
66
+ try {
67
+ const stat = fs.statSync(abs);
68
+ if (stat.size > 300_000)
69
+ return "(file too large to preview)";
70
+ oldContent = fs.readFileSync(abs, "utf-8");
71
+ }
72
+ catch {
73
+ oldContent = "";
74
+ }
75
+ let newContent;
76
+ if (toolName === "write_file") {
77
+ newContent = input.content ?? "";
78
+ }
79
+ else if (toolName === "edit_file") {
80
+ const oldString = input.old_string ?? "";
81
+ const newString = input.new_string ?? "";
82
+ if (!oldString)
83
+ return undefined;
84
+ if (input.replace_all === true)
85
+ newContent = oldContent.split(oldString).join(newString);
86
+ else {
87
+ const idx = oldContent.indexOf(oldString);
88
+ if (idx < 0)
89
+ return "(old_string not found in the current file)";
90
+ newContent = oldContent.slice(0, idx) + newString + oldContent.slice(idx + oldString.length);
91
+ }
92
+ }
93
+ if (newContent === undefined)
94
+ return undefined;
95
+ if (oldContent.split("\n").length > 3_000 || newContent.split("\n").length > 3_000)
96
+ return "(diff too large to preview)";
97
+ try {
98
+ return capLines(renderDiffCapped(oldContent, newContent, abs), 24);
99
+ }
100
+ catch {
101
+ return undefined;
102
+ }
103
+ }
104
+ function describeApproval(toolName, input, reason) {
105
+ const risk = toolName === "shell" ? "dangerous" : READ_TOOLS.has(toolName) ? "read" : "write";
106
+ if (toolName === "shell") {
107
+ const command = String(input.command ?? "");
108
+ const first = command.split("\n")[0].slice(0, 200);
109
+ const detail = command.length > 200 || command.includes("\n") ? capLines(command, 20) : undefined;
110
+ return { toolName, risk, reason, summary: first, detail };
111
+ }
112
+ if (toolName === "write_file" || toolName === "edit_file") {
113
+ const target = String(input.path ?? "");
114
+ return { toolName, risk, reason, summary: `${toolName === "write_file" ? "Write" : "Edit"} ${target}`, diff: previewDiff(toolName, input) };
115
+ }
116
+ const json = JSON.stringify(input, null, 2);
117
+ return { toolName, risk, reason, summary: toolName, detail: json && json !== "{}" ? capLines(json, 20) : undefined };
118
+ }
119
+ function refreshApproval() {
120
+ for (const entry of permissionQueue) {
121
+ if (entry.timer) {
122
+ clearTimeout(entry.timer);
123
+ entry.timer = undefined;
124
+ }
125
+ }
126
+ const front = permissionQueue[0];
127
+ if (front) {
128
+ front.timer = setTimeout(() => {
129
+ const idx = permissionQueue.indexOf(front);
130
+ if (idx < 0)
131
+ return;
132
+ permissionQueue.splice(idx, 1);
133
+ completedMessages.push({ id: nextId(), kind: "status", text: `\x1b[31m\u2717 ${front.toolName} (no answer, denied)\x1b[0m` });
134
+ refreshApproval();
135
+ front.resolve(false);
136
+ update();
137
+ }, PERMISSION_TIMEOUT_MS);
138
+ }
139
+ approvalInfo = front ? { ...front.info, queueDepth: permissionQueue.length - 1 } : null;
140
+ }
141
+ // Ink-compatible askUser: shows an approval panel, queues for y/n in input
33
142
  config.registry.askUser = async (toolName, input, reason) => {
34
143
  const { addAllow } = await import("../permissions/allowlist.js");
35
- const summary = Object.keys(input).length > 0
36
- ? `${toolName}(${Object.entries(input).map(([k, v]) => `${k}: ${JSON.stringify(v).slice(0, 40)}`).join(", ")})`
37
- : toolName;
38
- completedMessages.push({
39
- id: nextId(),
40
- kind: "status",
41
- text: `\x1b[1m\x1b[33m◇ Allow ${toolName}?\x1b[0m ${summary}\n \x1b[2m[y]es [n]o [a]llow [s]ession or type feedback to deny & redirect\x1b[0m`,
42
- });
144
+ const entry = { resolve: () => { }, toolName, input, info: describeApproval(toolName, input, reason), addAllow };
145
+ const allowed = new Promise((resolve) => { entry.resolve = resolve; });
146
+ permissionQueue.push(entry);
147
+ refreshApproval();
43
148
  update();
44
- return new Promise((resolve) => {
45
- permissionQueue.push({ resolve, toolName, input, addAllow });
46
- });
149
+ return allowed;
47
150
  };
48
151
  // Mutable render state — updated then pushed to React via rerender()
49
152
  const completedMessages = [];
50
153
  let streamingText = "";
154
+ let reasoningText = "";
51
155
  let thinking = false;
52
156
  let thinkStartTime = 0;
53
157
  let thinkElapsed = null;
54
158
  let currentToolCalls = [];
55
159
  let activeTool = null;
160
+ let modelPicker = null;
161
+ let modelPickerResolve = null;
162
+ const toolHistory = [];
163
+ let toolDetailIndex = null;
164
+ let planReview = null;
165
+ let planReviewResolve = null;
56
166
  function nextId() {
57
167
  return `msg-${++msgCounter}`;
58
168
  }
59
169
  function getAppState() {
170
+ const tracker = config.costTracker;
171
+ const cost = tracker
172
+ ? tracker.metered
173
+ ? `$${tracker.totalCost < 0.01 ? tracker.totalCost.toFixed(4) : tracker.totalCost.toFixed(2)}`
174
+ : `${tracker.totalInputTokens + tracker.totalOutputTokens} tok`
175
+ : "";
60
176
  return {
61
177
  provider: config.provider.name,
62
178
  project: config.phrenCtx?.project ?? null,
63
179
  turns: session.turns,
64
- cost: "",
180
+ cost,
65
181
  permMode: config.registry.permissionConfig.mode,
66
182
  agentCount: spawner?.listAgents().length ?? 0,
67
183
  version: AGENT_VERSION,
68
184
  model: config.provider.model,
69
- contextWindow: config.provider.contextWindow,
185
+ contextWindow: contextLimit,
186
+ contextTokens: currentContextTokens(),
70
187
  reasoningEffort: config.provider.reasoningEffort,
71
188
  };
72
189
  }
190
+ let contextMemo = { count: -1, tokens: 0 };
191
+ function currentContextTokens() {
192
+ const count = session.messages.length;
193
+ if (contextMemo.count !== count) {
194
+ contextMemo = { count, tokens: estimateMessageTokens(session.messages) };
195
+ }
196
+ return contextMemo.tokens;
197
+ }
73
198
  // Re-render the Ink app with current state
74
199
  let rerender = null;
75
200
  // Ink app instance — set after render(), used by closures for clear()
@@ -99,7 +224,79 @@ export async function startInkTui(config, spawner) {
99
224
  const displayActiveTool = agentConvo ? agentConvo.activeTool : activeTool;
100
225
  const displayThinking = agentConvo ? false : thinking;
101
226
  const displayRunning = agentConvo ? (spawner?.getAgent(selectedAgentId)?.status === "running" || false) : running;
102
- rerender(_jsx(App, { state: getAppState(), completedMessages: displayMessages, streamingText: displayStreaming, 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) }));
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 }));
228
+ }
229
+ function openModelPicker() {
230
+ const providerName = config.provider.name;
231
+ if (!providerName)
232
+ return Promise.resolve(null);
233
+ const currentModel = config.provider.model;
234
+ const models = getAvailableModels(providerName, currentModel);
235
+ if (models.length === 0)
236
+ return Promise.resolve(null);
237
+ let cursor = models.findIndex((m) => m.id === currentModel);
238
+ if (cursor < 0)
239
+ cursor = 0;
240
+ const reasoning = models.map((m) => m.id === currentModel ? (config.provider.reasoningEffort ?? m.reasoning) : m.reasoning);
241
+ modelPicker = { models, cursor, reasoning };
242
+ update();
243
+ return new Promise((resolve) => { modelPickerResolve = resolve; });
244
+ }
245
+ function closeModelPicker(result) {
246
+ modelPicker = null;
247
+ const resolve = modelPickerResolve;
248
+ modelPickerResolve = null;
249
+ update();
250
+ resolve?.(result);
251
+ }
252
+ function moveModelPicker(delta) {
253
+ if (!modelPicker)
254
+ return;
255
+ const count = modelPicker.models.length;
256
+ modelPicker = { ...modelPicker, cursor: (modelPicker.cursor + delta + count) % count };
257
+ update();
258
+ }
259
+ function adjustModelReasoning(delta) {
260
+ if (!modelPicker)
261
+ return;
262
+ const model = modelPicker.models[modelPicker.cursor];
263
+ if (model.reasoningRange.length === 0)
264
+ return;
265
+ const current = modelPicker.reasoning[modelPicker.cursor];
266
+ const index = current ? REASONING_LEVELS.indexOf(current) : -1;
267
+ const rangeIndices = model.reasoningRange.map((level) => REASONING_LEVELS.indexOf(level));
268
+ const candidate = delta > 0
269
+ ? rangeIndices.find((ri) => ri > index)
270
+ : [...rangeIndices].reverse().find((ri) => ri < index);
271
+ if (candidate === undefined)
272
+ return;
273
+ const reasoning = [...modelPicker.reasoning];
274
+ reasoning[modelPicker.cursor] = REASONING_LEVELS[candidate];
275
+ modelPicker = { ...modelPicker, reasoning };
276
+ update();
277
+ }
278
+ function selectModelPicker() {
279
+ if (!modelPicker)
280
+ return;
281
+ const model = modelPicker.models[modelPicker.cursor];
282
+ const result = { model: model.id, reasoning: modelPicker.reasoning[modelPicker.cursor] };
283
+ closeModelPicker(result);
284
+ }
285
+ function openToolDetail() {
286
+ if (toolHistory.length === 0)
287
+ return;
288
+ toolDetailIndex = toolHistory.length - 1;
289
+ update();
290
+ }
291
+ function moveToolDetail(delta) {
292
+ if (toolDetailIndex === null)
293
+ return;
294
+ toolDetailIndex = (toolDetailIndex + delta + toolHistory.length) % toolHistory.length;
295
+ update();
296
+ }
297
+ function closeToolDetail() {
298
+ toolDetailIndex = null;
299
+ update();
103
300
  }
104
301
  function handlePermissionCycle() {
105
302
  const next = nextPermissionMode(config.registry.permissionConfig.mode, yoloEnabled);
@@ -121,6 +318,18 @@ export async function startInkTui(config, spawner) {
121
318
  }
122
319
  pendingInput = null;
123
320
  steerQueueBuf.length = 0;
321
+ for (const entry of permissionQueue.splice(0)) {
322
+ if (entry.timer)
323
+ clearTimeout(entry.timer);
324
+ entry.resolve(false);
325
+ }
326
+ if (planReviewResolve) {
327
+ const resolve = planReviewResolve;
328
+ planReview = null;
329
+ planReviewResolve = null;
330
+ resolve({ approved: false });
331
+ }
332
+ refreshApproval();
124
333
  update();
125
334
  }
126
335
  // Slash command handler — captures stderr and displays as status messages
@@ -129,6 +338,7 @@ export async function startInkTui(config, spawner) {
129
338
  session,
130
339
  contextLimit,
131
340
  undoStack: [],
341
+ costTracker: config.costTracker,
132
342
  providerName: config.provider.name,
133
343
  currentModel: config.provider.model,
134
344
  currentReasoning: config.provider.reasoningEffort ?? null,
@@ -139,6 +349,21 @@ export async function startInkTui(config, spawner) {
139
349
  startTime,
140
350
  phrenPath: config.phrenCtx?.phrenPath,
141
351
  phrenCtx: config.phrenCtx,
352
+ forkSession: () => {
353
+ if (!config.phrenCtx?.phrenPath || !config.sessionId)
354
+ return { ok: false, message: "Fork needs a phren store." };
355
+ try {
356
+ const childId = randomUUID();
357
+ const child = persistFork(config.phrenCtx.phrenPath, session.log, childId);
358
+ session.log = child;
359
+ config.sessionId = childId;
360
+ setHerdrHookSession(childId);
361
+ return { ok: true, sessionId: childId, message: `Forked to ${childId.slice(0, 8)}` };
362
+ }
363
+ catch (err) {
364
+ return { ok: false, message: err instanceof Error ? err.message : String(err) };
365
+ }
366
+ },
142
367
  onModelChange: async (result) => {
143
368
  try {
144
369
  const { resolveProvider } = await import("../providers/resolve.js");
@@ -150,18 +375,44 @@ export async function startInkTui(config, spawner) {
150
375
  }
151
376
  catch { /* keep current provider */ }
152
377
  },
378
+ pickModel: openModelPicker,
153
379
  },
154
380
  onOutput: (text) => {
155
381
  completedMessages.push({ id: nextId(), kind: "status", text });
156
382
  },
157
383
  });
158
384
  function handleSubmit(input) {
159
- const line = input.trim();
385
+ let line = input.trim();
160
386
  if (!line)
161
387
  return;
388
+ // Plan review active — y approves, n aborts, anything else is feedback
389
+ if (planReview !== null) {
390
+ const key = line.toLowerCase();
391
+ const resolve = planReviewResolve;
392
+ planReview = null;
393
+ planReviewResolve = null;
394
+ if (key === "y" || key === "yes") {
395
+ completedMessages.push({ id: nextId(), kind: "status", text: "\x1b[32m\u2713 plan approved\x1b[0m" });
396
+ update();
397
+ resolve?.({ approved: true });
398
+ }
399
+ else if (key === "n" || key === "no") {
400
+ completedMessages.push({ id: nextId(), kind: "status", text: "\x1b[31m\u2717 plan rejected\x1b[0m" });
401
+ update();
402
+ resolve?.({ approved: false });
403
+ }
404
+ else {
405
+ completedMessages.push({ id: nextId(), kind: "status", text: `\x1b[33m\u21ba revising: "${line}"\x1b[0m` });
406
+ update();
407
+ resolve?.({ approved: false, feedback: line });
408
+ }
409
+ return;
410
+ }
162
411
  // Permission prompt active — intercept y/n/a/s (process next in queue)
163
412
  if (permissionQueue.length > 0) {
164
413
  const entry = permissionQueue.shift();
414
+ if (entry.timer)
415
+ clearTimeout(entry.timer);
165
416
  const key = line.toLowerCase();
166
417
  if (key === "y" || key === "yes") {
167
418
  completedMessages.push({ id: nextId(), kind: "status", text: `\x1b[32m\u2713 ${entry.toolName}\x1b[0m` });
@@ -189,12 +440,14 @@ export async function startInkTui(config, spawner) {
189
440
  }
190
441
  entry.resolve(false);
191
442
  }
443
+ refreshApproval();
192
444
  update();
193
445
  return;
194
446
  }
195
447
  // Track input history (skip duplicates of the last entry)
196
448
  if (inputHistory.length === 0 || inputHistory[inputHistory.length - 1] !== line) {
197
449
  inputHistory.push(line);
450
+ saveInputHistory(inputHistory);
198
451
  }
199
452
  // Bash mode: ! prefix
200
453
  if (line.startsWith("!")) {
@@ -278,6 +531,7 @@ export async function startInkTui(config, spawner) {
278
531
  const idx = THEME_NAMES.indexOf(theme.name);
279
532
  const next = THEME_NAMES[(idx + 1) % THEME_NAMES.length];
280
533
  theme = getTheme(next);
534
+ saveTheme(theme.name);
281
535
  completedMessages.push({ id: nextId(), kind: "status", text: `Theme: ${theme.name} (${THEME_NAMES.join(", ")})` });
282
536
  update();
283
537
  return;
@@ -295,7 +549,18 @@ export async function startInkTui(config, spawner) {
295
549
  }
296
550
  // Slash commands — capture stderr output and display as status message
297
551
  if (line.startsWith("/")) {
298
- if (slashCommands.tryHandleCommand(line)) {
552
+ // /skill-name gesture: rewrite into a run_skill task and fall through
553
+ const customTask = resolveCustomCommand(line);
554
+ const skillTask = customTask ? null : resolveSkillGesture(line, config.phrenCtx);
555
+ if (customTask) {
556
+ completedMessages.push({ id: nextId(), kind: "status", text: `↳ running custom command ${line.split(/\s+/)[0]}` });
557
+ line = customTask;
558
+ }
559
+ else if (skillTask) {
560
+ completedMessages.push({ id: nextId(), kind: "status", text: `↳ running skill via ${line.split(/\s+/)[0]}` });
561
+ line = skillTask;
562
+ }
563
+ else if (slashCommands.tryHandleCommand(line)) {
299
564
  update();
300
565
  return;
301
566
  }
@@ -340,6 +605,10 @@ export async function startInkTui(config, spawner) {
340
605
  streamingText += text;
341
606
  scheduleUpdate();
342
607
  },
608
+ onReasoningDelta: (text) => {
609
+ reasoningText += text;
610
+ scheduleUpdate();
611
+ },
343
612
  onTextDone: () => {
344
613
  // streaming complete — finalized in runAgentTurn
345
614
  },
@@ -355,16 +624,21 @@ export async function startInkTui(config, spawner) {
355
624
  },
356
625
  onToolEnd: (name, input, output, isError, dur) => {
357
626
  activeTool = null;
358
- const diffData = (name === "edit_file" || name === "write_file") ? decodeDiffPayload(output) : null;
627
+ const diffData = (name === "edit_file" || name === "multi_edit" || name === "write_file") ? decodeDiffPayload(output) : null;
359
628
  const cleanOutput = diffData ? output.slice(0, output.indexOf(DIFF_MARKER)) : output;
360
- const diffRendered = diffData ? renderInlineDiff(diffData.oldContent, diffData.newContent, diffData.filePath, theme.diff) : undefined;
361
- currentToolCalls.push({ name, input, output: cleanOutput, isError, durationMs: dur, diffRendered });
629
+ const diffRendered = diffData ? renderDiffCapped(diffData.oldContent, diffData.newContent, diffData.filePath) : undefined;
630
+ const call = { name, input, output: cleanOutput, isError, durationMs: dur, diffRendered };
631
+ currentToolCalls.push(call);
632
+ toolHistory.push(call);
362
633
  update();
363
634
  },
364
- // In the TUI, plan approval is handled by per-tool permission prompts
365
- // rather than a blocking readline prompt. Auto-approve the plan gate
366
- // and let the permission checker require approval on each tool call.
367
- onPlanApproval: async () => ({ approved: true }),
635
+ // Plan mode review happens in the TUI: show the plan and let the person
636
+ // approve, abort, or type feedback to revise before tools re-enable.
637
+ onPlanApproval: () => new Promise((resolve) => {
638
+ planReview = streamingText.trim() || "(empty plan)";
639
+ planReviewResolve = resolve;
640
+ update();
641
+ }),
368
642
  getSteeringInput: () => {
369
643
  const result = (() => {
370
644
  if (steerQueueBuf.length > 0 && inputMode === "steering") {
@@ -389,16 +663,23 @@ export async function startInkTui(config, spawner) {
389
663
  thinkStartTime = Date.now();
390
664
  thinkElapsed = null;
391
665
  streamingText = "";
666
+ reasoningText = "";
392
667
  currentToolCalls = [];
393
668
  activeTool = null;
394
669
  const pastVerb = PAST_VERBS[Math.floor(Math.random() * PAST_VERBS.length)];
395
670
  update();
671
+ emitHerdrHook("UserPromptSubmit");
396
672
  try {
397
673
  await runTurn(userInput, session, config, { ...tuiHooks, signal: turnAbort?.signal });
398
674
  }
399
675
  catch (err) {
400
676
  const msg = err instanceof Error ? err.message : String(err);
401
- streamingText += `\nError: ${msg}`;
677
+ if (!/abort/i.test(msg)) {
678
+ completedMessages.push({ id: nextId(), kind: "status", text: `\x1b[31mError: ${msg}\x1b[0m` });
679
+ }
680
+ }
681
+ finally {
682
+ emitHerdrHook("Stop");
402
683
  }
403
684
  // Compute elapsed time
404
685
  const elapsed = ((Date.now() - thinkStartTime) / 1000).toFixed(1);
@@ -413,6 +694,7 @@ export async function startInkTui(config, spawner) {
413
694
  });
414
695
  }
415
696
  streamingText = "";
697
+ reasoningText = "";
416
698
  currentToolCalls = [];
417
699
  activeTool = null;
418
700
  running = false;
@@ -517,10 +799,12 @@ export async function startInkTui(config, spawner) {
517
799
  spawner.on("tool_end", (agentId, toolName, input, output, isError, durationMs) => {
518
800
  const convo = getOrCreateConvo(agentId);
519
801
  convo.activeTool = null;
520
- const diffData = (toolName === "edit_file" || toolName === "write_file") ? decodeDiffPayload(output) : null;
802
+ const diffData = (toolName === "edit_file" || toolName === "multi_edit" || toolName === "write_file") ? decodeDiffPayload(output) : null;
521
803
  const cleanOutput = diffData ? output.slice(0, output.indexOf(DIFF_MARKER)) : output;
522
- const diffRendered = diffData ? renderInlineDiff(diffData.oldContent, diffData.newContent, diffData.filePath, theme.diff) : undefined;
523
- convo.toolCalls.push({ name: toolName, input, output: cleanOutput, isError, durationMs, diffRendered });
804
+ const diffRendered = diffData ? renderDiffCapped(diffData.oldContent, diffData.newContent, diffData.filePath) : undefined;
805
+ const call = { name: toolName, input, output: cleanOutput, isError, durationMs, diffRendered };
806
+ convo.toolCalls.push(call);
807
+ toolHistory.push(call);
524
808
  rebuildAgentTabs();
525
809
  if (selectedAgentId === agentId)
526
810
  update();
@@ -590,7 +874,7 @@ export async function startInkTui(config, spawner) {
590
874
  process.title = "phren";
591
875
  process.stdout.write(`\x1b]0;phren \xb7 ${projectName}\x07`); // set terminal window title
592
876
  // Initial render
593
- const app = render(_jsx(App, { state: getAppState(), completedMessages: [], streamingText: "", completedToolCalls: [], activeTool: null, thinking: false, thinkStartTime: 0, thinkElapsed: null, steerQueue: [], running: false, showBanner: true, inputHistory: [], verbose: verbose, theme: theme, onSubmit: handleSubmit, onPermissionCycle: handlePermissionCycle, onCancelTurn: handleCancelTurn, onExit: handleExit, agents: undefined, selectedAgentId: undefined, onCancelAgent: handleCancelAgent, onSelectAgent: handleSelectAgent }), { exitOnCtrlC: false });
877
+ const app = render(_jsx(App, { state: getAppState(), completedMessages: [], streamingText: "", completedToolCalls: [], activeTool: null, thinking: false, thinkStartTime: 0, thinkElapsed: null, steerQueue: [], running: false, showBanner: true, inputHistory: [], verbose: verbose, theme: theme, onSubmit: handleSubmit, onPermissionCycle: handlePermissionCycle, onCancelTurn: handleCancelTurn, onExit: handleExit, agents: undefined, selectedAgentId: undefined, onCancelAgent: handleCancelAgent, onSelectAgent: handleSelectAgent, approval: null, modelPicker: null, toolDetail: null, planReview: null }), { exitOnCtrlC: false });
594
878
  rerender = app.rerender;
595
879
  appInstance = app;
596
880
  const done = new Promise((r) => { resolveSession = r; });
@@ -26,7 +26,7 @@ export function formatToolInput(name, input) {
26
26
  switch (name) {
27
27
  case "read_file":
28
28
  case "write_file":
29
- case "edit_file": return input.file_path ?? "";
29
+ case "edit_file": return input.path ?? input.file_path ?? "";
30
30
  case "shell": return (input.command ?? "").slice(0, 60);
31
31
  case "glob": return input.pattern ?? "";
32
32
  case "grep": return `/${input.pattern ?? ""}/ ${input.path ?? ""}`;