@phren/agent 0.1.15 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +86 -0
- package/dist/agent-loop/index.js +239 -65
- package/dist/agent-loop/stream.js +212 -29
- package/dist/agent-loop/types.js +15 -2
- package/dist/checkpoint.js +103 -22
- package/dist/commands/info.js +30 -15
- package/dist/commands/model.js +6 -2
- package/dist/commands/review.js +183 -0
- package/dist/commands/session.js +70 -7
- package/dist/commands.js +168 -12
- package/dist/config.js +87 -10
- package/dist/context/compactor.js +239 -0
- package/dist/context/pruner.js +39 -13
- package/dist/context/token-counter.js +33 -1
- package/dist/custom-commands.js +69 -0
- package/dist/guards/repeat-tool-reminder.js +75 -0
- package/dist/headless.js +115 -0
- package/dist/herdr-hooks.js +71 -0
- package/dist/index.js +351 -48
- package/dist/mcp-client.js +434 -73
- package/dist/mcp-oauth.js +121 -0
- package/dist/memory/anti-patterns.js +7 -3
- package/dist/memory/auto-capture.js +7 -3
- package/dist/memory/context.js +92 -73
- package/dist/memory/project-context.js +24 -5
- package/dist/memory/provenance.js +15 -0
- package/dist/memory/review-triage.js +166 -0
- package/dist/memory/session.js +36 -1
- package/dist/models.js +152 -19
- package/dist/multi/child-entry.js +65 -10
- package/dist/multi/diff-renderer.js +3 -3
- package/dist/multi/markdown.js +125 -27
- package/dist/multi/provider-manager.js +8 -0
- package/dist/multi/publish.js +72 -0
- package/dist/multi/spawner.js +45 -4
- package/dist/multi/syntax-highlight.js +25 -4
- package/dist/multi/types.js +1 -1
- package/dist/permissions/allowlist.js +86 -13
- package/dist/permissions/checker.js +42 -7
- package/dist/permissions/kernel-sandbox.js +197 -0
- package/dist/permissions/prompt.js +10 -1
- package/dist/permissions/sandbox.js +40 -17
- package/dist/providers/anthropic.js +154 -7
- package/dist/providers/codex-auth.js +28 -0
- package/dist/providers/codex.js +134 -23
- package/dist/providers/history.js +35 -0
- package/dist/providers/ollama.js +37 -6
- package/dist/providers/openai-compat.js +171 -74
- package/dist/providers/openrouter.js +47 -17
- package/dist/providers/replay.js +62 -0
- package/dist/providers/resolve.js +41 -7
- package/dist/providers/retry.js +38 -5
- package/dist/providers/types.js +9 -1
- package/dist/repl.js +47 -5
- package/dist/session/log.js +217 -0
- package/dist/session/persist.js +190 -0
- package/dist/settings.js +42 -26
- package/dist/system-prompt.js +18 -2
- package/dist/tools/apply-patch.js +355 -0
- package/dist/tools/edit-engine.js +287 -0
- package/dist/tools/edit-file.js +86 -27
- package/dist/tools/grep.js +25 -10
- package/dist/tools/lint-test.js +0 -22
- package/dist/tools/mcp-resources.js +51 -6
- package/dist/tools/phren-finding.js +12 -4
- package/dist/tools/phren-search.js +7 -2
- package/dist/tools/read-file.js +37 -9
- package/dist/tools/read-image.js +76 -0
- package/dist/tools/registry.js +27 -5
- package/dist/tools/shell.js +134 -71
- package/dist/tools/skill.js +20 -20
- package/dist/tools/spawn-agent.js +77 -13
- package/dist/tools/update-plan.js +48 -0
- package/dist/tools/web-fetch.js +110 -12
- package/dist/tools/web-search.js +4 -4
- package/dist/tui/components/App.js +98 -26
- package/dist/tui/components/ApprovalPanel.js +8 -0
- package/dist/tui/components/InputArea.js +5 -5
- package/dist/tui/components/ModelPicker.js +43 -0
- package/dist/tui/components/PhrenInput.js +10 -5
- package/dist/tui/components/PlanReview.js +7 -0
- package/dist/tui/components/ShortcutHelp.js +5 -0
- package/dist/tui/components/StatusBar.js +46 -20
- package/dist/tui/components/SteerQueue.js +1 -1
- package/dist/tui/components/ThinkingIndicator.js +6 -4
- package/dist/tui/components/ToolCall.js +10 -4
- package/dist/tui/components/ToolDetail.js +21 -0
- package/dist/tui/help.js +6 -0
- package/dist/tui/hooks/useKeyboardShortcuts.js +15 -1
- package/dist/tui/index.js +0 -1
- package/dist/tui/ink-entry.js +317 -33
- package/dist/tui/tool-render.js +1 -1
- package/dist/user-hooks.js +171 -0
- package/package.json +14 -8
- package/dist/multi/multi-commands.js +0 -170
- package/dist/multi/multi-events.js +0 -98
- package/dist/multi/multi-render.js +0 -147
- package/dist/multi/pane.js +0 -28
- package/dist/multi/tui-multi.js +0 -200
- package/dist/permissions/privacy.js +0 -248
- package/dist/tui/components/AgentMessage.js +0 -5
- package/dist/tui/components/ChatMessage.js +0 -23
- package/dist/tui/components/CodeBlock.js +0 -8
- package/dist/tui/components/Separator.js +0 -7
- package/dist/tui/components/StreamingText.js +0 -5
- package/dist/tui/components/UserMessage.js +0 -5
- package/dist/tui/menu-mode.js +0 -86
- package/dist/tui/mouse.js +0 -71
- package/dist/tui/terminal-control.js +0 -62
- package/dist/tui.js +0 -781
package/dist/providers/types.js
CHANGED
|
@@ -1 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
/** Text of a tool result, whatever its content shape (images contribute nothing). */
|
|
2
|
+
export function toolResultText(block) {
|
|
3
|
+
if (typeof block.content === "string")
|
|
4
|
+
return block.content;
|
|
5
|
+
return block.content
|
|
6
|
+
.filter((part) => part.type === "text")
|
|
7
|
+
.map((part) => part.text)
|
|
8
|
+
.join("\n");
|
|
9
|
+
}
|
package/dist/repl.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/** Interactive REPL for the phren agent with steering/queue input modes. */
|
|
2
|
+
import { emitHerdrHook, setHerdrHookSession } from "./herdr-hooks.js";
|
|
2
3
|
import * as readline from "node:readline/promises";
|
|
3
4
|
import * as fs from "node:fs";
|
|
4
5
|
import * as path from "node:path";
|
|
5
6
|
import * as os from "node:os";
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { persistFork } from "./session/persist.js";
|
|
6
9
|
import { createSession, runTurn } from "./agent-loop.js";
|
|
7
|
-
import { handleCommand } from "./commands.js";
|
|
10
|
+
import { handleCommand, resolveSkillGesture, resolveCustomCommand } from "./commands.js";
|
|
8
11
|
import { resolveProvider } from "./providers/resolve.js";
|
|
9
12
|
import { loadInputMode } from "./settings.js";
|
|
10
13
|
const HISTORY_DIR = path.join(os.homedir(), ".phren-agent");
|
|
@@ -33,7 +36,8 @@ function saveHistory(lines) {
|
|
|
33
36
|
}
|
|
34
37
|
export async function startRepl(config) {
|
|
35
38
|
const contextLimit = config.provider.contextWindow ?? 200_000;
|
|
36
|
-
const session = createSession(contextLimit);
|
|
39
|
+
const session = createSession(contextLimit, { log: config.sessionLog });
|
|
40
|
+
const startTime = Date.now();
|
|
37
41
|
const history = loadHistory();
|
|
38
42
|
let inputMode = loadInputMode();
|
|
39
43
|
// Queued/steering input buffer — collects input typed while agent is running
|
|
@@ -55,7 +59,26 @@ export async function startRepl(config) {
|
|
|
55
59
|
session,
|
|
56
60
|
contextLimit,
|
|
57
61
|
undoStack: [],
|
|
62
|
+
costTracker: config.costTracker,
|
|
58
63
|
phrenCtx: config.phrenCtx,
|
|
64
|
+
sessionId: config.sessionId,
|
|
65
|
+
startTime,
|
|
66
|
+
phrenPath: config.phrenCtx?.phrenPath,
|
|
67
|
+
forkSession: () => {
|
|
68
|
+
if (!config.phrenCtx?.phrenPath || !config.sessionId)
|
|
69
|
+
return { ok: false, message: "Fork needs a phren store." };
|
|
70
|
+
try {
|
|
71
|
+
const childId = randomUUID();
|
|
72
|
+
const child = persistFork(config.phrenCtx.phrenPath, session.log, childId);
|
|
73
|
+
session.log = child;
|
|
74
|
+
config.sessionId = childId;
|
|
75
|
+
setHerdrHookSession(childId);
|
|
76
|
+
return { ok: true, sessionId: childId, message: `Forked to ${childId.slice(0, 8)}` };
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
return { ok: false, message: err instanceof Error ? err.message : String(err) };
|
|
80
|
+
}
|
|
81
|
+
},
|
|
59
82
|
providerName: config.provider.name,
|
|
60
83
|
currentModel: config.provider.model,
|
|
61
84
|
currentReasoning: config.provider.reasoningEffort ?? null,
|
|
@@ -67,14 +90,25 @@ export async function startRepl(config) {
|
|
|
67
90
|
},
|
|
68
91
|
});
|
|
69
92
|
for await (const line of rl) {
|
|
70
|
-
|
|
93
|
+
let trimmed = line.trim();
|
|
71
94
|
if (!trimmed) {
|
|
72
95
|
rl.prompt();
|
|
73
96
|
continue;
|
|
74
97
|
}
|
|
75
98
|
allHistory.push(trimmed);
|
|
76
|
-
//
|
|
77
|
-
|
|
99
|
+
// /skill-name gesture: rewrite into a run_skill task before command dispatch
|
|
100
|
+
const customTask = resolveCustomCommand(trimmed);
|
|
101
|
+
const skillTask = customTask ? null : resolveSkillGesture(trimmed, config.phrenCtx);
|
|
102
|
+
if (customTask) {
|
|
103
|
+
process.stderr.write(`${DIM}↳ running custom command ${trimmed.split(/\s+/)[0]}${RESET}\n`);
|
|
104
|
+
trimmed = customTask;
|
|
105
|
+
}
|
|
106
|
+
else if (skillTask) {
|
|
107
|
+
process.stderr.write(`${DIM}↳ running skill via ${trimmed.split(/\s+/)[0]}${RESET}\n`);
|
|
108
|
+
trimmed = skillTask;
|
|
109
|
+
}
|
|
110
|
+
else if (handleCommand(trimmed, buildCommandContext())) {
|
|
111
|
+
// Handle slash commands
|
|
78
112
|
rl.prompt();
|
|
79
113
|
continue;
|
|
80
114
|
}
|
|
@@ -90,6 +124,7 @@ export async function startRepl(config) {
|
|
|
90
124
|
continue;
|
|
91
125
|
}
|
|
92
126
|
agentRunning = true;
|
|
127
|
+
emitHerdrHook("UserPromptSubmit");
|
|
93
128
|
try {
|
|
94
129
|
await runTurn(trimmed, session, config);
|
|
95
130
|
}
|
|
@@ -97,6 +132,9 @@ export async function startRepl(config) {
|
|
|
97
132
|
const msg = err instanceof Error ? err.message : String(err);
|
|
98
133
|
process.stderr.write(`${RED}Error: ${msg}${RESET}\n`);
|
|
99
134
|
}
|
|
135
|
+
finally {
|
|
136
|
+
emitHerdrHook("Stop");
|
|
137
|
+
}
|
|
100
138
|
agentRunning = false;
|
|
101
139
|
// Process any input that came in while the agent was working
|
|
102
140
|
while (pendingInput !== null) {
|
|
@@ -108,6 +146,7 @@ export async function startRepl(config) {
|
|
|
108
146
|
break;
|
|
109
147
|
}
|
|
110
148
|
agentRunning = true;
|
|
149
|
+
emitHerdrHook("UserPromptSubmit");
|
|
111
150
|
try {
|
|
112
151
|
if (inputMode === "steering") {
|
|
113
152
|
// Steering: inject as a correction/redirect
|
|
@@ -119,6 +158,9 @@ export async function startRepl(config) {
|
|
|
119
158
|
const msg = err instanceof Error ? err.message : String(err);
|
|
120
159
|
process.stderr.write(`${RED}Error: ${msg}${RESET}\n`);
|
|
121
160
|
}
|
|
161
|
+
finally {
|
|
162
|
+
emitHerdrHook("Stop");
|
|
163
|
+
}
|
|
122
164
|
agentRunning = false;
|
|
123
165
|
}
|
|
124
166
|
rl.prompt();
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/** Bump only when an older reader could misread a newer log. */
|
|
2
|
+
export const SESSION_LOG_VERSION = 1;
|
|
3
|
+
const KNOWN_EVENT_TYPES = new Set(["user/message", "assistant/message", "tool/results", "log/replace"]);
|
|
4
|
+
/** Message-producing event types (the surface fold's inputs). */
|
|
5
|
+
const SURFACE_TYPES = new Set(["user/message", "assistant/message", "tool/results"]);
|
|
6
|
+
/** Recursively freeze event data so history cannot be edited in place. */
|
|
7
|
+
function deepFreeze(value) {
|
|
8
|
+
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
9
|
+
Object.freeze(value);
|
|
10
|
+
for (const key of Object.keys(value)) {
|
|
11
|
+
deepFreeze(value[key]);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Fold events into the model-visible surface (seq + message per node).
|
|
18
|
+
* Pure — shared by the live cache, resume, and tests.
|
|
19
|
+
*/
|
|
20
|
+
export function deriveSurface(events) {
|
|
21
|
+
const surface = [];
|
|
22
|
+
for (const event of events) {
|
|
23
|
+
if (SURFACE_TYPES.has(event.type)) {
|
|
24
|
+
const data = event.data;
|
|
25
|
+
surface.push({ seq: event.seq, message: data.message });
|
|
26
|
+
}
|
|
27
|
+
else if (event.type === "log/replace") {
|
|
28
|
+
const { start, end, message } = event.data;
|
|
29
|
+
const from = surface.findIndex((n) => n.seq >= start);
|
|
30
|
+
if (from === -1) {
|
|
31
|
+
surface.push({ seq: start, message });
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
let to = from;
|
|
35
|
+
while (to < surface.length && surface[to].seq <= end)
|
|
36
|
+
to++;
|
|
37
|
+
surface.splice(from, to - from, { seq: start, message });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return surface;
|
|
41
|
+
}
|
|
42
|
+
/** Fold events into the model-visible message array. */
|
|
43
|
+
export function deriveMessages(events) {
|
|
44
|
+
return deriveSurface(events).map((n) => n.message);
|
|
45
|
+
}
|
|
46
|
+
/** Validation failure loading a persisted log. */
|
|
47
|
+
export class SessionLogError extends Error {
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Validate a parsed event array: contiguous seqs from 0 and no unknown
|
|
51
|
+
* non-ignorable types. Fail closed — a log we cannot fully interpret would
|
|
52
|
+
* silently reconstruct wrong history.
|
|
53
|
+
*/
|
|
54
|
+
export function validateEvents(events) {
|
|
55
|
+
for (let i = 0; i < events.length; i++) {
|
|
56
|
+
const event = events[i];
|
|
57
|
+
if (event.seq !== i) {
|
|
58
|
+
throw new SessionLogError(`event log seq gap: expected ${i}, found ${event.seq}`);
|
|
59
|
+
}
|
|
60
|
+
if (!KNOWN_EVENT_TYPES.has(event.type) && event.ignorable !== true) {
|
|
61
|
+
throw new SessionLogError(`unknown session event type "${event.type}" without ignorable: true — refusing to reconstruct`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The live log: append events, read the derived message projection.
|
|
67
|
+
* Persistence is a caller-supplied sink so the loop stays storage-free.
|
|
68
|
+
*/
|
|
69
|
+
export class SessionLog {
|
|
70
|
+
header;
|
|
71
|
+
events = [];
|
|
72
|
+
sink;
|
|
73
|
+
surface = [];
|
|
74
|
+
derivedAt = -1;
|
|
75
|
+
replaceGeneration = 0;
|
|
76
|
+
derivedGeneration = -1;
|
|
77
|
+
constructor(header, sink) {
|
|
78
|
+
this.header = { type: "header", version: SESSION_LOG_VERSION, ...header };
|
|
79
|
+
this.sink = sink;
|
|
80
|
+
this.sink?.(JSON.stringify(this.header));
|
|
81
|
+
}
|
|
82
|
+
/** Rebuild a log from persisted events (already validated). */
|
|
83
|
+
static restore(header, events, sink) {
|
|
84
|
+
validateEvents(events);
|
|
85
|
+
if (header.version !== SESSION_LOG_VERSION) {
|
|
86
|
+
throw new SessionLogError(`unsupported session log version ${header.version}`);
|
|
87
|
+
}
|
|
88
|
+
const log = Object.create(SessionLog.prototype);
|
|
89
|
+
Object.assign(log, {
|
|
90
|
+
header,
|
|
91
|
+
events: events.map((e) => deepFreeze(e)),
|
|
92
|
+
sink,
|
|
93
|
+
surface: [],
|
|
94
|
+
derivedAt: -1,
|
|
95
|
+
replaceGeneration: events.filter((e) => e.type === "log/replace").length,
|
|
96
|
+
derivedGeneration: -1,
|
|
97
|
+
});
|
|
98
|
+
return log;
|
|
99
|
+
}
|
|
100
|
+
get length() {
|
|
101
|
+
return this.events.length;
|
|
102
|
+
}
|
|
103
|
+
/** Read-only view of the raw events. */
|
|
104
|
+
get all() {
|
|
105
|
+
return this.events;
|
|
106
|
+
}
|
|
107
|
+
append(type, data) {
|
|
108
|
+
const event = {
|
|
109
|
+
seq: this.events.length,
|
|
110
|
+
time: new Date().toISOString(),
|
|
111
|
+
type,
|
|
112
|
+
data,
|
|
113
|
+
};
|
|
114
|
+
// Frozen at commit: history edits must go through append (a log/replace),
|
|
115
|
+
// never in-place mutation of an already-logged message.
|
|
116
|
+
deepFreeze(event);
|
|
117
|
+
this.events.push(event);
|
|
118
|
+
if (type === "log/replace")
|
|
119
|
+
this.replaceGeneration++;
|
|
120
|
+
this.sink?.(JSON.stringify(event));
|
|
121
|
+
return event;
|
|
122
|
+
}
|
|
123
|
+
refreshSurface() {
|
|
124
|
+
if (this.derivedGeneration !== this.replaceGeneration) {
|
|
125
|
+
this.surface = deriveSurface(this.events);
|
|
126
|
+
this.derivedAt = this.events.length;
|
|
127
|
+
this.derivedGeneration = this.replaceGeneration;
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (this.derivedAt < this.events.length) {
|
|
131
|
+
for (let i = this.derivedAt; i < this.events.length; i++) {
|
|
132
|
+
const event = this.events[i];
|
|
133
|
+
if (SURFACE_TYPES.has(event.type)) {
|
|
134
|
+
this.surface.push({ seq: event.seq, message: event.data.message });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
this.derivedAt = this.events.length;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** The model-visible message projection, incrementally cached. */
|
|
141
|
+
getMessages() {
|
|
142
|
+
this.refreshSurface();
|
|
143
|
+
return this.surface.map((n) => n.message);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Replace the surface range [startIndex, endIndex] (message-array indices,
|
|
147
|
+
* inclusive) with one summary message, as a durable log/replace event.
|
|
148
|
+
*/
|
|
149
|
+
replaceMessageRange(startIndex, endIndex, message) {
|
|
150
|
+
this.refreshSurface();
|
|
151
|
+
const start = this.surface[startIndex]?.seq;
|
|
152
|
+
const end = this.surface[endIndex]?.seq;
|
|
153
|
+
if (start === undefined || end === undefined || start > end) {
|
|
154
|
+
throw new SessionLogError(`replace range [${startIndex}, ${endIndex}] outside surface (length ${this.surface.length})`);
|
|
155
|
+
}
|
|
156
|
+
return this.append("log/replace", { start, end, message });
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Assert the cached projection still equals a fresh derivation from the
|
|
160
|
+
* log — the "model-visible means logged" guarantee, run before every
|
|
161
|
+
* provider request. Catches any code path that swapped or reordered the
|
|
162
|
+
* projection without going through append().
|
|
163
|
+
*/
|
|
164
|
+
assertReconstructs() {
|
|
165
|
+
const fresh = deriveMessages(this.events);
|
|
166
|
+
const cached = this.getMessages();
|
|
167
|
+
if (JSON.stringify(cached) !== JSON.stringify(fresh)) {
|
|
168
|
+
throw new SessionLogError("session projection diverged from the event log (history was mutated outside the log)");
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Seed a log from a plain message array (legacy v1 snapshot resume). Roles
|
|
174
|
+
* are classified into event types; unknown roles are dropped with a warning
|
|
175
|
+
* rather than corrupting the log.
|
|
176
|
+
*/
|
|
177
|
+
export function seedFromMessages(log, messages) {
|
|
178
|
+
for (const message of messages) {
|
|
179
|
+
if (message.role === "assistant") {
|
|
180
|
+
log.append("assistant/message", { message, stop_reason: "end_turn", turn: 0 });
|
|
181
|
+
}
|
|
182
|
+
else if (message.role === "user") {
|
|
183
|
+
const isToolResults = Array.isArray(message.content) &&
|
|
184
|
+
message.content.length > 0 &&
|
|
185
|
+
message.content.every((b) => b.type === "tool_result" || b.type === "text");
|
|
186
|
+
if (isToolResults && Array.isArray(message.content) && message.content.some((b) => b.type === "tool_result")) {
|
|
187
|
+
log.append("tool/results", { message, turn: 0 });
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
log.append("user/message", { message, source: "user", turn: 0 });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
process.stderr.write(`[session] dropping message with unknown role during seed: ${String(message.role)}\n`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Fork: the events up to and including `atSeq` become a new session's seed.
|
|
200
|
+
* @returns header + events for the child (caller persists them).
|
|
201
|
+
*/
|
|
202
|
+
export function forkSessionEvents(parent, atSeq, childSessionId) {
|
|
203
|
+
if (atSeq < -1 || atSeq >= parent.length) {
|
|
204
|
+
throw new SessionLogError(`fork boundary ${atSeq} outside log (length ${parent.length})`);
|
|
205
|
+
}
|
|
206
|
+
const events = parent.all.slice(0, atSeq + 1).map((e) => ({ ...e }));
|
|
207
|
+
return {
|
|
208
|
+
header: {
|
|
209
|
+
...parent.header,
|
|
210
|
+
sessionId: childSessionId,
|
|
211
|
+
createdAt: new Date().toISOString(),
|
|
212
|
+
parentSession: parent.header.sessionId,
|
|
213
|
+
seedLength: events.length,
|
|
214
|
+
},
|
|
215
|
+
events,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSONL persistence for the session event log.
|
|
3
|
+
*
|
|
4
|
+
* One line per event, appended as it happens — replaces the whole-file
|
|
5
|
+
* snapshot rewrite (O(n) per turn, O(n^2) per session) for durability.
|
|
6
|
+
* The v1 message snapshot is still written once at session end for
|
|
7
|
+
* consumers that read it (see memory/session.ts).
|
|
8
|
+
*/
|
|
9
|
+
import * as fs from "fs";
|
|
10
|
+
import * as path from "path";
|
|
11
|
+
import { sessionsDir } from "@phren/cli/session/utils";
|
|
12
|
+
import { SessionLog, SessionLogError, forkSessionEvents, validateEvents, } from "./log.js";
|
|
13
|
+
export function eventLogPath(phrenPath, sessionId) {
|
|
14
|
+
return path.join(sessionsDir(phrenPath), `session-${sessionId}.events.jsonl`);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A sink that appends each line to the session's .events.jsonl.
|
|
18
|
+
* Failures are swallowed after a one-time warning: persistence must never
|
|
19
|
+
* take down a running turn.
|
|
20
|
+
*/
|
|
21
|
+
export function fileSink(phrenPath, sessionId) {
|
|
22
|
+
const file = eventLogPath(phrenPath, sessionId);
|
|
23
|
+
let warned = false;
|
|
24
|
+
return (line) => {
|
|
25
|
+
try {
|
|
26
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
27
|
+
fs.appendFileSync(file, line + "\n", "utf8");
|
|
28
|
+
}
|
|
29
|
+
catch (err) {
|
|
30
|
+
if (!warned) {
|
|
31
|
+
warned = true;
|
|
32
|
+
process.stderr.write(`[session] event log write failed (${err instanceof Error ? err.message : String(err)}); continuing without persistence\n`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Load and validate a persisted event log. Exactly one truncated final line
|
|
39
|
+
* is tolerated (a crash mid-append); anything else malformed fails closed.
|
|
40
|
+
*/
|
|
41
|
+
export function loadEventLog(file) {
|
|
42
|
+
const raw = fs.readFileSync(file, "utf8");
|
|
43
|
+
const lines = raw.split("\n").filter((l) => l.length > 0);
|
|
44
|
+
if (lines.length === 0)
|
|
45
|
+
throw new SessionLogError(`empty event log: ${file}`);
|
|
46
|
+
let repairedTail = false;
|
|
47
|
+
const parsed = [];
|
|
48
|
+
for (let i = 0; i < lines.length; i++) {
|
|
49
|
+
try {
|
|
50
|
+
parsed.push(JSON.parse(lines[i]));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
if (i === lines.length - 1) {
|
|
54
|
+
repairedTail = true;
|
|
55
|
+
process.stderr.write(`[session] dropped truncated final event line in ${path.basename(file)}\n`);
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
throw new SessionLogError(`malformed event log line ${i + 1} in ${file}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const header = parsed[0];
|
|
62
|
+
if (!header || header.type !== "header" || typeof header.sessionId !== "string") {
|
|
63
|
+
throw new SessionLogError(`event log missing header line: ${file}`);
|
|
64
|
+
}
|
|
65
|
+
const events = parsed.slice(1);
|
|
66
|
+
validateEvents(events);
|
|
67
|
+
return { header, events, repairedTail };
|
|
68
|
+
}
|
|
69
|
+
/** Restore a live SessionLog from disk, re-attaching an append sink. */
|
|
70
|
+
export function restoreSessionLog(phrenPath, file) {
|
|
71
|
+
const { header, events } = loadEventLog(file);
|
|
72
|
+
return SessionLog.restore(header, events, fileSink(phrenPath, header.sessionId));
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Fork a parent log into a new persisted session: the child file starts with
|
|
76
|
+
* the parent's full event history as its seed and appends from there.
|
|
77
|
+
*/
|
|
78
|
+
export function persistFork(phrenPath, parent, childSessionId) {
|
|
79
|
+
const { header, events } = forkSessionEvents(parent, parent.length - 1, childSessionId);
|
|
80
|
+
const sink = fileSink(phrenPath, childSessionId);
|
|
81
|
+
sink(JSON.stringify(header));
|
|
82
|
+
for (const event of events)
|
|
83
|
+
sink(JSON.stringify(event));
|
|
84
|
+
return SessionLog.restore(header, events, sink);
|
|
85
|
+
}
|
|
86
|
+
/** Recent sessions, newest first; unreadable logs are skipped. */
|
|
87
|
+
export function listEventLogs(phrenPath, opts = {}) {
|
|
88
|
+
const dir = sessionsDir(phrenPath);
|
|
89
|
+
let entries;
|
|
90
|
+
try {
|
|
91
|
+
entries = fs.readdirSync(dir).filter((f) => f.endsWith(".events.jsonl"));
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return [];
|
|
95
|
+
}
|
|
96
|
+
const stats = entries
|
|
97
|
+
.map((entry) => {
|
|
98
|
+
const file = path.join(dir, entry);
|
|
99
|
+
try {
|
|
100
|
+
return { file, mtimeMs: fs.statSync(file).mtimeMs };
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
.filter((e) => e !== null)
|
|
107
|
+
.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
108
|
+
const out = [];
|
|
109
|
+
for (const { file, mtimeMs } of stats) {
|
|
110
|
+
if (out.length >= (opts.limit ?? 20))
|
|
111
|
+
break;
|
|
112
|
+
try {
|
|
113
|
+
const { header, events } = loadEventLog(file);
|
|
114
|
+
if (opts.project && header.project !== opts.project)
|
|
115
|
+
continue;
|
|
116
|
+
const log = SessionLog.restore(header, events, () => { });
|
|
117
|
+
const msgs = log.getMessages();
|
|
118
|
+
if (msgs.length === 0)
|
|
119
|
+
continue;
|
|
120
|
+
const first = msgs.find((m) => m.role === "user" && typeof m.content === "string");
|
|
121
|
+
const title = typeof first?.content === "string" ? first.content.replace(/\s+/g, " ").trim().slice(0, 80) : "";
|
|
122
|
+
out.push({
|
|
123
|
+
sessionId: header.sessionId,
|
|
124
|
+
file,
|
|
125
|
+
mtimeMs,
|
|
126
|
+
...(header.project ? { project: header.project } : {}),
|
|
127
|
+
...(header.cwd ? { cwd: header.cwd } : {}),
|
|
128
|
+
messages: msgs.length,
|
|
129
|
+
title,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// corrupt logs are not listed
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The event log whose session id starts with `idPrefix`.
|
|
140
|
+
* Throws when the prefix matches no session or more than one.
|
|
141
|
+
*/
|
|
142
|
+
export function findEventLogById(phrenPath, idPrefix) {
|
|
143
|
+
const dir = sessionsDir(phrenPath);
|
|
144
|
+
const prefix = idPrefix.replace(/^session-/, "");
|
|
145
|
+
let entries = [];
|
|
146
|
+
try {
|
|
147
|
+
entries = fs.readdirSync(dir).filter((f) => f.startsWith(`session-${prefix}`) && f.endsWith(".events.jsonl"));
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
// no sessions directory
|
|
151
|
+
}
|
|
152
|
+
if (entries.length === 0)
|
|
153
|
+
throw new SessionLogError(`no session matches "${idPrefix}"`);
|
|
154
|
+
if (entries.length > 1) {
|
|
155
|
+
const ids = entries.slice(0, 5).map((f) => f.slice("session-".length, -".events.jsonl".length));
|
|
156
|
+
throw new SessionLogError(`"${idPrefix}" matches ${entries.length} sessions (${ids.join(", ")}${entries.length > 5 ? ", …" : ""}); give more of the id`);
|
|
157
|
+
}
|
|
158
|
+
return path.join(dir, entries[0]);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Newest event log for resume, optionally filtered by project.
|
|
162
|
+
* @returns the file path, or null when none exist.
|
|
163
|
+
*/
|
|
164
|
+
export function findLatestEventLog(phrenPath, project) {
|
|
165
|
+
const dir = sessionsDir(phrenPath);
|
|
166
|
+
let entries;
|
|
167
|
+
try {
|
|
168
|
+
entries = fs.readdirSync(dir).filter((f) => f.endsWith(".events.jsonl"));
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const candidates = [];
|
|
174
|
+
for (const entry of entries) {
|
|
175
|
+
const file = path.join(dir, entry);
|
|
176
|
+
try {
|
|
177
|
+
if (project) {
|
|
178
|
+
const { header } = loadEventLog(file);
|
|
179
|
+
if (header.project !== project)
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
candidates.push({ file, mtimeMs: fs.statSync(file).mtimeMs });
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
// unreadable/corrupt log is skipped for resume selection, not fatal
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
189
|
+
return candidates[0]?.file ?? null;
|
|
190
|
+
}
|
package/dist/settings.js
CHANGED
|
@@ -3,40 +3,56 @@ import * as fs from "fs";
|
|
|
3
3
|
import * as path from "path";
|
|
4
4
|
import * as os from "os";
|
|
5
5
|
export const SETTINGS_FILE = path.join(os.homedir(), ".phren-agent", "settings.json");
|
|
6
|
-
|
|
6
|
+
function readSettings() {
|
|
7
7
|
try {
|
|
8
8
|
const data = JSON.parse(fs.readFileSync(SETTINGS_FILE, "utf-8"));
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return {};
|
|
11
13
|
}
|
|
12
|
-
catch { }
|
|
13
|
-
return "steering";
|
|
14
14
|
}
|
|
15
|
-
|
|
15
|
+
function writeSettings(data) {
|
|
16
16
|
try {
|
|
17
|
-
|
|
18
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
19
|
-
let data = {};
|
|
20
|
-
try {
|
|
21
|
-
data = JSON.parse(fs.readFileSync(SETTINGS_FILE, "utf-8"));
|
|
22
|
-
}
|
|
23
|
-
catch { }
|
|
24
|
-
data.inputMode = mode;
|
|
17
|
+
fs.mkdirSync(path.dirname(SETTINGS_FILE), { recursive: true });
|
|
25
18
|
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(data, null, 2) + "\n");
|
|
26
19
|
}
|
|
27
|
-
catch { }
|
|
20
|
+
catch { /* best effort */ }
|
|
21
|
+
}
|
|
22
|
+
function update(key, value) {
|
|
23
|
+
const data = readSettings();
|
|
24
|
+
data[key] = value;
|
|
25
|
+
writeSettings(data);
|
|
26
|
+
}
|
|
27
|
+
export function loadInputMode() {
|
|
28
|
+
return readSettings().inputMode === "queue" ? "queue" : "steering";
|
|
29
|
+
}
|
|
30
|
+
export function saveInputMode(mode) {
|
|
31
|
+
update("inputMode", mode);
|
|
28
32
|
}
|
|
29
33
|
export function savePermissionMode(mode) {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
}
|
|
37
|
-
catch { }
|
|
38
|
-
data.permissionMode = mode;
|
|
39
|
-
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(data, null, 2) + "\n");
|
|
34
|
+
update("permissionMode", mode);
|
|
35
|
+
}
|
|
36
|
+
export function loadPermissionMode() {
|
|
37
|
+
const mode = readSettings().permissionMode;
|
|
38
|
+
if (mode === "suggest" || mode === "auto-confirm" || mode === "plan" || mode === "full-auto") {
|
|
39
|
+
return mode;
|
|
40
40
|
}
|
|
41
|
-
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
export function loadTheme() {
|
|
44
|
+
const name = readSettings().theme;
|
|
45
|
+
return typeof name === "string" && name ? name : undefined;
|
|
46
|
+
}
|
|
47
|
+
export function saveTheme(name) {
|
|
48
|
+
update("theme", name);
|
|
49
|
+
}
|
|
50
|
+
export function loadInputHistory() {
|
|
51
|
+
const history = readSettings().inputHistory;
|
|
52
|
+
return Array.isArray(history)
|
|
53
|
+
? history.filter((line) => typeof line === "string").slice(-500)
|
|
54
|
+
: [];
|
|
55
|
+
}
|
|
56
|
+
export function saveInputHistory(lines) {
|
|
57
|
+
update("inputHistory", lines.slice(-500));
|
|
42
58
|
}
|
package/dist/system-prompt.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export function buildSystemPrompt(phrenContext, priorSummary, providerInfo) {
|
|
1
|
+
export function buildSystemPrompt(phrenContext, priorSummary, providerInfo, customCommands) {
|
|
2
2
|
const modelNote = providerInfo ? ` You are running on ${providerInfo.name}${providerInfo.model ? ` (model: ${providerInfo.model})` : ""}.` : "";
|
|
3
3
|
const parts = [
|
|
4
4
|
`You are phren-agent, an autonomous coding agent with persistent memory.${modelNote}`,
|
|
@@ -22,6 +22,7 @@ export function buildSystemPrompt(phrenContext, priorSummary, providerInfo) {
|
|
|
22
22
|
"- System: `shell` (run commands, cd, build, test)",
|
|
23
23
|
"- Git: `git_status`, `git_diff`, `git_commit`",
|
|
24
24
|
"- Memory: `phren_search`, `phren_add_finding`, `phren_get_tasks`, `phren_complete_task`, `phren_add_task`",
|
|
25
|
+
"- Planning: `update_plan` — keep a short visible todo list for multi-step work",
|
|
25
26
|
"",
|
|
26
27
|
"## Important",
|
|
27
28
|
"- Be direct and concise. Lead with the answer, not the reasoning.",
|
|
@@ -32,10 +33,25 @@ export function buildSystemPrompt(phrenContext, priorSummary, providerInfo) {
|
|
|
32
33
|
"- You ARE phren-agent. You can run `phren` CLI commands via shell to configure yourself.",
|
|
33
34
|
];
|
|
34
35
|
if (priorSummary) {
|
|
35
|
-
|
|
36
|
+
if (typeof priorSummary === "string") {
|
|
37
|
+
parts.push("", `## Last session\n${priorSummary}`);
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
const meta = [];
|
|
41
|
+
if (priorSummary.project)
|
|
42
|
+
meta.push(`project: ${priorSummary.project}`);
|
|
43
|
+
if (priorSummary.endedAt)
|
|
44
|
+
meta.push(`ended: ${priorSummary.endedAt.slice(0, 16).replace("T", " ")}`);
|
|
45
|
+
const header = meta.length > 0 ? `## Last session (${meta.join(", ")})` : "## Last session";
|
|
46
|
+
parts.push("", `${header}\n${priorSummary.summary}`);
|
|
47
|
+
}
|
|
36
48
|
}
|
|
37
49
|
if (phrenContext) {
|
|
38
50
|
parts.push("", phrenContext);
|
|
39
51
|
}
|
|
52
|
+
if (customCommands && customCommands.length > 0) {
|
|
53
|
+
const lines = customCommands.map((command) => command.description ? `- /${command.name} — ${command.description}` : `- /${command.name}`);
|
|
54
|
+
parts.push("", `## Custom commands\nThe user has defined these slash commands; they expand to instructions you should follow:\n${lines.join("\n")}`);
|
|
55
|
+
}
|
|
40
56
|
return parts.join("\n");
|
|
41
57
|
}
|