@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,41 +1,153 @@
1
+ import { chainKey, recordCall } from "../guards/repeat-tool-reminder.js";
1
2
  import { searchErrorRecovery } from "../memory/error-recovery.js";
2
3
  import { analyzeAndCapture } from "../memory/auto-capture.js";
4
+ import { DIFF_MARKER } from "../multi/diff-renderer.js";
3
5
  const MAX_TOOL_CONCURRENCY = 5;
4
- /** Run tool blocks with concurrency limit. Tracks execution duration per tool. */
5
- export async function runToolsConcurrently(blocks, registry) {
6
- const results = [];
7
- for (let i = 0; i < blocks.length; i += MAX_TOOL_CONCURRENCY) {
8
- const batch = blocks.slice(i, i + MAX_TOOL_CONCURRENCY);
6
+ /** Replay a first result already pulled from an iterator, then drain it. */
7
+ export async function* prefetchFirst(iterator, first) {
8
+ try {
9
+ if (!first.done)
10
+ yield first.value;
11
+ while (true) {
12
+ const next = await iterator.next();
13
+ if (next.done)
14
+ return;
15
+ yield next.value;
16
+ }
17
+ }
18
+ finally {
19
+ await iterator.return?.();
20
+ }
21
+ }
22
+ /** Default per-call budget when the tool declares none. */
23
+ const DEFAULT_TOOL_TIMEOUT_MS = 120_000;
24
+ /** Results that were synthesized by the loop rather than produced by a tool. */
25
+ function isSyntheticResult(output) {
26
+ return output.startsWith("Cancelled by user.") || output.startsWith("User denied permission.");
27
+ }
28
+ /**
29
+ * Run tool blocks with concurrency limit. Tracks execution duration per tool.
30
+ *
31
+ * Identical calls (same tool, same canonicalized arguments) within one
32
+ * assistant message execute once and share the result — the fixed windows
33
+ * launch a whole batch at once, so post-hoc repeat detection alone cannot
34
+ * stop N copies of the same call from all running.
35
+ *
36
+ * The per-call deadline comes from the tool's own timeoutMs declaration
37
+ * (default 120s). Expiry aborts the call's signal AND settles the result;
38
+ * a tool that ignores the signal keeps running detached.
39
+ */
40
+ export async function runToolsConcurrently(blocks, registry, turnSignal) {
41
+ // Dedupe identical calls within this message: first occurrence executes.
42
+ const byKey = new Map();
43
+ const duplicates = new Map(); // dup -> canonical
44
+ for (const block of blocks) {
45
+ const key = chainKey(block.name, block.input);
46
+ const first = byKey.get(key);
47
+ if (first)
48
+ duplicates.set(block, first);
49
+ else
50
+ byKey.set(key, block);
51
+ }
52
+ const uniques = blocks.filter((b) => !duplicates.has(b));
53
+ const resultsByBlock = new Map();
54
+ for (let i = 0; i < uniques.length; i += MAX_TOOL_CONCURRENCY) {
55
+ const batch = uniques.slice(i, i + MAX_TOOL_CONCURRENCY);
9
56
  const batchResults = await Promise.all(batch.map(async (block) => {
10
- const TOOL_TIMEOUT_MS = 120_000;
57
+ if (turnSignal?.aborted)
58
+ return { block, output: "Cancelled by user.", is_error: true, durationMs: 0, cancelled: true };
59
+ const timeoutMs = registry.get(block.name)?.timeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;
11
60
  const start = Date.now();
61
+ const abort = new AbortController();
62
+ let timer;
63
+ let onTurnAbort;
64
+ let onRaceAbort;
12
65
  try {
13
- let timer;
66
+ onTurnAbort = () => abort.abort(turnSignal?.reason);
67
+ turnSignal?.addEventListener("abort", onTurnAbort, { once: true });
68
+ const cancelled = new Promise((_, reject) => {
69
+ onRaceAbort = () => reject(new Error("Cancelled by user."));
70
+ turnSignal?.addEventListener("abort", onRaceAbort, { once: true });
71
+ });
14
72
  const result = await Promise.race([
15
- registry.execute(block.name, block.input),
73
+ registry.execute(block.name, block.input, abort.signal),
74
+ cancelled,
16
75
  new Promise((_, reject) => {
17
- timer = setTimeout(() => reject(new Error(`Tool '${block.name}' timed out after ${TOOL_TIMEOUT_MS / 1000}s`)), TOOL_TIMEOUT_MS);
76
+ timer = setTimeout(() => {
77
+ abort.abort(new Error(`timeout after ${timeoutMs / 1000}s`));
78
+ reject(new Error(`Tool '${block.name}' timed out after ${timeoutMs / 1000}s`));
79
+ }, timeoutMs);
18
80
  }),
19
81
  ]);
20
- clearTimeout(timer);
21
- return { block, output: result.output, is_error: !!result.is_error, durationMs: Date.now() - start };
82
+ return {
83
+ block,
84
+ output: result.output,
85
+ is_error: !!result.is_error,
86
+ durationMs: Date.now() - start,
87
+ ...(result.permissionDenied ? { permissionDenied: true } : {}),
88
+ ...(result.images && result.images.length > 0 ? { images: result.images } : {}),
89
+ };
22
90
  }
23
91
  catch (err) {
24
92
  const msg = err instanceof Error ? err.message : String(err);
25
- return { block, output: msg, is_error: true, durationMs: Date.now() - start };
93
+ return { block, output: msg, is_error: true, durationMs: Date.now() - start, cancelled: msg === "Cancelled by user." };
94
+ }
95
+ finally {
96
+ if (timer)
97
+ clearTimeout(timer);
98
+ if (onTurnAbort)
99
+ turnSignal?.removeEventListener("abort", onTurnAbort);
100
+ if (onRaceAbort)
101
+ turnSignal?.removeEventListener("abort", onRaceAbort);
26
102
  }
27
103
  }));
28
- results.push(...batchResults);
104
+ for (const r of batchResults)
105
+ resultsByBlock.set(r.block, r);
29
106
  }
30
- return results;
107
+ // Model order preserved; duplicates share the canonical result with a note.
108
+ return blocks.map((block) => {
109
+ const canonical = duplicates.get(block);
110
+ if (!canonical)
111
+ return resultsByBlock.get(block);
112
+ const shared = resultsByBlock.get(canonical);
113
+ return {
114
+ ...shared,
115
+ block,
116
+ output: `${shared.output}\n\n[duplicate call: identical to a call in this same message; the result above was computed once and shared]`,
117
+ };
118
+ });
31
119
  }
32
120
  /** Consume a chatStream into ContentBlock[] + stop_reason, streaming text via callback. */
33
- export async function consumeStream(stream, costTracker, onTextDelta, signal) {
121
+ export async function consumeStream(stream, costTracker, hooks, signal) {
122
+ const onTextDelta = typeof hooks === "function" ? hooks : hooks?.onTextDelta;
123
+ const onReasoningDelta = typeof hooks === "function" ? undefined : hooks?.onReasoningDelta;
124
+ const providerName = typeof hooks === "function" ? undefined : hooks?.providerName;
34
125
  const content = [];
35
126
  let stop_reason = "end_turn";
36
127
  let currentText = "";
128
+ let currentReasoning = "";
37
129
  // Map block index -> tool state for Anthropic-style index-based IDs
38
130
  const toolsByIndex = new Map();
131
+ // Tool calls whose accumulated JSON failed to parse, held until the turn's
132
+ // stop_reason is known (see tool_use_end).
133
+ const malformedTools = [];
134
+ // Reasoning must land BEFORE the text/tool blocks it preceded: Anthropic
135
+ // requires thinking blocks first in the assistant content array.
136
+ const flushReasoning = (end) => {
137
+ if (!currentReasoning && !end?.redacted && !end?.encrypted_content)
138
+ return;
139
+ content.push({
140
+ type: "reasoning",
141
+ text: currentReasoning,
142
+ ...(providerName !== undefined ? { provider: providerName } : {}),
143
+ ...(end?.signature !== undefined ? { signature: end.signature } : {}),
144
+ ...(end?.id !== undefined ? { id: end.id } : {}),
145
+ ...(end?.encrypted_content !== undefined ? { encrypted_content: end.encrypted_content } : {}),
146
+ ...(end?.redacted ? { redacted: true } : {}),
147
+ ...(end?.data !== undefined ? { data: end.data } : {}),
148
+ });
149
+ currentReasoning = "";
150
+ };
39
151
  for await (const delta of stream) {
40
152
  if (signal?.aborted)
41
153
  break;
@@ -43,8 +155,24 @@ export async function consumeStream(stream, costTracker, onTextDelta, signal) {
43
155
  (onTextDelta ?? process.stdout.write.bind(process.stdout))(delta.text);
44
156
  currentText += delta.text;
45
157
  }
158
+ else if (delta.type === "reasoning_delta") {
159
+ // Preserve stream order: a reasoning segment starting after visible
160
+ // text closes that text block first (providers normally emit
161
+ // reasoning before text, so this is the uncommon direction).
162
+ if (currentText && !currentReasoning) {
163
+ content.push({ type: "text", text: currentText });
164
+ currentText = "";
165
+ }
166
+ onReasoningDelta?.(delta.text);
167
+ currentReasoning += delta.text;
168
+ }
169
+ else if (delta.type === "reasoning_end") {
170
+ flushReasoning(delta);
171
+ }
46
172
  else if (delta.type === "tool_use_start") {
47
- // Flush accumulated text
173
+ // Flush accumulated reasoning (without a reasoning_end, e.g. compat
174
+ // providers that only emit deltas), then text.
175
+ flushReasoning();
48
176
  if (currentText) {
49
177
  content.push({ type: "text", text: currentText });
50
178
  currentText = "";
@@ -60,15 +188,25 @@ export async function consumeStream(stream, costTracker, onTextDelta, signal) {
60
188
  const tool = toolsByIndex.get(delta.id);
61
189
  if (tool) {
62
190
  const jsonStr = tool.jsonParts.join("");
63
- let input = {};
191
+ let input = null;
64
192
  try {
65
- input = JSON.parse(jsonStr);
193
+ const parsed = JSON.parse(jsonStr);
194
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
195
+ input = parsed;
196
+ }
197
+ }
198
+ catch { /* fall through to malformed handling */ }
199
+ if (input) {
200
+ content.push({ type: "tool_use", id: tool.id, name: tool.name, input });
66
201
  }
67
- catch {
68
- process.stderr.write(`\x1b[33m[warning] Malformed tool_use JSON for ${tool.name} (${tool.id}), skipping block\x1b[0m\n`);
69
- continue;
202
+ else {
203
+ // Defer: a malformed call must not become an orphan tool_use on a
204
+ // truncated (max_tokens) or text turn, where runTurn never executes
205
+ // it. If the turn does end as tool_use, emit it with empty input so
206
+ // the tool runs and produces the matching tool_result.
207
+ malformedTools.push({ id: tool.id, name: tool.name });
208
+ process.stderr.write(`\x1b[33m[warning] Malformed tool_use JSON for ${tool.name} (${tool.id}); using empty input\x1b[0m\n`);
70
209
  }
71
- content.push({ type: "tool_use", id: tool.id, name: tool.name, input });
72
210
  }
73
211
  }
74
212
  else if (delta.type === "done") {
@@ -78,25 +216,55 @@ export async function consumeStream(stream, costTracker, onTextDelta, signal) {
78
216
  }
79
217
  }
80
218
  }
81
- // Flush remaining text
219
+ // Flush remaining reasoning, then text
220
+ flushReasoning();
82
221
  if (currentText) {
83
222
  if (!currentText.endsWith("\n")) {
84
223
  (onTextDelta ?? process.stdout.write.bind(process.stdout))("\n");
85
224
  }
86
225
  content.push({ type: "text", text: currentText });
87
226
  }
227
+ // Only a genuine tool_use turn can safely carry a synthesized tool block;
228
+ // runTurn executes it and pairs the result. On any other stop reason the
229
+ // block is dropped so the durable history never holds an orphan tool_use.
230
+ if (stop_reason === "tool_use") {
231
+ for (const tool of malformedTools) {
232
+ content.push({ type: "tool_use", id: tool.id, name: tool.name, input: {} });
233
+ }
234
+ }
88
235
  return { content, stop_reason };
89
236
  }
237
+ /**
238
+ * The model-visible part of a tool output. File tools append a full
239
+ * before/after payload after DIFF_MARKER for the TUI's diff view; sending it
240
+ * to the model would put two copies of the file into context on every edit.
241
+ */
242
+ export function modelVisibleOutput(output) {
243
+ const at = output.indexOf(DIFF_MARKER);
244
+ return at === -1 ? output : output.slice(0, at);
245
+ }
90
246
  /** Execute tool blocks, collect results with error recovery and anti-pattern tracking. */
91
247
  export async function executeToolBlocks(toolUseBlocks, ctx) {
92
- const execResults = await runToolsConcurrently(toolUseBlocks, ctx.registry);
248
+ const execResults = await runToolsConcurrently(toolUseBlocks, ctx.registry, ctx.signal);
93
249
  const results = [];
94
250
  let toolCallCount = 0;
95
- for (const { block, output, is_error, durationMs } of execResults) {
251
+ for (const { block, output, is_error, durationMs, images, cancelled } of execResults) {
96
252
  toolCallCount++;
97
253
  let finalOutput = output;
98
254
  ctx.antiPatterns.recordAttempt(block.name, block.input, !is_error, output);
99
- if (is_error && ctx.phrenCtx) {
255
+ // Repeat-call guard: counts every executed call (denied and failed calls
256
+ // included — a model hammering a denied call is exactly the loop worth
257
+ // breaking) and appends an escalating reminder at thresholds.
258
+ if (ctx.repeatChain) {
259
+ const reminder = recordCall(ctx.repeatChain, block.name, block.input);
260
+ if (reminder)
261
+ finalOutput += reminder;
262
+ }
263
+ // Synthetic cancellation/denial results are not tool failures: recovery
264
+ // search and auto-capture would record noise and, for a cancelled turn,
265
+ // run after the user has already asked to stop.
266
+ const synthetic = !!cancelled || isSyntheticResult(output);
267
+ if (is_error && ctx.phrenCtx && !synthetic) {
100
268
  try {
101
269
  const recovery = await searchErrorRecovery(ctx.phrenCtx, output);
102
270
  if (recovery)
@@ -104,21 +272,36 @@ export async function executeToolBlocks(toolUseBlocks, ctx) {
104
272
  }
105
273
  catch { /* best effort */ }
106
274
  try {
107
- await analyzeAndCapture(ctx.phrenCtx, output, ctx.captureState);
275
+ await analyzeAndCapture(ctx.phrenCtx, output, ctx.captureState, ctx.sessionId);
108
276
  }
109
277
  catch { /* best effort */ }
110
278
  }
111
- if (ctx.hooks?.onToolEnd) {
279
+ if (cancelled) {
280
+ // The tool never produced a result, so a completed-call card would
281
+ // misrepresent it; report the cancellation as status instead.
282
+ if (ctx.verbose)
283
+ ctx.status(`\x1b[2m ← ${block.name} cancelled before execution\x1b[0m\n`);
284
+ }
285
+ else if (ctx.hooks?.onToolEnd) {
112
286
  ctx.hooks.onToolEnd(block.name, block.input, finalOutput, is_error, durationMs);
113
287
  }
114
288
  else if (ctx.verbose) {
115
289
  const preview = finalOutput.slice(0, 200);
116
290
  ctx.status(`\x1b[2m ← ${is_error ? "ERROR: " : ""}${preview}${finalOutput.length > 200 ? "..." : ""}\x1b[0m\n`);
117
291
  }
292
+ const modelOutput = modelVisibleOutput(finalOutput);
118
293
  results.push({
119
294
  type: "tool_result",
120
295
  tool_use_id: block.id,
121
- content: finalOutput,
296
+ content: images
297
+ ? [
298
+ { type: "text", text: modelOutput },
299
+ ...images.map((img) => ({
300
+ type: "image",
301
+ source: { type: "base64", media_type: img.media_type, data: img.data },
302
+ })),
303
+ ]
304
+ : modelOutput,
122
305
  is_error,
123
306
  });
124
307
  }
@@ -1,13 +1,26 @@
1
1
  import { createCaptureState } from "../memory/auto-capture.js";
2
2
  import { AntiPatternTracker } from "../memory/anti-patterns.js";
3
3
  import { createFlushConfig } from "../memory/context-flush.js";
4
- export function createSession(contextLimit) {
4
+ import { SessionLog } from "../session/log.js";
5
+ import { createRepeatChain } from "../guards/repeat-tool-reminder.js";
6
+ import { randomUUID } from "crypto";
7
+ export function createSession(contextLimit, options) {
8
+ const log = options?.log ??
9
+ new SessionLog({
10
+ sessionId: `mem-${randomUUID()}`,
11
+ cwd: process.cwd(),
12
+ createdAt: new Date().toISOString(),
13
+ });
5
14
  return {
6
- messages: [],
15
+ log,
16
+ get messages() {
17
+ return log.getMessages();
18
+ },
7
19
  turns: 0,
8
20
  toolCalls: 0,
9
21
  captureState: createCaptureState(),
10
22
  antiPatterns: new AntiPatternTracker(),
11
23
  flushConfig: createFlushConfig(contextLimit ?? 200_000),
24
+ repeatChain: createRepeatChain(),
12
25
  };
13
26
  }
@@ -1,4 +1,5 @@
1
1
  import { execFileSync } from "child_process";
2
+ import { createHash, randomUUID } from "crypto";
2
3
  import * as fs from "fs";
3
4
  import * as path from "path";
4
5
  import * as os from "os";
@@ -15,10 +16,38 @@ function isGitRepo(cwd) {
15
16
  return false;
16
17
  }
17
18
  }
18
- function storeFile(_cwd) {
19
- const dir = path.join(os.homedir(), ".phren-agent");
19
+ function repoRoot(cwd) {
20
+ try {
21
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim() || cwd;
22
+ }
23
+ catch {
24
+ return cwd;
25
+ }
26
+ }
27
+ function repoKey(cwd) {
28
+ let root = cwd;
29
+ try {
30
+ root = execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim() || cwd;
31
+ }
32
+ catch { /* not a repo yet; fall back to cwd */ }
33
+ try {
34
+ root = fs.realpathSync(root);
35
+ }
36
+ catch { /* keep the path as given */ }
37
+ return createHash("sha256").update(root).digest("hex").slice(0, 16);
38
+ }
39
+ function storeFile(cwd) {
40
+ const dir = path.join(os.homedir(), ".phren-agent", "checkpoints");
20
41
  fs.mkdirSync(dir, { recursive: true });
21
- return path.join(dir, "checkpoints.json");
42
+ const file = path.join(dir, `${repoKey(cwd)}.json`);
43
+ const legacy = path.join(os.homedir(), ".phren-agent", "checkpoints.json");
44
+ if (!fs.existsSync(file) && fs.existsSync(legacy)) {
45
+ try {
46
+ fs.renameSync(legacy, file);
47
+ }
48
+ catch { /* best effort migration */ }
49
+ }
50
+ return file;
22
51
  }
23
52
  function loadStore(cwd) {
24
53
  const file = storeFile(cwd);
@@ -34,36 +63,88 @@ function saveStore(cwd, store) {
34
63
  fs.writeFileSync(storeFile(cwd), JSON.stringify(store, null, 2) + "\n");
35
64
  }
36
65
  /**
37
- * Create a checkpoint via `git stash create`. Returns the ref or null if
38
- * the working tree is clean (stash create produces no output when clean).
66
+ * Create a checkpoint of the working tree, untracked files included.
67
+ *
68
+ * `git stash create` ignores untracked files, so a file created by write_file
69
+ * could not be captured or removed by /rewind. Instead, stage the tree into a
70
+ * throwaway index (GIT_INDEX_FILE) seeded from HEAD, write it to a tree object,
71
+ * wrap it in a commit, and pin it with an update-ref so `git gc` keeps it. The
72
+ * store keeps the commit SHA; `kind: "commit"` marks the new scheme, while
73
+ * entries written before this change have no `kind` and are restored as stash
74
+ * refs. Returns the commit ref, or null when the snapshot could not be made.
39
75
  */
40
76
  export function createCheckpoint(cwd, label) {
41
77
  if (!isGitRepo(cwd))
42
78
  return null;
79
+ const root = repoRoot(cwd);
80
+ const indexFile = path.join(os.tmpdir(), `phren-agent-index-${randomUUID()}`);
81
+ const env = {
82
+ ...process.env,
83
+ GIT_INDEX_FILE: indexFile,
84
+ GIT_AUTHOR_NAME: process.env.GIT_AUTHOR_NAME ?? "phren-agent",
85
+ GIT_AUTHOR_EMAIL: process.env.GIT_AUTHOR_EMAIL ?? "agent@phren.local",
86
+ GIT_COMMITTER_NAME: process.env.GIT_COMMITTER_NAME ?? "phren-agent",
87
+ GIT_COMMITTER_EMAIL: process.env.GIT_COMMITTER_EMAIL ?? "agent@phren.local",
88
+ };
43
89
  try {
44
- const ref = execFileSync("git", ["stash", "create"], {
45
- cwd,
46
- encoding: "utf-8",
47
- stdio: ["ignore", "pipe", "pipe"],
48
- }).trim();
49
- if (!ref)
50
- return null; // clean working tree
51
- // Store the ref so `git gc` won't collect it
52
- execFileSync("git", ["stash", "store", "-m", label || "phren-checkpoint", ref], {
53
- cwd,
54
- encoding: "utf-8",
55
- stdio: ["ignore", "pipe", "pipe"],
56
- });
57
- const store = loadStore(cwd);
90
+ execFileSync("git", ["read-tree", "HEAD"], { cwd: root, env, stdio: ["ignore", "pipe", "pipe"] });
91
+ execFileSync("git", ["add", "-A"], { cwd: root, env, stdio: ["ignore", "pipe", "pipe"] });
92
+ const tree = execFileSync("git", ["write-tree"], { cwd: root, env, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
93
+ if (!tree)
94
+ return null;
95
+ const commit = execFileSync("git", ["commit-tree", tree, "-p", "HEAD", "-m", label || "phren-checkpoint"], { cwd: root, env, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
96
+ if (!commit)
97
+ return null;
98
+ const refName = `refs/phren-agent/checkpoints/${repoKey(root)}-${Date.now()}-${randomUUID().slice(0, 8)}`;
99
+ execFileSync("git", ["update-ref", refName, commit], { cwd: root, stdio: ["ignore", "pipe", "pipe"] });
100
+ const store = loadStore(root);
58
101
  store.checkpoints.push({
59
- ref,
102
+ ref: commit,
60
103
  label: label || `checkpoint-${store.checkpoints.length + 1}`,
61
104
  createdAt: new Date().toISOString(),
105
+ kind: "commit",
62
106
  });
63
- saveStore(cwd, store);
64
- return ref;
107
+ saveStore(root, store);
108
+ return commit;
65
109
  }
66
110
  catch {
67
111
  return null;
68
112
  }
113
+ finally {
114
+ fs.rmSync(indexFile, { force: true });
115
+ }
116
+ }
117
+ /** Stored checkpoints, newest first. */
118
+ export function listCheckpoints() {
119
+ return loadStore(process.cwd()).checkpoints.slice().reverse();
120
+ }
121
+ /**
122
+ * Restore the working tree to a stored checkpoint. Takes a safety checkpoint
123
+ * of the current state first. New "commit" checkpoints restore the full tree
124
+ * (`git checkout <ref> -- .`) and remove untracked files created since
125
+ * (`git clean -fd`, which leaves ignored files alone). Legacy stash refs keep
126
+ * the old checkout + stash-apply path.
127
+ */
128
+ export function restoreCheckpoint(cwd, ref) {
129
+ if (!isGitRepo(cwd))
130
+ return { ok: false, message: "Not a git repository." };
131
+ const root = repoRoot(cwd);
132
+ const checkpoint = loadStore(root).checkpoints.find((c) => c.ref === ref || c.label === ref);
133
+ if (!checkpoint)
134
+ return { ok: false, message: `No checkpoint "${ref}".` };
135
+ try {
136
+ createCheckpoint(root, "pre-restore");
137
+ if (checkpoint.kind === "commit") {
138
+ execFileSync("git", ["checkout", checkpoint.ref, "--", "."], { cwd: root, stdio: ["ignore", "pipe", "pipe"] });
139
+ execFileSync("git", ["clean", "-fd"], { cwd: root, stdio: ["ignore", "pipe", "pipe"] });
140
+ }
141
+ else {
142
+ execFileSync("git", ["checkout", "--", "."], { cwd: root, stdio: ["ignore", "pipe", "pipe"] });
143
+ execFileSync("git", ["stash", "apply", checkpoint.ref], { cwd: root, stdio: ["ignore", "pipe", "pipe"] });
144
+ }
145
+ return { ok: true, message: `Restored ${checkpoint.label} (${checkpoint.createdAt.slice(0, 19).replace("T", " ")}).` };
146
+ }
147
+ catch (err) {
148
+ return { ok: false, message: err instanceof Error ? err.message : String(err) };
149
+ }
69
150
  }
@@ -1,8 +1,8 @@
1
1
  import { estimateMessageTokens } from "../context/token-counter.js";
2
2
  import { execSync } from "node:child_process";
3
3
  const DIM = "\x1b[2m";
4
- const BOLD = "\x1b[1m";
5
- const CYAN = "\x1b[36m";
4
+ const _BOLD = "\x1b[1m";
5
+ const _CYAN = "\x1b[36m";
6
6
  const GREEN = "\x1b[32m";
7
7
  const RED = "\x1b[31m";
8
8
  const YELLOW = "\x1b[33m";
@@ -22,7 +22,8 @@ export function helpCommand(_parts, _ctx) {
22
22
  /plan Show conversation plan (tool calls so far)
23
23
  /undo Undo last user message and response
24
24
  /history [n|full] Show last N messages (default 10) with rich formatting
25
- /compact Compact conversation to save context space
25
+ /compact Compact conversation (LLM checkpoint + knowledge promotion)
26
+ /review Triage the phren review queue (go = manual, auto = model-assisted)
26
27
  /context Show context window usage and provider info
27
28
  /mode Toggle input mode (steering ↔ queue)
28
29
  /verbose Toggle verbose tool output (show first 5 lines)
@@ -46,13 +47,18 @@ export function helpCommand(_parts, _ctx) {
46
47
  export function turnsCommand(_parts, ctx) {
47
48
  const tokens = estimateMessageTokens(ctx.session.messages);
48
49
  const pct = ctx.contextLimit > 0 ? ((tokens / ctx.contextLimit) * 100).toFixed(1) : "?";
49
- const costLine = ctx.costTracker ? ` Cost: $${ctx.costTracker.totalCost.toFixed(4)}` : "";
50
+ const costLine = ctx.costTracker
51
+ ? ` Cost: ${ctx.costTracker.metered ? `$${ctx.costTracker.totalCost.toFixed(4)}` : "included"}`
52
+ : "";
50
53
  process.stderr.write(`${DIM}Turns: ${ctx.session.turns} Tool calls: ${ctx.session.toolCalls} ` +
51
54
  `Messages: ${ctx.session.messages.length} Tokens: ~${tokens} (${pct}%)${costLine}${RESET}\n`);
52
55
  return true;
53
56
  }
54
57
  export function clearCommand(_parts, ctx) {
55
- ctx.session.messages.length = 0;
58
+ const count = ctx.session.messages.length;
59
+ if (count > 0) {
60
+ ctx.session.log.replaceMessageRange(0, count - 1, { role: "user", content: "[conversation cleared]" });
61
+ }
56
62
  ctx.session.turns = 0;
57
63
  ctx.session.toolCalls = 0;
58
64
  ctx.undoStack.length = 0;
@@ -87,7 +93,8 @@ export function filesCommand(_parts, _ctx) {
87
93
  export function costCommand(_parts, ctx) {
88
94
  const ct = ctx.costTracker;
89
95
  if (ct) {
90
- process.stderr.write(`${DIM}Tokens — input: ${ct.inputTokens} output: ${ct.outputTokens} est. cost: $${ct.totalCost.toFixed(4)}${RESET}\n`);
96
+ const cost = ct.metered ? `$${ct.totalCost.toFixed(4)}` : "included";
97
+ process.stderr.write(`${DIM}Tokens — input: ${ct.totalInputTokens} output: ${ct.totalOutputTokens} est. cost: ${cost}${RESET}\n`);
91
98
  }
92
99
  else {
93
100
  process.stderr.write(`${DIM}Cost tracking not available.${RESET}\n`);
@@ -114,18 +121,26 @@ export function planCommand(_parts, ctx) {
114
121
  return true;
115
122
  }
116
123
  export function undoCommand(_parts, ctx) {
117
- if (ctx.session.messages.length < 2) {
124
+ const messages = ctx.session.messages;
125
+ let start = -1;
126
+ for (let i = messages.length - 1; i >= 0; i--) {
127
+ const message = messages[i];
128
+ if (message.role !== "user")
129
+ continue;
130
+ const hasText = typeof message.content === "string"
131
+ || (Array.isArray(message.content) && message.content.some((b) => b.type === "text"));
132
+ if (hasText) {
133
+ start = i;
134
+ break;
135
+ }
136
+ }
137
+ if (start < 0 || messages.length < 2) {
118
138
  process.stderr.write(`${DIM}Nothing to undo.${RESET}\n`);
119
139
  return true;
120
140
  }
121
- let removed = 0;
122
- while (ctx.session.messages.length > 0) {
123
- const last = ctx.session.messages.pop();
124
- removed++;
125
- if (last?.role === "user" && typeof last.content === "string")
126
- break;
127
- }
128
- process.stderr.write(`${DIM}Undid ${removed} messages.${RESET}\n`);
141
+ const removed = messages.length - start;
142
+ ctx.session.log.replaceMessageRange(start, messages.length - 1, { role: "user", content: "[undone]" });
143
+ process.stderr.write(`${DIM}Undid ${removed} message${removed === 1 ? "" : "s"}.${RESET}\n`);
129
144
  return true;
130
145
  }
131
146
  export function contextCommand(_parts, ctx) {
@@ -51,7 +51,7 @@ export function modelCommand(parts, ctx) {
51
51
  process.stderr.write(`${DIM}Provider not configured. Start with --provider to set one.${RESET}\n`);
52
52
  return true;
53
53
  }
54
- showModelPicker(ctx.providerName, ctx.currentModel, ctx.currentReasoning, process.stdout).then((result) => {
54
+ const applyResult = (result) => {
55
55
  if (result && ctx.onModelChange) {
56
56
  ctx.onModelChange(result);
57
57
  const reasoningLabel = result.reasoning ? ` (reasoning: ${result.reasoning})` : "";
@@ -60,7 +60,11 @@ export function modelCommand(parts, ctx) {
60
60
  else if (result) {
61
61
  process.stderr.write(`${DIM}Model selected: ${result.model} -- restart to apply.${RESET}\n`);
62
62
  }
63
- });
63
+ };
64
+ if (ctx.pickModel) {
65
+ return ctx.pickModel().then((result) => { applyResult(result); return true; });
66
+ }
67
+ showModelPicker(ctx.providerName, ctx.currentModel, ctx.currentReasoning, process.stdout).then(applyResult);
64
68
  return true;
65
69
  }
66
70
  export function providerCommand(_parts, _ctx) {