@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
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Loop-hygiene guard: detects runs of consecutive tool calls with identical
3
+ * canonicalized arguments and appends an escalating reminder to the tool
4
+ * result so the model breaks out of the loop itself.
5
+ *
6
+ * Advisory only — it never blocks or delays a call, and a legitimately
7
+ * repeated call just carries a note. Counting happens post-execution so
8
+ * denied/failed calls count too: a model hammering a denied call is exactly
9
+ * the loop worth breaking. A direct user interjection resets the chain
10
+ * (repetition across it is not a loop).
11
+ */
12
+ /** Consecutive-run lengths that trigger a reminder. */
13
+ export const REPEAT_THRESHOLDS = [3, 5, 8];
14
+ /** Cap on canonical arguments quoted in the detailed reminder. */
15
+ const ARGUMENTS_PREVIEW_CHARS = 500;
16
+ export function createRepeatChain() {
17
+ return { key: null, count: 0 };
18
+ }
19
+ /** Deep key-sort so argument objects differing only in property order match. */
20
+ function sortJsonValue(value) {
21
+ if (Array.isArray(value))
22
+ return value.map(sortJsonValue);
23
+ if (value !== null && typeof value === "object") {
24
+ const record = value;
25
+ const sorted = {};
26
+ for (const key of Object.keys(record).sort()) {
27
+ sorted[key] = sortJsonValue(record[key]);
28
+ }
29
+ return sorted;
30
+ }
31
+ return value;
32
+ }
33
+ /** Canonical string form of a call's arguments. */
34
+ export function canonicalizeArgs(input) {
35
+ return JSON.stringify(sortJsonValue(input)) ?? "null";
36
+ }
37
+ /** Chain key: the tool plus its full canonical arguments. */
38
+ export function chainKey(toolName, input) {
39
+ return JSON.stringify([toolName, canonicalizeArgs(input)]);
40
+ }
41
+ /** Reset on user-authored input (direct prompt or steering). */
42
+ export function resetRepeatChain(state) {
43
+ state.key = null;
44
+ state.count = 0;
45
+ }
46
+ /**
47
+ * Record one executed call and return the reminder to append to its result,
48
+ * if a threshold was crossed. The preview cap bounds only the reminder text —
49
+ * detection always compares full canonical arguments.
50
+ */
51
+ export function recordCall(state, toolName, input) {
52
+ const key = chainKey(toolName, input);
53
+ if (state.key === key) {
54
+ state.count++;
55
+ }
56
+ else {
57
+ state.key = key;
58
+ state.count = 1;
59
+ }
60
+ if (!REPEAT_THRESHOLDS.includes(state.count))
61
+ return null;
62
+ if (state.count === REPEAT_THRESHOLDS[0]) {
63
+ return ("\n\n[repeat-call notice] You are repeating the exact same tool call with identical arguments. " +
64
+ "Carefully analyze the previous result before calling again: if the task is not complete, " +
65
+ "try a different approach or different arguments instead of repeating the call.");
66
+ }
67
+ const canonical = canonicalizeArgs(input);
68
+ const preview = canonical.length > ARGUMENTS_PREVIEW_CHARS
69
+ ? `${canonical.slice(0, ARGUMENTS_PREVIEW_CHARS)}… (${canonical.length - ARGUMENTS_PREVIEW_CHARS} chars omitted)`
70
+ : canonical;
71
+ return (`\n\n[repeat-call notice] This is call ${state.count} of "${toolName}" in a row with identical arguments: ${preview}\n` +
72
+ "The repeated calls are not making progress. Do not call this tool with these exact arguments again. " +
73
+ "Inspect the latest result and choose a different action, different arguments, or finish the task if " +
74
+ "enough evidence has been gathered.");
75
+ }
@@ -0,0 +1,115 @@
1
+ const SUBTYPE = {
2
+ end_turn: "success",
3
+ max_turns: "error_max_turns",
4
+ budget: "error_budget",
5
+ plan_rejected: "error_plan_rejected",
6
+ aborted: "cancelled",
7
+ };
8
+ export function buildHeadlessResult(opts) {
9
+ const subtype = opts.stopReason === "error" ? "error_during_execution" : SUBTYPE[opts.stopReason];
10
+ const tracker = opts.costTracker;
11
+ return {
12
+ type: "result",
13
+ subtype,
14
+ is_error: subtype !== "success",
15
+ result: opts.text,
16
+ num_turns: opts.turns,
17
+ tool_calls: opts.toolCalls,
18
+ duration_ms: Date.now() - opts.startedAt,
19
+ session_id: opts.sessionId,
20
+ provider: opts.provider,
21
+ model: opts.model,
22
+ usage: { input_tokens: tracker?.totalInputTokens ?? 0, output_tokens: tracker?.totalOutputTokens ?? 0 },
23
+ total_cost_usd: tracker?.metered ? Number(tracker.totalCost.toFixed(6)) : null,
24
+ permission_denials: opts.permissionDenials,
25
+ ...(opts.error ? { error: opts.error } : {}),
26
+ };
27
+ }
28
+ /** Exit status for a headless run: 0 only when the task finished normally. */
29
+ export function headlessExitCode(result) {
30
+ if (result.subtype === "success")
31
+ return 0;
32
+ if (result.subtype === "cancelled")
33
+ return 130;
34
+ return 1;
35
+ }
36
+ function textOf(content) {
37
+ return content
38
+ .filter((b) => b.type === "text")
39
+ .map((b) => b.text)
40
+ .join("\n");
41
+ }
42
+ function resultText(block) {
43
+ if (block.type !== "tool_result")
44
+ return "";
45
+ if (typeof block.content === "string")
46
+ return block.content;
47
+ return block.content.map((c) => (c.type === "text" ? c.text : `[${c.type}]`)).join("\n");
48
+ }
49
+ const MAX_EVENT_OUTPUT = 4000;
50
+ /**
51
+ * Turn hooks that keep stdout clean. `write` receives complete stdout lines
52
+ * (stream-json events); text and json formats print once, at the end.
53
+ */
54
+ export function createHeadlessHooks(opts) {
55
+ const stderr = opts.stderr ?? ((t) => process.stderr.write(t));
56
+ const emit = (event) => {
57
+ if (opts.format === "stream-json")
58
+ opts.write(JSON.stringify(event));
59
+ };
60
+ const toolNames = new Map();
61
+ return {
62
+ onTextDelta: () => { },
63
+ onTextBlock: () => { },
64
+ onReasoningDelta: opts.verbose ? (t) => stderr(`\x1b[2m${t}\x1b[0m`) : () => { },
65
+ onStatus: (msg) => stderr(msg),
66
+ onToolStart: (name, input) => {
67
+ if (opts.verbose)
68
+ stderr(`→ ${name} ${JSON.stringify(input).slice(0, 200)}\n`);
69
+ },
70
+ onToolEnd: (name, _input, output, isError, durationMs) => {
71
+ if (opts.verbose)
72
+ stderr(`← ${name}${isError ? " (error)" : ""} ${durationMs}ms ${output.split("\n")[0].slice(0, 160)}\n`);
73
+ },
74
+ onAssistantMessage: (content, stopReason) => {
75
+ const text = textOf(content);
76
+ if (text)
77
+ emit({ type: "assistant", text, stop_reason: stopReason });
78
+ for (const block of content) {
79
+ if (block.type !== "tool_use")
80
+ continue;
81
+ toolNames.set(block.id, block.name);
82
+ emit({ type: "tool_use", id: block.id, name: block.name, input: block.input });
83
+ }
84
+ },
85
+ onToolResults: (results) => {
86
+ for (const block of results) {
87
+ if (block.type !== "tool_result")
88
+ continue;
89
+ const output = resultText(block);
90
+ emit({
91
+ type: "tool_result",
92
+ tool_use_id: block.tool_use_id,
93
+ name: toolNames.get(block.tool_use_id) ?? null,
94
+ is_error: !!block.is_error,
95
+ output: output.length > MAX_EVENT_OUTPUT ? `${output.slice(0, MAX_EVENT_OUTPUT)}… [${output.length} chars]` : output,
96
+ });
97
+ }
98
+ },
99
+ // No one can review a plan: stop after presenting it.
100
+ onPlanApproval: async () => ({ approved: false }),
101
+ };
102
+ }
103
+ /** Parse --output-format; null for an unknown value. */
104
+ export function parseOutputFormat(raw) {
105
+ if (raw === "text" || raw === "json" || raw === "stream-json")
106
+ return raw;
107
+ return null;
108
+ }
109
+ /** Read the whole of stdin (for `echo task | phren-agent -p`). */
110
+ export async function readStdin(stream = process.stdin) {
111
+ const chunks = [];
112
+ for await (const chunk of stream)
113
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
114
+ return Buffer.concat(chunks).toString("utf-8");
115
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Lifecycle reports to Phren Hook when phren-agent runs inside a Herdr pane,
3
+ * or a tmux pane on a computer without Herdr.
4
+ *
5
+ * Codex, Claude Code and Copilot deliver these through their own hook
6
+ * settings (`phren bridge install` edits them); phren-agent has no settings
7
+ * file, so it calls the installed hook bundle itself with the same JSON on
8
+ * stdin. That is what binds this session's event log to the pane the iPhone
9
+ * is looking at. Strictly best effort: no Herdr, no bundle, or a slow bundle
10
+ * must never slow down or fail a turn.
11
+ */
12
+ import { spawn } from "node:child_process";
13
+ import * as fs from "node:fs";
14
+ import * as os from "node:os";
15
+ import * as path from "node:path";
16
+ const HOOK_TIMEOUT_MS = 3000;
17
+ /** The bundle to call, or null when this process is in neither a Herdr nor a
18
+ * tmux pane, or nothing is installed. The Hook finds the pane from the same
19
+ * variables; inside Herdr only Herdr's pane counts. */
20
+ export function herdrHookBundle(env = process.env) {
21
+ const herdr = env.HERDR_ENV === "1" && !!env.HERDR_PANE_ID;
22
+ const tmux = env.HERDR_ENV !== "1" && !!env.TMUX && !!env.TMUX_PANE;
23
+ if (!herdr && !tmux)
24
+ return null;
25
+ const root = env.PHREN_BRIDGE_HOME || path.join(os.homedir(), ".local/share/phren/bridge");
26
+ const bundle = path.join(root, "current/bridge-hook.mjs");
27
+ try {
28
+ return fs.statSync(bundle).isFile() ? bundle : null;
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ function defaultRunner(command, args, stdin) {
35
+ const child = spawn(command, args, { stdio: ["pipe", "ignore", "ignore"], env: process.env });
36
+ const timer = setTimeout(() => child.kill(), HOOK_TIMEOUT_MS);
37
+ timer.unref();
38
+ child.on("error", () => clearTimeout(timer));
39
+ child.on("exit", () => clearTimeout(timer));
40
+ child.unref();
41
+ child.stdin.on("error", () => { });
42
+ child.stdin.end(stdin);
43
+ }
44
+ let currentSession = null;
45
+ /** The session whose event log later reports name. Set once at startup. */
46
+ export function setHerdrHookSession(sessionId) {
47
+ currentSession = sessionId;
48
+ }
49
+ /**
50
+ * Fire-and-forget one lifecycle event for the current session. Returns the
51
+ * payload that was sent, or null when nothing was (no session, not under
52
+ * Herdr, no bundle) — so callers and tests can see what happened without
53
+ * awaiting anything.
54
+ */
55
+ export function emitHerdrHook(event, options = {}) {
56
+ const sessionId = options.sessionId ?? currentSession;
57
+ if (!sessionId)
58
+ return null;
59
+ const env = options.env ?? process.env;
60
+ const bundle = herdrHookBundle(env);
61
+ if (!bundle)
62
+ return null;
63
+ const payload = { hook_event_name: event, session_id: sessionId, cwd: options.cwd ?? process.cwd() };
64
+ try {
65
+ (options.runner ?? defaultRunner)(process.execPath, [bundle, "hook", "phren"], JSON.stringify(payload));
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ return payload;
71
+ }