@phren/agent 0.3.19 → 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.
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The live reply sidecar: `<event log>.preview.json` holds the assistant text
3
+ * block the model is streaming right now, as `{turnStartedAt, text}` (the
4
+ * shape OpenCode's plugin writes). The event log only gets whole messages;
5
+ * Phren Hook reads this file to stream a reply to the phone while it is
6
+ * still being written. Removed once the message lands in the log.
7
+ */
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+ import { sessionsDir } from "@phren/cli/session/utils";
11
+ import { eventLogPath } from "./persist.js";
12
+ /** At most this often on disk; the Hook reads it twice a second. */
13
+ export const PREVIEW_WRITE_MS = 100;
14
+ const MAX_TEXT = 32_768;
15
+ /**
16
+ * A sidecar untouched this long belongs to a process that died mid-reply
17
+ * (a live one rewrites it while streaming and removes it when done).
18
+ */
19
+ export const STALE_PREVIEW_MS = 30 * 60_000;
20
+ /**
21
+ * Remove sidecars and their staging files that a killed agent left behind.
22
+ * Best effort; run when an agent session starts or resumes.
23
+ */
24
+ export function removeStalePreviews(phrenPath, maxAgeMs = STALE_PREVIEW_MS, now = Date.now()) {
25
+ const dir = sessionsDir(phrenPath);
26
+ let entries;
27
+ try {
28
+ entries = fs.readdirSync(dir);
29
+ }
30
+ catch {
31
+ return 0;
32
+ }
33
+ let removed = 0;
34
+ for (const name of entries) {
35
+ if (!/\.preview\.json(?:\.\d+\.tmp)?$/.test(name))
36
+ continue;
37
+ const file = path.join(dir, name);
38
+ try {
39
+ if (now - fs.statSync(file).mtimeMs < maxAgeMs)
40
+ continue;
41
+ fs.rmSync(file, { force: true });
42
+ removed++;
43
+ }
44
+ catch { /* gone already */ }
45
+ }
46
+ return removed;
47
+ }
48
+ export function previewPath(phrenPath, sessionId) {
49
+ return `${eventLogPath(phrenPath, sessionId)}.preview.json`;
50
+ }
51
+ export function livePreview(file, now = Date.now) {
52
+ let turnStartedAt = "";
53
+ let text = "";
54
+ let writtenAt = -Infinity;
55
+ let timer;
56
+ const cancel = () => { if (timer) {
57
+ clearTimeout(timer);
58
+ timer = undefined;
59
+ } };
60
+ const write = () => {
61
+ cancel();
62
+ if (!turnStartedAt || !text)
63
+ return;
64
+ writtenAt = now();
65
+ const staging = `${file}.${process.pid}.tmp`;
66
+ try {
67
+ fs.writeFileSync(staging, JSON.stringify({ turnStartedAt, text }), { mode: 0o600 });
68
+ fs.renameSync(staging, file);
69
+ }
70
+ catch {
71
+ try {
72
+ fs.rmSync(staging, { force: true });
73
+ }
74
+ catch { /* best effort */ }
75
+ }
76
+ };
77
+ return {
78
+ // A new response (or a retried one) shows its first words at once.
79
+ start(at) { cancel(); turnStartedAt = at; text = ""; writtenAt = -Infinity; },
80
+ append(delta) {
81
+ if (!turnStartedAt || text.length >= MAX_TEXT)
82
+ return;
83
+ text = (text + delta).slice(0, MAX_TEXT);
84
+ const wait = writtenAt + PREVIEW_WRITE_MS - now();
85
+ if (wait <= 0)
86
+ write();
87
+ else if (!timer)
88
+ timer = setTimeout(write, wait);
89
+ },
90
+ clear() {
91
+ cancel();
92
+ text = "";
93
+ try {
94
+ fs.rmSync(file, { force: true });
95
+ }
96
+ catch { /* best effort */ }
97
+ },
98
+ };
99
+ }
@@ -1,14 +1,37 @@
1
- import { execFile, spawn } from "child_process";
2
- import { promisify } from "util";
1
+ import { spawn } from "child_process";
3
2
  import * as fs from "fs";
4
3
  import * as path from "path";
5
4
  import * as os from "os";
6
5
  import { checkShellSafety, scrubEnv } from "../permissions/shell-safety.js";
7
6
  import { wrapWithSandbox, classifySandboxDenial, SandboxRequiredError } from "../permissions/kernel-sandbox.js";
8
- const execFileAsync = promisify(execFile);
9
- const DEFAULT_TIMEOUT_MS = 30_000;
10
- const MAX_TIMEOUT_MS = 120_000;
7
+ /** A positive whole number from the environment, else the fallback. */
8
+ function envPositiveInt(key, fallback) {
9
+ const value = Number(process.env[key]);
10
+ return Number.isInteger(value) && value > 0 ? value : fallback;
11
+ }
12
+ /**
13
+ * Foreground limits. A real test suite or build often needs minutes, and
14
+ * weaker models handle background polling badly, so the cap is 10 minutes
15
+ * (as in Claude Code). Override with PHREN_AGENT_SHELL_TIMEOUT_MS (default)
16
+ * and PHREN_AGENT_SHELL_MAX_TIMEOUT_MS (cap).
17
+ */
18
+ function shellTimeouts() {
19
+ const maxMs = envPositiveInt("PHREN_AGENT_SHELL_MAX_TIMEOUT_MS", 600_000);
20
+ return { defaultMs: Math.min(maxMs, envPositiveInt("PHREN_AGENT_SHELL_TIMEOUT_MS", 120_000)), maxMs };
21
+ }
22
+ /** Background task_output reads are capped at this many trailing characters. */
11
23
  const MAX_OUTPUT_BYTES = 100_000;
24
+ /**
25
+ * Foreground output kept for the model: the head (what ran) and the tail
26
+ * (test summaries, stack traces). Anything between is dropped with a marker
27
+ * and the full output is kept in a log file the model can read.
28
+ */
29
+ export const OUTPUT_HEAD_CHARS = 8_000;
30
+ export const OUTPUT_TAIL_CHARS = 24_000;
31
+ /** Stop writing the full-output file past this, so a runaway command can't fill the disk. */
32
+ const MAX_SPILL_BYTES = 50_000_000;
33
+ /** All full-output files of one agent process together stop growing past this (PHREN_AGENT_SHELL_SPILL_TOTAL_BYTES). */
34
+ const sessionSpillLimit = () => envPositiveInt("PHREN_AGENT_SHELL_SPILL_TOTAL_BYTES", 200_000_000);
12
35
  // Background task tracking
13
36
  const backgroundTasks = new Map();
14
37
  /**
@@ -29,6 +52,214 @@ function backgroundLogDir() {
29
52
  return backgroundLogRoot;
30
53
  }
31
54
  let nextBgId = 1;
55
+ let nextSpillId = 1;
56
+ /** Full-output files written by this process; removed when it exits. */
57
+ const spillFiles = new Set();
58
+ let sessionSpilled = 0;
59
+ /**
60
+ * Process groups of foreground commands still running. Each one is detached
61
+ * into its own group (so a timeout kills what it spawned), which also means
62
+ * Ctrl+C, a closed terminal or the agent exiting no longer reach it; the
63
+ * exit and signal handlers below kill them instead.
64
+ */
65
+ const foregroundGroups = new Set();
66
+ let exitHandlersInstalled = false;
67
+ /** Kill every running foreground command's process group. Synchronous, so it can run in an exit handler. */
68
+ export function killForegroundCommands() {
69
+ for (const pgid of foregroundGroups) {
70
+ try {
71
+ process.kill(-pgid, "SIGKILL");
72
+ }
73
+ catch { /* already gone */ }
74
+ }
75
+ foregroundGroups.clear();
76
+ }
77
+ /** Remove this process's full-output files. */
78
+ export function removeSpillFiles() {
79
+ for (const file of spillFiles) {
80
+ try {
81
+ fs.rmSync(file, { force: true });
82
+ }
83
+ catch { /* best effort */ }
84
+ }
85
+ spillFiles.clear();
86
+ // Background logs may still be in use; the directory goes only when empty.
87
+ if (backgroundLogRoot) {
88
+ try {
89
+ fs.rmdirSync(backgroundLogRoot);
90
+ backgroundLogRoot = undefined;
91
+ }
92
+ catch { /* not empty */ }
93
+ }
94
+ }
95
+ function onProcessExit() {
96
+ killForegroundCommands();
97
+ removeSpillFiles();
98
+ }
99
+ /**
100
+ * Covers every way the agent ends: process.exit from the one-shot, REPL,
101
+ * TUI and subagent paths (a subagent exits when its parent's IPC channel
102
+ * closes) runs the exit handler; SIGINT, SIGTERM and SIGHUP kill the groups
103
+ * first and, when nothing else handles the signal, re-raise it so the
104
+ * default exit still happens.
105
+ */
106
+ function installExitHandlers() {
107
+ if (exitHandlersInstalled)
108
+ return;
109
+ exitHandlersInstalled = true;
110
+ process.on("exit", onProcessExit);
111
+ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
112
+ const onSignal = () => {
113
+ killForegroundCommands();
114
+ if (process.listenerCount(sig) === 1) {
115
+ process.removeListener(sig, onSignal);
116
+ process.kill(process.pid, sig);
117
+ }
118
+ };
119
+ process.on(sig, onSignal);
120
+ }
121
+ }
122
+ /** Interleaved stdout/stderr, keeping only the head and tail in memory. */
123
+ class OutputCapture {
124
+ head = "";
125
+ tail = "";
126
+ total = 0;
127
+ spillFd = null;
128
+ spillPath = null;
129
+ spilled = 0;
130
+ push(chunk) {
131
+ const full = this.total <= OUTPUT_HEAD_CHARS + OUTPUT_TAIL_CHARS;
132
+ this.total += chunk.length;
133
+ if (full && this.total <= OUTPUT_HEAD_CHARS + OUTPUT_TAIL_CHARS) {
134
+ // Still small enough to hold whole: everything lives in head.
135
+ this.head += chunk;
136
+ return;
137
+ }
138
+ if (full) {
139
+ // Crossing the limit: start the full-output file with what we have.
140
+ const all = this.head + chunk;
141
+ this.openSpill(all.slice(0, all.length - chunk.length));
142
+ this.head = all.slice(0, OUTPUT_HEAD_CHARS);
143
+ this.tail = all.slice(OUTPUT_HEAD_CHARS).slice(-OUTPUT_TAIL_CHARS);
144
+ }
145
+ else {
146
+ this.tail = (this.tail + chunk).slice(-OUTPUT_TAIL_CHARS);
147
+ }
148
+ this.writeSpill(chunk);
149
+ }
150
+ openSpill(initial) {
151
+ if (sessionSpilled >= sessionSpillLimit())
152
+ return;
153
+ try {
154
+ this.spillPath = path.join(backgroundLogDir(), `shell-${nextSpillId++}.log`);
155
+ this.spillFd = fs.openSync(this.spillPath, "wx");
156
+ spillFiles.add(this.spillPath);
157
+ installExitHandlers();
158
+ this.writeSpill(initial);
159
+ }
160
+ catch {
161
+ this.spillFd = null;
162
+ this.spillPath = null;
163
+ }
164
+ }
165
+ get capped() {
166
+ return this.spilled >= MAX_SPILL_BYTES || sessionSpilled >= sessionSpillLimit();
167
+ }
168
+ writeSpill(text) {
169
+ if (this.spillFd === null || this.capped)
170
+ return;
171
+ try {
172
+ const written = fs.writeSync(this.spillFd, text);
173
+ this.spilled += written;
174
+ sessionSpilled += written;
175
+ }
176
+ catch { /* best effort */ }
177
+ }
178
+ /** The model-visible text: whole when small, else head + marker + tail. */
179
+ finish() {
180
+ if (this.spillFd !== null) {
181
+ try {
182
+ fs.closeSync(this.spillFd);
183
+ }
184
+ catch { /* already closed */ }
185
+ this.spillFd = null;
186
+ }
187
+ if (this.total <= OUTPUT_HEAD_CHARS + OUTPUT_TAIL_CHARS)
188
+ return this.head.trim();
189
+ const omitted = this.total - this.head.length - this.tail.length;
190
+ const where = this.spillPath
191
+ ? ` Full output (${this.total} chars${this.capped ? `, file capped at ${this.spilled} bytes` : ""}) is in ${this.spillPath}; read or grep it for the middle.`
192
+ : sessionSpilled >= sessionSpillLimit()
193
+ ? " Full output was not saved: this session's output files reached their size cap; rerun with less output (e.g. pipe through grep or tail)."
194
+ : "";
195
+ return `${this.head}\n\n... [${omitted} chars of output omitted.${where}] ...\n\n${this.tail}`.trim();
196
+ }
197
+ }
198
+ /**
199
+ * Run a command to completion without a size limit: output streams into an
200
+ * OutputCapture, so a verbose command is never killed for printing too much
201
+ * and its real exit code is reported. On POSIX the command gets its own
202
+ * process group so a timeout or cancel also kills what it spawned.
203
+ */
204
+ function runForeground(exe, args, opts) {
205
+ return new Promise((resolve) => {
206
+ const capture = new OutputCapture();
207
+ const posix = process.platform !== "win32";
208
+ let timedOut = false;
209
+ let aborted = false;
210
+ let settled = false;
211
+ let child;
212
+ try {
213
+ child = spawn(exe, args, {
214
+ cwd: opts.cwd,
215
+ env: scrubEnv(),
216
+ stdio: ["ignore", "pipe", "pipe"],
217
+ detached: posix,
218
+ });
219
+ }
220
+ catch (err) {
221
+ resolve({ code: null, signal: null, output: "", timedOut, aborted, error: err instanceof Error ? err : new Error(String(err)) });
222
+ return;
223
+ }
224
+ const pgid = posix ? child.pid : undefined;
225
+ if (pgid) {
226
+ foregroundGroups.add(pgid);
227
+ installExitHandlers();
228
+ }
229
+ const kill = () => {
230
+ try {
231
+ if (pgid)
232
+ process.kill(-pgid, "SIGKILL");
233
+ else
234
+ child.kill("SIGKILL");
235
+ }
236
+ catch { /* already gone */ }
237
+ };
238
+ const timer = setTimeout(() => { timedOut = true; kill(); }, opts.timeout);
239
+ const onAbort = () => { aborted = true; kill(); };
240
+ if (opts.signal?.aborted)
241
+ onAbort();
242
+ else
243
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
244
+ child.stdout?.setEncoding("utf-8");
245
+ child.stderr?.setEncoding("utf-8");
246
+ child.stdout?.on("data", (chunk) => capture.push(chunk));
247
+ child.stderr?.on("data", (chunk) => capture.push(chunk));
248
+ const done = (result) => {
249
+ if (settled)
250
+ return;
251
+ settled = true;
252
+ if (pgid)
253
+ foregroundGroups.delete(pgid);
254
+ clearTimeout(timer);
255
+ opts.signal?.removeEventListener("abort", onAbort);
256
+ resolve({ ...result, output: capture.finish(), timedOut, aborted });
257
+ };
258
+ child.on("error", (err) => done({ code: null, signal: null, error: err }));
259
+ // "close" fires after stdio drains, so the tail is complete.
260
+ child.on("close", (code, signal) => done({ code, signal }));
261
+ });
262
+ }
32
263
  /**
33
264
  * Shell tool factory. `getPermissions` is read per call so /permissions and
34
265
  * /sandbox changes apply live; the kernel write fence derives its writable
@@ -37,9 +268,9 @@ let nextBgId = 1;
37
268
  export function createShellTool(getPermissions) {
38
269
  return {
39
270
  name: "shell",
40
- // Internal budget maxes at 120s; give the scheduler a little headroom so
41
- // the tool's own richer timeout message wins the race.
42
- timeoutMs: MAX_TIMEOUT_MS + 5_000,
271
+ // Give the scheduler a little headroom over the internal cap so the
272
+ // tool's own richer timeout message wins the race.
273
+ timeoutMs: shellTimeouts().maxMs + 5_000,
43
274
  description: "Run a shell command and return stdout + stderr. Use run_in_background for long-running commands (builds, test suites, dev servers). Use description to explain what the command does.",
44
275
  input_schema: {
45
276
  type: "object",
@@ -47,7 +278,7 @@ export function createShellTool(getPermissions) {
47
278
  command: { type: "string", description: "Shell command to execute." },
48
279
  description: { type: "string", description: "Human-readable description of what this command does (shown to user)." },
49
280
  cwd: { type: "string", description: "Working directory. Defaults to process cwd." },
50
- timeout: { type: "number", description: "Timeout in ms. Default: 30000, max: 120000." },
281
+ timeout: { type: "number", description: `Timeout in ms. Default: ${shellTimeouts().defaultMs}, max: ${shellTimeouts().maxMs}.` },
51
282
  run_in_background: { type: "boolean", description: "If true, run in background and return a task_id. Use task_output to get results later." },
52
283
  },
53
284
  required: ["command"],
@@ -55,7 +286,8 @@ export function createShellTool(getPermissions) {
55
286
  async execute(input, signal) {
56
287
  const command = input.command;
57
288
  const cwd = input.cwd || process.cwd();
58
- const timeout = Math.min(MAX_TIMEOUT_MS, input.timeout || DEFAULT_TIMEOUT_MS);
289
+ const limits = shellTimeouts();
290
+ const timeout = Math.min(limits.maxMs, input.timeout || limits.defaultMs);
59
291
  const description = input.description;
60
292
  const runInBackground = input.run_in_background;
61
293
  const safety = checkShellSafety(command);
@@ -107,38 +339,29 @@ export function createShellTool(getPermissions) {
107
339
  return { output: `${noticePrefix}Background task ${taskId} started${desc}${confined}. PID: ${child.pid}. Use task_output to get results.` };
108
340
  }
109
341
  // Foreground execution — async so concurrent tool batches actually run
110
- // concurrently (execFileSync blocked the event loop, making batch
111
- // concurrency fictional and timeouts unenforceable mid-call) and so the
112
- // scheduler's abort signal can kill a hung command.
113
- try {
114
- const { stdout, stderr } = await execFileAsync(exe, exeArgs, {
115
- cwd,
116
- encoding: "utf-8",
117
- timeout,
118
- maxBuffer: MAX_OUTPUT_BYTES,
119
- env: scrubEnv(),
120
- ...(signal ? { signal } : {}),
121
- });
122
- const combined = [stdout, stderr].filter(Boolean).join("\n").trim();
123
- return { output: noticePrefix + (combined || "(no output)") };
342
+ // concurrently and the scheduler's abort signal can kill a hung command.
343
+ const result = await runForeground(exe, exeArgs, { cwd, timeout, signal });
344
+ if (result.error)
345
+ return { output: noticePrefix + result.error.message, is_error: true };
346
+ const combined = result.output;
347
+ if (result.aborted) {
348
+ return { output: `${noticePrefix}Command was cancelled\n${combined}`.trim(), is_error: true };
124
349
  }
125
- catch (err) {
126
- if (err && typeof err === "object" && ("stdout" in err || "stderr" in err)) {
127
- const e = err;
128
- const combined = [e.stdout, e.stderr].filter(Boolean).join("\n").trim();
129
- if (e.killed || e.signal === "SIGTERM") {
130
- return { output: `${noticePrefix}Command timed out or was cancelled after ${timeout}ms\n${combined}`, is_error: true };
131
- }
132
- // Explain kernel write-fence denials so the model redirects instead
133
- // of retrying (classify combined output — commands often 2>&1)
134
- const denial = decision.sandboxed
135
- ? classifySandboxDenial(combined, perms?.projectRoot ?? process.cwd())
136
- : null;
137
- return { output: `${noticePrefix}Exit code ${typeof e.code === "number" ? e.code : 1}\n${combined}${denial ?? ""}`, is_error: true };
138
- }
139
- const msg = err instanceof Error ? err.message : String(err);
140
- return { output: msg, is_error: true };
350
+ if (result.timedOut) {
351
+ return {
352
+ output: `${noticePrefix}Command timed out after ${timeout}ms (pass a larger timeout, up to ${limits.maxMs}ms, or use run_in_background)\n${combined}`.trim(),
353
+ is_error: true,
354
+ };
141
355
  }
356
+ if (result.code === 0)
357
+ return { output: noticePrefix + (combined || "(no output)") };
358
+ // Explain kernel write-fence denials so the model redirects instead
359
+ // of retrying (classify combined output — commands often 2>&1)
360
+ const denial = decision.sandboxed
361
+ ? classifySandboxDenial(combined, perms?.projectRoot ?? process.cwd())
362
+ : null;
363
+ const status = result.code !== null ? `Exit code ${result.code}` : `Killed by ${result.signal ?? "signal"}`;
364
+ return { output: `${noticePrefix}${status}\n${combined}${denial ?? ""}`, is_error: true };
142
365
  },
143
366
  };
144
367
  }
@@ -152,6 +152,9 @@ export async function startInkTui(config, spawner) {
152
152
  const completedMessages = [];
153
153
  let streamingText = "";
154
154
  let reasoningText = "";
155
+ // Length of streamingText when the current model call began, so a retried
156
+ // call can drop only its own partial text.
157
+ let streamMark = 0;
155
158
  let thinking = false;
156
159
  let thinkStartTime = 0;
157
160
  let thinkElapsed = null;
@@ -171,7 +174,7 @@ export async function startInkTui(config, spawner) {
171
174
  const cost = tracker
172
175
  ? tracker.metered
173
176
  ? `$${tracker.totalCost < 0.01 ? tracker.totalCost.toFixed(4) : tracker.totalCost.toFixed(2)}`
174
- : `${tracker.totalInputTokens + tracker.totalOutputTokens} tok`
177
+ : `${tracker.totalInputTokens + tracker.totalCacheReadTokens + tracker.totalOutputTokens} tok`
175
178
  : "";
176
179
  return {
177
180
  provider: config.provider.name,
@@ -370,12 +373,15 @@ export async function startInkTui(config, spawner) {
370
373
  const newProvider = resolveProvider(config.provider.name, result.model, undefined, result.reasoning ?? undefined);
371
374
  config.provider = newProvider;
372
375
  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 });
376
+ config.systemPrompt = config.rebuildSystemPrompt
377
+ ? config.rebuildSystemPrompt({ name: newProvider.name, model: result.model })
378
+ : buildSystemPrompt(config.systemPrompt.split("\n## Last session")[0], null, { name: newProvider.name, model: result.model });
374
379
  update();
375
380
  }
376
381
  catch { /* keep current provider */ }
