@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.
- 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/README.md
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# @phren/agent
|
|
2
|
+
|
|
3
|
+
phren's coding agent. It reads, edits and runs your code with tool calls, and
|
|
4
|
+
starts every session already knowing the project's truths, open tasks, recent
|
|
5
|
+
findings and last session, from the same phren store your other agents use.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g @phren/cli @phren/agent
|
|
9
|
+
phren init # once, creates the memory store
|
|
10
|
+
phren agent -i # or: phren-agent -i
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
It runs on a ChatGPT/Codex subscription (`phren agent auth login`), OpenAI,
|
|
14
|
+
OpenRouter, Anthropic, DeepSeek (`DEEPSEEK_API_KEY`), any OpenAI-compatible
|
|
15
|
+
endpoint (`--provider openai-compat --base-url … --model …`) or local Ollama
|
|
16
|
+
models. For scripts, `-p --output-format json|stream-json` gives
|
|
17
|
+
machine-readable output. [PARITY.md](PARITY.md) compares it with Claude Code,
|
|
18
|
+
Codex and OpenCode, and `scripts/bench/run.mjs` runs it headless against small
|
|
19
|
+
real-task fixture repos. The full guide, including MCP
|
|
20
|
+
servers, permissions, headless runs and the phone app, is
|
|
21
|
+
[docs/agent.md](https://github.com/alaarab/phren/blob/main/docs/agent.md).
|
|
22
|
+
This package is released together with `@phren/cli` and pins its exact version.
|
|
23
|
+
|
|
24
|
+
## Keyboard help and remote MCP
|
|
25
|
+
|
|
26
|
+
Press `?` with an empty draft or `F1` to open keyboard help; Escape closes it
|
|
27
|
+
without losing the draft. The help hint remains visible in every permission mode.
|
|
28
|
+
Assistant text wraps beneath its first text column in both live and completed turns.
|
|
29
|
+
|
|
30
|
+
MCP configuration accepts `stdio`, `http` (Streamable HTTP), and legacy `sse`.
|
|
31
|
+
Remote transports use the MCP SDK, including responses delivered on a separate
|
|
32
|
+
SSE stream after HTTP 202. To enable browser OAuth, set `oauth: true` on a server:
|
|
33
|
+
|
|
34
|
+
```json
|
|
35
|
+
{"mcpServers":{"example":{"type":"http","url":"https://example.com/mcp","oauth":true}}}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
On first connection, open the authorization URL printed in the terminal. The
|
|
39
|
+
loopback callback verifies state; the SDK handles discovery, PKCE and token
|
|
40
|
+
refresh. OAuth requires HTTPS except for local loopback servers. For a registered
|
|
41
|
+
client, `oauth` can instead be an object with `clientId`, optional `clientSecret`,
|
|
42
|
+
`scope`, and `callbackPort` (default 14557). Credentials are stored per server in
|
|
43
|
+
mode-0600 files under `~/.phren/agent/mcp-auth`; `PHREN_MCP_AUTH_DIR` overrides that
|
|
44
|
+
directory. PKCE verifiers remain in memory. Authorization waits at most five
|
|
45
|
+
minutes and closing a connection closes its callback listener.
|
|
46
|
+
|
|
47
|
+
## Developing this package
|
|
48
|
+
|
|
49
|
+
`packages/agent` is a pnpm workspace member, built by the root
|
|
50
|
+
`pnpm build` and tested in CI by its own `agent-test` job:
|
|
51
|
+
|
|
52
|
+
- `pnpm build` (root) includes this package.
|
|
53
|
+
- `pnpm test` (root) does not run this package's tests: its suite runs separately (its own `vitest.config.ts`,
|
|
54
|
+
no workspace-root globalSetup) and is kept off the CI OS×node matrix.
|
|
55
|
+
|
|
56
|
+
To build, test, or lint this package on demand:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pnpm exec turbo run test --filter=@phren/agent # builds @phren/cli dist first
|
|
60
|
+
pnpm --filter @phren/agent build
|
|
61
|
+
pnpm --filter @phren/agent lint
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Note: the test suite imports `@phren/cli` subpath exports that resolve to
|
|
65
|
+
`packages/cli/dist/`, so a bare `pnpm --filter @phren/agent test` on a clean
|
|
66
|
+
checkout fails until the CLI is built — prefer the turbo invocation.
|
|
67
|
+
|
|
68
|
+
## Phren Hook / iPhone chat
|
|
69
|
+
|
|
70
|
+
When phren-agent runs inside a Herdr pane (`HERDR_ENV=1`), it reports
|
|
71
|
+
`SessionStart`, `UserPromptSubmit` and `Stop` to the installed Phren Hook
|
|
72
|
+
bundle (`~/.local/share/phren/bridge/current/bridge-hook.mjs hook phren`, see
|
|
73
|
+
`src/herdr-hooks.ts`) so the iPhone can bind the pane to this session's
|
|
74
|
+
`.runtime/sessions/session-<id>.events.jsonl`. Everything on Phren's side is in
|
|
75
|
+
place; the pane shows up as a chat once Herdr reports `phren` as an agent kind
|
|
76
|
+
(Herdr adds agents in its own releases — see the draft request in the project
|
|
77
|
+
notes). Without Herdr the hook calls are silent no-ops. Under tmux the Hook
|
|
78
|
+
recognizes the agent from its process, whether it was started as `phren-agent`
|
|
79
|
+
or `phren agent` (which spawns this package's binary with argv0 `phren-agent`).
|
|
80
|
+
|
|
81
|
+
## Splash
|
|
82
|
+
|
|
83
|
+
Interactive sessions (`phren-agent -i`, `--multi`, `--team`) open with the
|
|
84
|
+
phren splash — mascot plus the wordmark text effect — using the CLI's
|
|
85
|
+
`@phren/cli/shell/intro` export, with the provider and model in the tagline.
|
|
86
|
+
Set `PHREN_INTRO=off` to skip it.
|
package/dist/agent-loop/index.js
CHANGED
|
@@ -1,14 +1,38 @@
|
|
|
1
1
|
import { createSpinner, formatTurnHeader, formatToolCall } from "../spinner.js";
|
|
2
|
-
import { shouldPrune
|
|
2
|
+
import { shouldPrune } from "../context/pruner.js";
|
|
3
|
+
import { compactWithLlm } from "../context/compactor.js";
|
|
3
4
|
import { estimateMessageTokens } from "../context/token-counter.js";
|
|
4
|
-
import { withRetry } from "../providers/retry.js";
|
|
5
|
+
import { isContextOverflowError, withRetry } from "../providers/retry.js";
|
|
5
6
|
import { checkFlushNeeded } from "../memory/context-flush.js";
|
|
6
7
|
import { injectPlanPrompt, requestPlanApproval } from "../plan.js";
|
|
7
|
-
import { detectLintCommand, detectTestCommand
|
|
8
|
+
import { detectLintCommand, detectTestCommand } from "../tools/lint-test.js";
|
|
8
9
|
import { createCheckpoint } from "../checkpoint.js";
|
|
10
|
+
import { resetRepeatChain } from "../guards/repeat-tool-reminder.js";
|
|
11
|
+
import { runLifecycleHooks } from "../user-hooks.js";
|
|
9
12
|
import { createSession } from "./types.js";
|
|
10
|
-
import { consumeStream, executeToolBlocks } from "./stream.js";
|
|
13
|
+
import { consumeStream, executeToolBlocks, prefetchFirst, runToolsConcurrently } from "./stream.js";
|
|
11
14
|
export { createSession };
|
|
15
|
+
/**
|
|
16
|
+
* If the history ends with an assistant message whose tool calls have no
|
|
17
|
+
* results, append a cancelled result for each. Returns how many were closed.
|
|
18
|
+
*/
|
|
19
|
+
export function closeDanglingToolUses(session, reason = "Cancelled by user.") {
|
|
20
|
+
const messages = session.messages;
|
|
21
|
+
const last = messages[messages.length - 1];
|
|
22
|
+
if (!last || last.role !== "assistant" || !Array.isArray(last.content))
|
|
23
|
+
return 0;
|
|
24
|
+
const calls = last.content.filter((b) => b.type === "tool_use");
|
|
25
|
+
if (calls.length === 0)
|
|
26
|
+
return 0;
|
|
27
|
+
session.log.append("tool/results", {
|
|
28
|
+
message: {
|
|
29
|
+
role: "user",
|
|
30
|
+
content: calls.map((b) => ({ type: "tool_result", tool_use_id: b.id, content: reason, is_error: true })),
|
|
31
|
+
},
|
|
32
|
+
turn: session.turns,
|
|
33
|
+
});
|
|
34
|
+
return calls.length;
|
|
35
|
+
}
|
|
12
36
|
export async function runTurn(userInput, session, config, hooks) {
|
|
13
37
|
const { provider, registry, maxTurns, verbose, costTracker } = config;
|
|
14
38
|
let systemPrompt = config.systemPrompt;
|
|
@@ -23,18 +47,40 @@ export async function runTurn(userInput, session, config, hooks) {
|
|
|
23
47
|
if (planPending) {
|
|
24
48
|
systemPrompt = injectPlanPrompt(systemPrompt);
|
|
25
49
|
}
|
|
26
|
-
//
|
|
27
|
-
|
|
50
|
+
// A previous turn that crashed or was killed mid-tool (or a resumed log
|
|
51
|
+
// written by one) can end with unanswered tool calls; answer them first.
|
|
52
|
+
closeDanglingToolUses(session);
|
|
53
|
+
// Direct user input resets the repeat-call chain (repetition across it is not a loop)
|
|
54
|
+
resetRepeatChain(session.repeatChain);
|
|
55
|
+
// Append user message to the durable log
|
|
56
|
+
session.log.append("user/message", {
|
|
57
|
+
message: { role: "user", content: userInput },
|
|
58
|
+
source: "user",
|
|
59
|
+
turn: session.turns,
|
|
60
|
+
});
|
|
28
61
|
let turnToolCalls = 0;
|
|
29
62
|
const turnStart = session.turns;
|
|
63
|
+
// A refusal applies to automatic checks for this entire user turn.
|
|
64
|
+
const deniedChecks = new Set();
|
|
65
|
+
// One overflow-driven compaction per model call; reset after a success.
|
|
66
|
+
let overflowRecovered = false;
|
|
30
67
|
const signal = hooks?.signal;
|
|
68
|
+
const hookConfig = config.hookConfig ?? null;
|
|
69
|
+
if (hookConfig) {
|
|
70
|
+
await runLifecycleHooks(hookConfig, "UserPromptSubmit", { prompt: userInput });
|
|
71
|
+
}
|
|
72
|
+
// Why the loop ended; stays "max_turns" if the turn cap runs out.
|
|
73
|
+
let endReason = "max_turns";
|
|
31
74
|
while (session.turns - turnStart < maxTurns) {
|
|
32
75
|
// Abort check
|
|
33
|
-
if (signal?.aborted)
|
|
76
|
+
if (signal?.aborted) {
|
|
77
|
+
endReason = "aborted";
|
|
34
78
|
break;
|
|
79
|
+
}
|
|
35
80
|
// Budget check
|
|
36
81
|
if (costTracker?.isOverBudget()) {
|
|
37
82
|
status(`\x1b[33m[budget exceeded: ${costTracker.formatCost()}]\x1b[0m\n`);
|
|
83
|
+
endReason = "budget";
|
|
38
84
|
break;
|
|
39
85
|
}
|
|
40
86
|
if (verbose && session.turns > turnStart) {
|
|
@@ -44,101 +90,200 @@ export async function runTurn(userInput, session, config, hooks) {
|
|
|
44
90
|
const contextLimit = provider.contextWindow ?? 200_000;
|
|
45
91
|
const flushPrompt = checkFlushNeeded(systemPrompt, session.messages, session.flushConfig);
|
|
46
92
|
if (flushPrompt) {
|
|
47
|
-
session.
|
|
93
|
+
session.log.append("user/message", {
|
|
94
|
+
message: { role: "user", content: flushPrompt },
|
|
95
|
+
source: "system",
|
|
96
|
+
turn: session.turns,
|
|
97
|
+
});
|
|
48
98
|
if (verbose)
|
|
49
99
|
status("[context flush injected]\n");
|
|
50
100
|
}
|
|
51
|
-
// Prune context if approaching limit
|
|
52
|
-
|
|
101
|
+
// Prune context if approaching limit — LLM checkpoint with knowledge
|
|
102
|
+
// promotion, degrading to the regex summary on any failure.
|
|
103
|
+
const compactHistory = async (keepRecentTurns, trigger) => {
|
|
53
104
|
const preCount = session.messages.length;
|
|
54
105
|
const preTokens = estimateMessageTokens(session.messages);
|
|
55
|
-
|
|
106
|
+
const result = await compactWithLlm(provider, systemPrompt, session.messages, {
|
|
107
|
+
phrenCtx: config.phrenCtx,
|
|
108
|
+
sessionId: config.sessionId,
|
|
109
|
+
costTracker,
|
|
110
|
+
config: config.compaction,
|
|
111
|
+
pruneConfig: { contextLimit, keepRecentTurns },
|
|
112
|
+
signal,
|
|
113
|
+
verbose,
|
|
114
|
+
});
|
|
115
|
+
if (!result)
|
|
116
|
+
return false;
|
|
117
|
+
session.log.replaceMessageRange(result.plan.startIndex, result.plan.endIndex, result.plan.summaryMessage);
|
|
56
118
|
const postCount = session.messages.length;
|
|
57
119
|
const postTokens = estimateMessageTokens(session.messages);
|
|
58
120
|
const reduction = preTokens > 0 ? ((1 - postTokens / preTokens) * 100).toFixed(0) : "0";
|
|
59
121
|
const fmtPre = preTokens >= 1000 ? `${(preTokens / 1000).toFixed(1)}k` : String(preTokens);
|
|
60
122
|
const fmtPost = postTokens >= 1000 ? `${(postTokens / 1000).toFixed(1)}k` : String(postTokens);
|
|
61
|
-
|
|
123
|
+
const mode = result.usedLlm ? "llm" : "regex";
|
|
124
|
+
const routed = result.promoted + result.queued > 0
|
|
125
|
+
? `, +${result.promoted} promoted, +${result.queued} queued`
|
|
126
|
+
: "";
|
|
127
|
+
status(`\x1b[2m[context compacted (${mode}${trigger}): ${preCount} → ${postCount} messages, ~${fmtPre} → ~${fmtPost} tokens, ${reduction}% reduction${routed}]\x1b[0m\n`);
|
|
128
|
+
return true;
|
|
129
|
+
};
|
|
130
|
+
if (shouldPrune(systemPrompt, session.messages, { contextLimit })) {
|
|
131
|
+
await compactHistory(6, "");
|
|
62
132
|
}
|
|
63
133
|
// For plan mode first turn, pass empty tools so LLM can't call any
|
|
64
134
|
const turnTools = planPending ? [] : toolDefs;
|
|
135
|
+
// Model-visible means logged: everything the provider is about to see
|
|
136
|
+
// must be reconstructable from the event log. Cheap relative to a model
|
|
137
|
+
// call; opt out with PHREN_AGENT_NO_INVARIANT=1 if it ever matters.
|
|
138
|
+
if (process.env.PHREN_AGENT_NO_INVARIANT !== "1") {
|
|
139
|
+
session.log.assertReconstructs();
|
|
140
|
+
}
|
|
65
141
|
let assistantContent;
|
|
66
142
|
let stopReason;
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
143
|
+
try {
|
|
144
|
+
if (useStream) {
|
|
145
|
+
// Streaming path — retry the initial connection. The async generator does
|
|
146
|
+
// no work until first read, so the first next() runs inside withRetry.
|
|
147
|
+
const opening = await withRetry(async () => {
|
|
148
|
+
const iterator = provider.chatStream(systemPrompt, session.messages, turnTools, signal)[Symbol.asyncIterator]();
|
|
149
|
+
const first = await iterator.next();
|
|
150
|
+
return { iterator, first };
|
|
151
|
+
}, undefined, verbose, signal);
|
|
152
|
+
const onReasoningDelta = hooks?.onReasoningDelta ??
|
|
153
|
+
(verbose ? (text) => process.stderr.write(`\x1b[2m${text}\x1b[0m`) : undefined);
|
|
154
|
+
const result = await consumeStream(prefetchFirst(opening.iterator, opening.first), costTracker, { onTextDelta: hooks?.onTextDelta, onReasoningDelta, providerName: provider.name }, signal);
|
|
155
|
+
assistantContent = result.content;
|
|
156
|
+
stopReason = result.stop_reason;
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
// Batch path
|
|
160
|
+
spinner.start("Thinking...");
|
|
161
|
+
const response = await withRetry(() => provider.chat(systemPrompt, session.messages, turnTools, signal), undefined, verbose, signal);
|
|
162
|
+
spinner.stop();
|
|
163
|
+
assistantContent = response.content;
|
|
164
|
+
stopReason = response.stop_reason;
|
|
165
|
+
// Track cost from batch response
|
|
166
|
+
if (costTracker && response.usage) {
|
|
167
|
+
costTracker.recordUsage(response.usage.input_tokens, response.usage.output_tokens);
|
|
168
|
+
}
|
|
169
|
+
// Print text blocks (streaming already prints inline)
|
|
170
|
+
for (const block of assistantContent) {
|
|
171
|
+
if (block.type === "text" && block.text) {
|
|
172
|
+
if (hooks?.onTextBlock) {
|
|
173
|
+
hooks.onTextBlock(block.text);
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
process.stdout.write(block.text);
|
|
177
|
+
if (!block.text.endsWith("\n"))
|
|
178
|
+
process.stdout.write("\n");
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
73
183
|
}
|
|
74
|
-
|
|
75
|
-
// Batch path
|
|
76
|
-
spinner.start("Thinking...");
|
|
77
|
-
const response = await withRetry(() => provider.chat(systemPrompt, session.messages, turnTools), undefined, verbose);
|
|
184
|
+
catch (err) {
|
|
78
185
|
spinner.stop();
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
186
|
+
// The token estimate is approximate; when the provider itself says the
|
|
187
|
+
// prompt is too long, compact harder (keep 2 turns) and retry once.
|
|
188
|
+
if (!overflowRecovered && !signal?.aborted && isContextOverflowError(err)) {
|
|
189
|
+
overflowRecovered = true;
|
|
190
|
+
status("\x1b[33m[provider reported a context overflow; compacting and retrying]\x1b[0m\n");
|
|
191
|
+
if (await compactHistory(2, ", after overflow"))
|
|
192
|
+
continue;
|
|
84
193
|
}
|
|
85
|
-
|
|
194
|
+
throw err;
|
|
195
|
+
}
|
|
196
|
+
overflowRecovered = false;
|
|
197
|
+
if (hooks?.onReasoningDone) {
|
|
86
198
|
for (const block of assistantContent) {
|
|
87
|
-
if (block.type === "
|
|
88
|
-
|
|
89
|
-
hooks.onTextBlock(block.text);
|
|
90
|
-
}
|
|
91
|
-
else {
|
|
92
|
-
process.stdout.write(block.text);
|
|
93
|
-
if (!block.text.endsWith("\n"))
|
|
94
|
-
process.stdout.write("\n");
|
|
95
|
-
}
|
|
96
|
-
}
|
|
199
|
+
if (block.type === "reasoning" && block.text)
|
|
200
|
+
hooks.onReasoningDone(block.text);
|
|
97
201
|
}
|
|
98
202
|
}
|
|
99
|
-
|
|
203
|
+
// Defensive: a provider may report tool_use with no tool blocks (e.g. a
|
|
204
|
+
// malformed call dropped upstream). Executing zero blocks would append an
|
|
205
|
+
// empty tool/results message, which 400s on Anthropic, so treat it as a
|
|
206
|
+
// normal end of turn.
|
|
207
|
+
if (stopReason === "tool_use" && !assistantContent.some((b) => b.type === "tool_use")) {
|
|
208
|
+
stopReason = "end_turn";
|
|
209
|
+
}
|
|
210
|
+
session.log.append("assistant/message", {
|
|
211
|
+
message: { role: "assistant", content: assistantContent },
|
|
212
|
+
stop_reason: stopReason,
|
|
213
|
+
turn: session.turns,
|
|
214
|
+
});
|
|
100
215
|
session.turns++;
|
|
101
|
-
|
|
102
|
-
|
|
216
|
+
hooks?.onAssistantMessage?.(assistantContent, stopReason);
|
|
217
|
+
// Abort check after LLM response. Tool calls the model already made must
|
|
218
|
+
// still get results, or the next request carries an unpaired tool_use,
|
|
219
|
+
// which Anthropic and OpenAI reject on every later turn.
|
|
220
|
+
if (signal?.aborted) {
|
|
221
|
+
closeDanglingToolUses(session);
|
|
222
|
+
endReason = "aborted";
|
|
103
223
|
break;
|
|
224
|
+
}
|
|
104
225
|
// Show turn cost
|
|
105
226
|
if (verbose && costTracker) {
|
|
106
227
|
status(`\x1b[2m cost: ${costTracker.formatCost()}\x1b[0m\n`);
|
|
107
228
|
}
|
|
108
229
|
// Plan mode gate: after first response, ask for approval
|
|
109
230
|
if (planPending) {
|
|
110
|
-
planPending = false;
|
|
111
231
|
const approve = hooks?.onPlanApproval ?? requestPlanApproval;
|
|
112
232
|
const { approved, feedback } = await approve();
|
|
233
|
+
if (signal?.aborted) {
|
|
234
|
+
endReason = "aborted";
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
113
237
|
if (!approved) {
|
|
114
|
-
// Always restore original system prompt on rejection to prevent plan prompt leaking
|
|
115
|
-
systemPrompt = config.systemPrompt;
|
|
116
238
|
const msg = feedback
|
|
117
239
|
? `The user rejected the plan with feedback: ${feedback}\nPlease revise your plan.`
|
|
118
240
|
: "The user rejected the plan. Task aborted.";
|
|
119
241
|
if (feedback) {
|
|
120
|
-
//
|
|
121
|
-
session.
|
|
242
|
+
// Revisions remain in plan mode, with tools disabled, until approved.
|
|
243
|
+
session.log.append("user/message", {
|
|
244
|
+
message: { role: "user", content: msg },
|
|
245
|
+
source: "user",
|
|
246
|
+
turn: session.turns,
|
|
247
|
+
});
|
|
122
248
|
continue;
|
|
123
249
|
}
|
|
250
|
+
endReason = "plan_rejected";
|
|
124
251
|
break;
|
|
125
252
|
}
|
|
126
253
|
// Approved — restore original system prompt and continue with tools enabled
|
|
254
|
+
planPending = false;
|
|
127
255
|
systemPrompt = config.systemPrompt;
|
|
128
|
-
session.
|
|
256
|
+
session.log.append("user/message", {
|
|
257
|
+
message: { role: "user", content: "Plan approved. Proceed with execution." },
|
|
258
|
+
source: "system",
|
|
259
|
+
turn: session.turns,
|
|
260
|
+
});
|
|
129
261
|
continue;
|
|
130
262
|
}
|
|
131
263
|
// If max_tokens, warn user and inject continuation prompt
|
|
132
264
|
if (stopReason === "max_tokens") {
|
|
133
265
|
status("\x1b[33m[response truncated: max_tokens reached, requesting continuation]\x1b[0m\n");
|
|
134
|
-
session.
|
|
266
|
+
session.log.append("user/message", {
|
|
267
|
+
message: { role: "user", content: "Your response was truncated due to length. Please continue where you left off." },
|
|
268
|
+
source: "system",
|
|
269
|
+
turn: session.turns,
|
|
270
|
+
});
|
|
135
271
|
continue;
|
|
136
272
|
}
|
|
137
273
|
// If no tool use, we're done
|
|
138
|
-
if (stopReason !== "tool_use")
|
|
274
|
+
if (stopReason !== "tool_use") {
|
|
275
|
+
endReason = "end_turn";
|
|
139
276
|
break;
|
|
277
|
+
}
|
|
140
278
|
// Execute tool calls with concurrency
|
|
141
279
|
const toolUseBlocks = assistantContent.filter((b) => b.type === "tool_use");
|
|
280
|
+
// Checkpoint BEFORE the mutating batch: the tool names are known now, and
|
|
281
|
+
// the snapshot must be the true pre-turn tree so /rewind can restore it.
|
|
282
|
+
const mutatingTools = new Set(["edit_file", "multi_edit", "apply_patch", "write_file"]);
|
|
283
|
+
const hasMutation = toolUseBlocks.some(b => mutatingTools.has(b.name));
|
|
284
|
+
if (hasMutation) {
|
|
285
|
+
createCheckpoint(process.cwd(), `turn-${session.turns}`);
|
|
286
|
+
}
|
|
142
287
|
// Log all tool calls upfront
|
|
143
288
|
if (hooks?.onToolStart) {
|
|
144
289
|
for (const block of toolUseBlocks)
|
|
@@ -151,26 +296,46 @@ export async function runTurn(userInput, session, config, hooks) {
|
|
|
151
296
|
if (!hooks?.onToolStart)
|
|
152
297
|
spinner.start(`Running ${toolUseBlocks.length} tool${toolUseBlocks.length > 1 ? "s" : ""}...`);
|
|
153
298
|
const { results: toolResults, toolCallCount } = await executeToolBlocks(toolUseBlocks, {
|
|
154
|
-
registry, verbose, status, hooks,
|
|
299
|
+
registry, verbose, status, hooks, signal,
|
|
155
300
|
antiPatterns: session.antiPatterns,
|
|
156
301
|
captureState: session.captureState,
|
|
157
302
|
phrenCtx: config.phrenCtx,
|
|
303
|
+
sessionId: config.sessionId,
|
|
304
|
+
repeatChain: session.repeatChain,
|
|
158
305
|
});
|
|
159
306
|
if (!hooks?.onToolStart)
|
|
160
307
|
spinner.stop();
|
|
161
308
|
session.toolCalls += toolCallCount;
|
|
162
309
|
turnToolCalls += toolCallCount;
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
|
|
310
|
+
// Only successful write/edit results justify checks; requested, denied,
|
|
311
|
+
// failed, or cancelled mutations must never launch a follow-up command.
|
|
312
|
+
const successfulMutation = toolUseBlocks.some((block) => mutatingTools.has(block.name)
|
|
313
|
+
&& toolResults.some((result) => result.type === "tool_result"
|
|
314
|
+
&& result.tool_use_id === block.id && !result.is_error));
|
|
315
|
+
if (successfulMutation && !signal?.aborted && config.lintTestConfig) {
|
|
316
|
+
const cwd = registry.permissionConfig.projectRoot;
|
|
168
317
|
const lintCmd = config.lintTestConfig.lintCmd ?? detectLintCommand(cwd);
|
|
169
318
|
const testCmd = config.lintTestConfig.testCmd ?? detectTestCommand(cwd);
|
|
170
319
|
const lintFailures = [];
|
|
171
|
-
for (const cmd of [lintCmd, testCmd].filter(Boolean)) {
|
|
172
|
-
|
|
173
|
-
|
|
320
|
+
for (const cmd of new Set([lintCmd, testCmd].filter(Boolean))) {
|
|
321
|
+
if (signal?.aborted)
|
|
322
|
+
break;
|
|
323
|
+
if (deniedChecks.has(cmd))
|
|
324
|
+
continue;
|
|
325
|
+
const input = { command: cmd, cwd, timeout: 60_000, description: "Verify the completed edit" };
|
|
326
|
+
hooks?.onToolStart?.("shell", input, 1);
|
|
327
|
+
// The same registry and scheduler preserve shell approval, hooks,
|
|
328
|
+
// kernel sandbox, secret scrubbing, timeout, and turn cancellation.
|
|
329
|
+
const [check] = await runToolsConcurrently([{
|
|
330
|
+
type: "tool_use", id: `post-edit-${session.turns}`, name: "shell", input,
|
|
331
|
+
}], registry, signal);
|
|
332
|
+
session.toolCalls++;
|
|
333
|
+
turnToolCalls++;
|
|
334
|
+
if (!check.cancelled)
|
|
335
|
+
hooks?.onToolEnd?.("shell", input, check.output, check.is_error, check.durationMs);
|
|
336
|
+
if (check.permissionDenied)
|
|
337
|
+
deniedChecks.add(cmd);
|
|
338
|
+
if (check.is_error) {
|
|
174
339
|
if (verbose)
|
|
175
340
|
status(`\x1b[33m[post-edit check failed: ${cmd}]\x1b[0m\n`);
|
|
176
341
|
lintFailures.push(`Post-edit check failed (${cmd}):\n${check.output.slice(0, 2000)}`);
|
|
@@ -184,16 +349,21 @@ export async function runTurn(userInput, session, config, hooks) {
|
|
|
184
349
|
});
|
|
185
350
|
}
|
|
186
351
|
}
|
|
187
|
-
// Create checkpoint before mutating tool results are committed to conversation
|
|
188
|
-
if (hasMutation) {
|
|
189
|
-
createCheckpoint(process.cwd(), `turn-${session.turns}`);
|
|
190
|
-
}
|
|
191
352
|
// Add tool results as a user message
|
|
192
|
-
session.
|
|
353
|
+
session.log.append("tool/results", {
|
|
354
|
+
message: { role: "user", content: toolResults },
|
|
355
|
+
turn: session.turns,
|
|
356
|
+
});
|
|
357
|
+
hooks?.onToolResults?.(toolResults);
|
|
193
358
|
// Steering input injection (TUI mid-turn input)
|
|
194
359
|
const steer = hooks?.getSteeringInput?.();
|
|
195
360
|
if (steer) {
|
|
196
|
-
session.
|
|
361
|
+
resetRepeatChain(session.repeatChain);
|
|
362
|
+
session.log.append("user/message", {
|
|
363
|
+
message: { role: "user", content: steer },
|
|
364
|
+
source: "steer",
|
|
365
|
+
turn: session.turns,
|
|
366
|
+
});
|
|
197
367
|
}
|
|
198
368
|
}
|
|
199
369
|
// Extract text from the last assistant message in this turn
|
|
@@ -208,7 +378,10 @@ export async function runTurn(userInput, session, config, hooks) {
|
|
|
208
378
|
else if (lastAssistant && typeof lastAssistant.content === "string") {
|
|
209
379
|
text = lastAssistant.content;
|
|
210
380
|
}
|
|
211
|
-
|
|
381
|
+
if (hookConfig) {
|
|
382
|
+
await runLifecycleHooks(hookConfig, "Stop", {});
|
|
383
|
+
}
|
|
384
|
+
return { text, turns: session.turns - turnStart, toolCalls: turnToolCalls, stopReason: signal?.aborted ? "aborted" : endReason };
|
|
212
385
|
}
|
|
213
386
|
export async function runAgent(task, config) {
|
|
214
387
|
const contextLimit = config.provider.contextWindow ?? 200_000;
|
|
@@ -220,5 +393,6 @@ export async function runAgent(task, config) {
|
|
|
220
393
|
toolCalls: result.toolCalls,
|
|
221
394
|
totalCost: config.costTracker?.formatCost(),
|
|
222
395
|
messages: session.messages,
|
|
396
|
+
session,
|
|
223
397
|
};
|
|
224
398
|
}
|