377
382
  },
378
383
  pickModel: openModelPicker,
384
+ promote: config.promote,
379
385
  },
380
386
  onOutput: (text) => {
381
387
  completedMessages.push({ id: nextId(), kind: "status", text });
@@ -612,6 +618,14 @@ export async function startInkTui(config, spawner) {
612
618
  onTextDone: () => {
613
619
  // streaming complete — finalized in runAgentTurn
614
620
  },
621
+ onAssistantMessage: () => {
622
+ streamMark = streamingText.length;
623
+ },
624
+ onStreamRetry: () => {
625
+ streamingText = streamingText.slice(0, streamMark);
626
+ reasoningText = "";
627
+ scheduleUpdate();
628
+ },
615
629
  onTextBlock: (text) => {
616
630
  thinking = false;
617
631
  streamingText += text;
@@ -664,6 +678,7 @@ export async function startInkTui(config, spawner) {
664
678
  thinkElapsed = null;
665
679
  streamingText = "";
666
680
  reasoningText = "";
681
+ streamMark = 0;
667
682
  currentToolCalls = [];
668
683
  activeTool = null;
669
684
  const pastVerb = PAST_VERBS[Math.floor(Math.random() * PAST_VERBS.length)];
@@ -695,6 +710,7 @@ export async function startInkTui(config, spawner) {
695
710
  }
696
711
  streamingText = "";
697
712
  reasoningText = "";
713
+ streamMark = 0;
698
714
  currentToolCalls = [];
699
715
  activeTool = null;
700
716
  running = false;
@@ -783,6 +799,13 @@ export async function startInkTui(config, spawner) {
783
799
  if (selectedAgentId === agentId)
784
800
  update();
785
801
  });
802
+ spawner.on("stream_retry", (agentId, discard) => {
803
+ // The agent's model call is being retried: drop the abandoned attempt's text.
804
+ const convo = getOrCreateConvo(agentId);
805
+ convo.streamingText = convo.streamingText.slice(0, Math.max(0, convo.streamingText.length - discard));
806
+ if (selectedAgentId === agentId)
807
+ update();
808
+ });
786
809
  spawner.on("text_block", (agentId, text) => {
787
810
  const convo = getOrCreateConvo(agentId);
788
811
  convo.streamingText += text;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/agent",
3
- "version": "0.3.19",
3
+ "version": "0.3.20",
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": {
@@ -17,7 +17,7 @@
17
17
  "@modelcontextprotocol/sdk": "^1.30.1",
18
18
  "ink": "^7.1.1",
19
19
  "react": "^19.3.0",
20
- "@phren/cli": "0.3.19"
20
+ "@phren/cli": "0.3.20"
21
21
  },
22
22
  "engines": {
23
23
  "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
- }