@phren/agent 0.1.14 → 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 (112) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +86 -0
  3. package/dist/agent-loop/index.js +239 -65
  4. package/dist/agent-loop/stream.js +212 -29
  5. package/dist/agent-loop/types.js +15 -2
  6. package/dist/bin.js +0 -0
  7. package/dist/checkpoint.js +103 -22
  8. package/dist/commands/info.js +30 -15
  9. package/dist/commands/model.js +6 -2
  10. package/dist/commands/review.js +183 -0
  11. package/dist/commands/session.js +70 -7
  12. package/dist/commands.js +168 -12
  13. package/dist/config.js +87 -10
  14. package/dist/context/compactor.js +239 -0
  15. package/dist/context/pruner.js +39 -13
  16. package/dist/context/token-counter.js +33 -1
  17. package/dist/custom-commands.js +69 -0
  18. package/dist/guards/repeat-tool-reminder.js +75 -0
  19. package/dist/headless.js +115 -0
  20. package/dist/herdr-hooks.js +71 -0
  21. package/dist/index.js +351 -48
  22. package/dist/mcp-client.js +434 -73
  23. package/dist/mcp-oauth.js +121 -0
  24. package/dist/memory/anti-patterns.js +7 -3
  25. package/dist/memory/auto-capture.js +7 -3
  26. package/dist/memory/context.js +92 -73
  27. package/dist/memory/project-context.js +24 -5
  28. package/dist/memory/provenance.js +15 -0
  29. package/dist/memory/review-triage.js +166 -0
  30. package/dist/memory/session.js +36 -1
  31. package/dist/models.js +152 -19
  32. package/dist/multi/child-entry.js +65 -10
  33. package/dist/multi/diff-renderer.js +3 -3
  34. package/dist/multi/markdown.js +125 -27
  35. package/dist/multi/provider-manager.js +8 -0
  36. package/dist/multi/publish.js +72 -0
  37. package/dist/multi/spawner.js +45 -4
  38. package/dist/multi/syntax-highlight.js +25 -4
  39. package/dist/multi/types.js +1 -1
  40. package/dist/permissions/allowlist.js +86 -13
  41. package/dist/permissions/checker.js +42 -7
  42. package/dist/permissions/kernel-sandbox.js +197 -0
  43. package/dist/permissions/prompt.js +10 -1
  44. package/dist/permissions/sandbox.js +40 -17
  45. package/dist/providers/anthropic.js +154 -7
  46. package/dist/providers/codex-auth.js +28 -0
  47. package/dist/providers/codex.js +134 -23
  48. package/dist/providers/history.js +35 -0
  49. package/dist/providers/ollama.js +37 -6
  50. package/dist/providers/openai-compat.js +171 -74
  51. package/dist/providers/openrouter.js +47 -17
  52. package/dist/providers/replay.js +62 -0
  53. package/dist/providers/resolve.js +41 -7
  54. package/dist/providers/retry.js +38 -5
  55. package/dist/providers/types.js +9 -1
  56. package/dist/repl.js +47 -5
  57. package/dist/session/log.js +217 -0
  58. package/dist/session/persist.js +190 -0
  59. package/dist/settings.js +42 -26
  60. package/dist/system-prompt.js +18 -2
  61. package/dist/tools/apply-patch.js +355 -0
  62. package/dist/tools/edit-engine.js +287 -0
  63. package/dist/tools/edit-file.js +86 -27
  64. package/dist/tools/grep.js +25 -10
  65. package/dist/tools/lint-test.js +0 -22
  66. package/dist/tools/mcp-resources.js +51 -6
  67. package/dist/tools/phren-finding.js +12 -4
  68. package/dist/tools/phren-search.js +7 -2
  69. package/dist/tools/read-file.js +37 -9
  70. package/dist/tools/read-image.js +76 -0
  71. package/dist/tools/registry.js +27 -5
  72. package/dist/tools/shell.js +134 -71
  73. package/dist/tools/skill.js +20 -20
  74. package/dist/tools/spawn-agent.js +77 -13
  75. package/dist/tools/update-plan.js +48 -0
  76. package/dist/tools/web-fetch.js +110 -12
  77. package/dist/tools/web-search.js +4 -4
  78. package/dist/tui/components/App.js +98 -26
  79. package/dist/tui/components/ApprovalPanel.js +8 -0
  80. package/dist/tui/components/InputArea.js +5 -5
  81. package/dist/tui/components/ModelPicker.js +43 -0
  82. package/dist/tui/components/PhrenInput.js +10 -5
  83. package/dist/tui/components/PlanReview.js +7 -0
  84. package/dist/tui/components/ShortcutHelp.js +5 -0
  85. package/dist/tui/components/StatusBar.js +46 -20
  86. package/dist/tui/components/SteerQueue.js +1 -1
  87. package/dist/tui/components/ThinkingIndicator.js +6 -4
  88. package/dist/tui/components/ToolCall.js +10 -4
  89. package/dist/tui/components/ToolDetail.js +21 -0
  90. package/dist/tui/help.js +6 -0
  91. package/dist/tui/hooks/useKeyboardShortcuts.js +15 -1
  92. package/dist/tui/index.js +0 -1
  93. package/dist/tui/ink-entry.js +317 -33
  94. package/dist/tui/tool-render.js +1 -1
  95. package/dist/user-hooks.js +171 -0
  96. package/package.json +18 -12
  97. package/dist/multi/multi-commands.js +0 -170
  98. package/dist/multi/multi-events.js +0 -98
  99. package/dist/multi/multi-render.js +0 -147
  100. package/dist/multi/pane.js +0 -28
  101. package/dist/multi/tui-multi.js +0 -200
  102. package/dist/permissions/privacy.js +0 -248
  103. package/dist/tui/components/AgentMessage.js +0 -5
  104. package/dist/tui/components/ChatMessage.js +0 -23
  105. package/dist/tui/components/CodeBlock.js +0 -8
  106. package/dist/tui/components/Separator.js +0 -7
  107. package/dist/tui/components/StreamingText.js +0 -5
  108. package/dist/tui/components/UserMessage.js +0 -5
  109. package/dist/tui/menu-mode.js +0 -86
  110. package/dist/tui/mouse.js +0 -71
  111. package/dist/tui/terminal-control.js +0 -62
  112. package/dist/tui.js +0 -781
@@ -1,200 +0,0 @@
1
- /** Multiplexed TUI for multi-agent orchestration. */
2
- import * as readline from "node:readline";
3
- import { MAX_SCROLLBACK, createPane, appendToPane } from "./pane.js";
4
- import { ESC, s, render } from "./multi-render.js";
5
- import { handleSlashCommand } from "./multi-commands.js";
6
- import { wireSpawnerEvents } from "./multi-events.js";
7
- // ── Main TUI ─────────────────────────────────────────────────────────────────
8
- export async function startMultiTui(spawner, config) {
9
- const w = process.stdout;
10
- const panes = new Map();
11
- let selectedId = null;
12
- let inputLine = "";
13
- let scrollOffset = 0;
14
- // Ordered list of agent IDs for tab navigation
15
- const agentOrder = [];
16
- // ── Pane management ────────────────────────────────────────────────────
17
- function getOrCreatePane(agentId) {
18
- let pane = panes.get(agentId);
19
- if (!pane) {
20
- const agent = spawner.getAgent(agentId);
21
- const name = agent?.task.slice(0, 20) ?? agentId;
22
- pane = createPane(agentId, name);
23
- panes.set(agentId, pane);
24
- if (!agentOrder.includes(agentId)) {
25
- agentOrder.push(agentId);
26
- }
27
- // Auto-select first agent
28
- if (!selectedId) {
29
- selectedId = agentId;
30
- }
31
- }
32
- return pane;
33
- }
34
- function selectAgent(agentId) {
35
- if (panes.has(agentId)) {
36
- selectedId = agentId;
37
- scrollOffset = 0;
38
- doRender();
39
- }
40
- }
41
- function selectByIndex(index) {
42
- if (index >= 0 && index < agentOrder.length) {
43
- selectAgent(agentOrder[index]);
44
- }
45
- }
46
- function cycleAgent(direction) {
47
- if (agentOrder.length === 0)
48
- return;
49
- const currentIdx = selectedId ? agentOrder.indexOf(selectedId) : -1;
50
- let next = currentIdx + direction;
51
- if (next < 0)
52
- next = agentOrder.length - 1;
53
- if (next >= agentOrder.length)
54
- next = 0;
55
- selectAgent(agentOrder[next]);
56
- }
57
- function doRender() {
58
- render(w, spawner, panes, selectedId, scrollOffset, inputLine);
59
- }
60
- // ── Command context for slash commands ────────────────────────────────
61
- function getCmdCtx() {
62
- return {
63
- spawner,
64
- config,
65
- panes,
66
- agentOrder,
67
- selectedId,
68
- setSelectedId: (id) => { selectedId = id; },
69
- getOrCreatePane,
70
- render: doRender,
71
- };
72
- }
73
- // ── Spawner event wiring ───────────────────────────────────────────────
74
- wireSpawnerEvents(spawner, {
75
- panes,
76
- getOrCreatePane,
77
- getSelectedId: () => selectedId,
78
- render: doRender,
79
- });
80
- // ── Terminal setup ─────────────────────────────────────────────────────
81
- // Enter alternate screen
82
- w.write("\x1b[?1049h");
83
- if (process.stdin.isTTY) {
84
- readline.emitKeypressEvents(process.stdin);
85
- process.stdin.setRawMode(true);
86
- }
87
- function cleanup() {
88
- w.write("\x1b[?1049l"); // leave alternate screen
89
- w.write(`${ESC}?25h`); // show cursor
90
- if (process.stdin.isTTY) {
91
- try {
92
- process.stdin.setRawMode(false);
93
- }
94
- catch { }
95
- }
96
- }
97
- // ── Promise-based lifecycle ────────────────────────────────────────────
98
- return new Promise((resolve) => {
99
- async function shutdown() {
100
- cleanup();
101
- w.write(s.dim("Shutting down agents...\n"));
102
- await spawner.shutdown();
103
- w.write(s.dim("All agents stopped.\n"));
104
- resolve();
105
- }
106
- // ── Keypress handler ─────────────────────────────────────────────────
107
- process.stdin.on("keypress", (_ch, key) => {
108
- if (!key)
109
- return;
110
- // Ctrl+D — exit
111
- if (key.ctrl && key.name === "d") {
112
- shutdown();
113
- return;
114
- }
115
- // Ctrl+C — clear input or exit if empty
116
- if (key.ctrl && key.name === "c") {
117
- if (inputLine.length > 0) {
118
- inputLine = "";
119
- doRender();
120
- }
121
- else {
122
- shutdown();
123
- }
124
- return;
125
- }
126
- // Number keys 1-9 — select agent
127
- if (!key.ctrl && !key.meta && key.sequence && /^[1-9]$/.test(key.sequence) && inputLine.length === 0) {
128
- selectByIndex(parseInt(key.sequence, 10) - 1);
129
- return;
130
- }
131
- // Ctrl+Left/Right — cycle agents
132
- if (key.ctrl && key.name === "left") {
133
- cycleAgent(-1);
134
- return;
135
- }
136
- if (key.ctrl && key.name === "right") {
137
- cycleAgent(1);
138
- return;
139
- }
140
- // Page Up/Down — scroll
141
- if (key.name === "pageup") {
142
- const availRows = (process.stdout.rows || 24) - 3;
143
- scrollOffset = Math.min(scrollOffset + Math.floor(availRows / 2), MAX_SCROLLBACK);
144
- doRender();
145
- return;
146
- }
147
- if (key.name === "pagedown") {
148
- const availRows = (process.stdout.rows || 24) - 3;
149
- scrollOffset = Math.max(0, scrollOffset - Math.floor(availRows / 2));
150
- doRender();
151
- return;
152
- }
153
- // Enter — submit input
154
- if (key.name === "return") {
155
- const line = inputLine.trim();
156
- inputLine = "";
157
- if (!line) {
158
- doRender();
159
- return;
160
- }
161
- if (line.startsWith("/")) {
162
- if (handleSlashCommand(line, getCmdCtx())) {
163
- doRender();
164
- return;
165
- }
166
- }
167
- // Send as text to currently selected agent's pane
168
- if (selectedId && panes.has(selectedId)) {
169
- const pane = panes.get(selectedId);
170
- appendToPane(pane, s.cyan(`> ${line}`) + "\n");
171
- }
172
- doRender();
173
- return;
174
- }
175
- // Backspace
176
- if (key.name === "backspace") {
177
- if (inputLine.length > 0) {
178
- inputLine = inputLine.slice(0, -1);
179
- doRender();
180
- }
181
- return;
182
- }
183
- // Regular character input
184
- if (key.sequence && !key.ctrl && !key.meta) {
185
- inputLine += key.sequence;
186
- doRender();
187
- }
188
- });
189
- // Handle terminal resize
190
- process.stdout.on("resize", () => doRender());
191
- // Register panes for any agents that already exist
192
- for (const agent of spawner.listAgents()) {
193
- getOrCreatePane(agent.id);
194
- }
195
- if (agentOrder.length > 0) {
196
- selectedId = agentOrder[0];
197
- }
198
- doRender();
199
- });
200
- }
@@ -1,248 +0,0 @@
1
- /**
2
- * Privacy safeguards — scrub sensitive data from tool outputs, findings, and LLM context.
3
- *
4
- * Prevents accidental leakage of:
5
- * - API keys and tokens in tool output (e.g., from reading .env files)
6
- * - Passwords and connection strings
7
- * - PII patterns (emails, IPs shown in logs)
8
- * - Private keys and certificates
9
- *
10
- * Applied at three layers:
11
- * 1. Tool output → before sending to LLM (scrubToolOutput)
12
- * 2. Findings → before saving to phren (scrubFinding)
13
- * 3. Session summaries → before persisting (scrubSummary)
14
- */
15
- // ── Secret patterns ──────────────────────────────────────────────────────
16
- /** Patterns that match common API key/token formats. */
17
- const SECRET_PATTERNS = [
18
- // Generic API keys (long hex/base64 strings prefixed by common env var names)
19
- { pattern: /(?:api[_-]?key|api[_-]?secret|api[_-]?token)\s*[:=]\s*["']?([A-Za-z0-9_\-/.+=]{20,})["']?/gi, label: "API_KEY" },
20
- // AWS keys
21
- { pattern: /AKIA[0-9A-Z]{16}/g, label: "AWS_ACCESS_KEY" },
22
- { pattern: /(?:aws[_-]?secret[_-]?access[_-]?key)\s*[:=]\s*["']?([A-Za-z0-9/+=]{30,})["']?/gi, label: "AWS_SECRET" },
23
- // Bearer tokens
24
- { pattern: /Bearer\s+[A-Za-z0-9_\-/.+=]{20,}/g, label: "BEARER_TOKEN" },
25
- // GitHub tokens
26
- { pattern: /gh[pousr]_[A-Za-z0-9_]{36,}/g, label: "GITHUB_TOKEN" },
27
- // Anthropic keys
28
- { pattern: /sk-ant-[A-Za-z0-9_\-]{20,}/g, label: "ANTHROPIC_KEY" },
29
- // OpenAI keys
30
- { pattern: /sk-[A-Za-z0-9]{20,}/g, label: "OPENAI_KEY" },
31
- // Generic password assignments
32
- { pattern: /(?:password|passwd|pwd)\s*[:=]\s*["']?([^\s"']{8,})["']?/gi, label: "PASSWORD" },
33
- // Connection strings with passwords
34
- { pattern: /:\/\/[^:]+:([^@\s]{8,})@/g, label: "CONNECTION_PASSWORD" },
35
- // Private key blocks
36
- { pattern: /-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----[\s\S]*?-----END\s+(?:RSA\s+)?PRIVATE\s+KEY-----/g, label: "PRIVATE_KEY" },
37
- // JWT tokens
38
- { pattern: /eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, label: "JWT" },
39
- // Slack tokens
40
- { pattern: /xox[bpras]-[0-9]{10,}-[A-Za-z0-9-]+/g, label: "SLACK_TOKEN" },
41
- // Env variable assignments with secret-ish names
42
- { pattern: /(?:SECRET|TOKEN|PASSWORD|PRIVATE_KEY|AUTH|CREDENTIAL)[A-Z_]*\s*=\s*["']?([^\s"']{8,})["']?/gi, label: "SECRET_VAR" },
43
- ];
44
- /** Patterns for PII that shouldn't be stored in findings. */
45
- const PII_PATTERNS = [
46
- // Email addresses (only redact in contexts where they're likely PII, not code)
47
- { pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, label: "EMAIL" },
48
- // IP addresses (v4) — only in log-like contexts
49
- { pattern: /\b(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)){3}\b/g, label: "IP_ADDRESS" },
50
- ];
51
- // ── Scrubbing functions ──────────────────────────────────────────────────
52
- /**
53
- * Scrub sensitive data from tool output before it's sent to the LLM.
54
- * This is the primary privacy gate — catches secrets in file reads, command output, etc.
55
- */
56
- export function scrubToolOutput(toolName, output) {
57
- // Don't scrub short outputs (unlikely to contain full secrets)
58
- if (output.length < 20)
59
- return output;
60
- let scrubbed = output;
61
- for (const { pattern, label } of SECRET_PATTERNS) {
62
- // Reset regex state for global patterns
63
- pattern.lastIndex = 0;
64
- scrubbed = scrubbed.replace(pattern, `[REDACTED:${label}]`);
65
- }
66
- return scrubbed;
67
- }
68
- /**
69
- * Check if a string contains likely secrets. Returns true if secrets detected.
70
- * Use this as a gate before saving to persistent storage.
71
- */
72
- export function containsSecrets(text) {
73
- for (const { pattern } of SECRET_PATTERNS) {
74
- pattern.lastIndex = 0;
75
- if (pattern.test(text))
76
- return true;
77
- }
78
- return false;
79
- }
80
- /**
81
- * Scrub sensitive data from a finding before saving to phren.
82
- * More aggressive than tool output scrubbing — also catches PII.
83
- */
84
- export function scrubFinding(finding) {
85
- let scrubbed = finding;
86
- // Secret patterns
87
- for (const { pattern, label } of SECRET_PATTERNS) {
88
- pattern.lastIndex = 0;
89
- scrubbed = scrubbed.replace(pattern, `[REDACTED:${label}]`);
90
- }
91
- // PII patterns (only in findings, not tool outputs where they may be needed)
92
- for (const { pattern, label } of PII_PATTERNS) {
93
- pattern.lastIndex = 0;
94
- scrubbed = scrubbed.replace(pattern, `[REDACTED:${label}]`);
95
- }
96
- return scrubbed;
97
- }
98
- /**
99
- * Scrub a session summary before persisting.
100
- */
101
- export function scrubSummary(summary) {
102
- return scrubFinding(summary);
103
- }
104
- /**
105
- * Check if tool output looks like it came from reading a sensitive file
106
- * (e.g., .env, credentials). Returns true if the content appears to be
107
- * mostly key-value secrets.
108
- */
109
- export function looksLikeSecretsFile(output) {
110
- const lines = output.split("\n").filter(l => l.trim() && !l.startsWith("#"));
111
- if (lines.length < 2)
112
- return false;
113
- let secretLines = 0;
114
- for (const line of lines) {
115
- // Count lines that look like KEY=secret_value
116
- if (/^[A-Z_]{2,}=\S+/.test(line)) {
117
- for (const { pattern } of SECRET_PATTERNS) {
118
- pattern.lastIndex = 0;
119
- if (pattern.test(line)) {
120
- secretLines++;
121
- break;
122
- }
123
- }
124
- }
125
- }
126
- // If >50% of non-comment lines are secrets, it's probably a secrets file
127
- return secretLines / lines.length > 0.5;
128
- }
129
- /**
130
- * Validate that a finding doesn't contain obvious secrets before saving.
131
- * Returns an error message if the finding should be rejected, null if OK.
132
- */
133
- export function validateFindingSafety(finding) {
134
- if (containsSecrets(finding)) {
135
- return "Finding contains detected secrets (API keys, tokens, passwords). Secrets should never be stored in findings. The sensitive values have been redacted.";
136
- }
137
- return null;
138
- }
139
- /**
140
- * Patterns that indicate prompt injection — text trying to override AI instructions.
141
- * Each entry: [regex, flag label].
142
- */
143
- const PROMPT_INJECTION_PATTERNS = [
144
- // Direct instruction override attempts
145
- [/\b(?:ignore|disregard|forget|override)\s+(?:all\s+)?(?:previous|prior|above|earlier|your|the|safety|system)\b/i, "prompt_injection:instruction_override"],
146
- [/\byou\s+(?:must|should|shall|will|are\s+(?:now|required\s+to))\b/i, "prompt_injection:directive"],
147
- [/\byour\s+new\s+(?:instructions?|role|purpose|directive)\b/i, "prompt_injection:role_reassignment"],
148
- [/\bas\s+an?\s+(?:AI|language\s+model|assistant|LLM)\b/i, "prompt_injection:identity_framing"],
149
- [/\bforget\s+everything\b/i, "prompt_injection:memory_wipe"],
150
- // System prompt markers (ChatML, Llama, etc.)
151
- [/\[INST\]|\[\/INST\]/i, "prompt_injection:chatml_inst"],
152
- [/<<SYS>>|<<\/SYS>>/i, "prompt_injection:llama_sys"],
153
- [/<\|im_start\|>|<\|im_end\|>/i, "prompt_injection:chatml_marker"],
154
- [/^system\s*:/im, "prompt_injection:system_prefix"],
155
- [/SYSTEM\s*:\s*you\s+are/i, "prompt_injection:system_role"],
156
- // Jailbreak-style keywords
157
- [/\b(?:DAN|do\s+anything\s+now|jailbreak)\b/i, "prompt_injection:jailbreak_keyword"],
158
- ];
159
- /**
160
- * Patterns for dangerous executable instructions embedded in findings.
161
- */
162
- const DANGEROUS_COMMAND_PATTERNS = [
163
- // Pipe-to-shell patterns
164
- [/\bcurl\s+[^\s|]*\s*\|\s*(?:sh|bash|zsh|eval)\b/i, "dangerous_command:curl_pipe_shell"],
165
- [/\bwget\s+[^\s|]*\s*\|\s*(?:sh|bash|zsh|eval)\b/i, "dangerous_command:wget_pipe_shell"],
166
- // Dangerous eval/exec
167
- [/\beval\s*\(\s*['"`].*['"`]\s*\)/i, "dangerous_command:eval_literal"],
168
- [/\bexec\s*\(\s*['"`].*['"`]\s*\)/i, "dangerous_command:exec_literal"],
169
- // Destructive commands
170
- [/\brm\s+-rf\s+[/~]/i, "dangerous_command:rm_rf_root"],
171
- [/\bdd\s+.*\bof=\/dev\//i, "dangerous_command:dd_device"],
172
- [/\bmkfs\b/i, "dangerous_command:mkfs"],
173
- // Instructions to always run dangerous commands
174
- [/\b(?:always|first)\s+run\s+[`"'].*(?:curl|wget|rm\s+-rf|chmod\s+777|sudo)/i, "dangerous_command:instruction_to_run"],
175
- ];
176
- /**
177
- * Patterns for authority/permission escalation claims.
178
- */
179
- const AUTHORITY_ESCALATION_PATTERNS = [
180
- [/\b(?:user|admin|owner)\s+has\s+(?:authorized|approved|granted|confirmed)\b/i, "authority_escalation:false_authorization"],
181
- [/\bfull\s+(?:access|permission|control)\s+(?:granted|given|enabled)\b/i, "authority_escalation:false_access"],
182
- [/\bskip\s+(?:validation|verification|safety|security|auth)\b/i, "authority_escalation:skip_safety"],
183
- [/\bno\s+need\s+to\s+(?:ask|confirm|verify|validate|check)\b/i, "authority_escalation:skip_confirmation"],
184
- [/\bauto[-\s]?(?:approve|accept|confirm)\s+(?:all|every)\b/i, "authority_escalation:auto_approve"],
185
- [/\bdisable\s+(?:safety|security|protection|guard|check|filter)\b/i, "authority_escalation:disable_safety"],
186
- ];
187
- /**
188
- * Patterns for self-replication — findings that instruct saving more findings.
189
- */
190
- const SELF_REPLICATION_PATTERNS = [
191
- [/\b(?:save|add|create|write|store|append)\s+(?:this\s+)?(?:finding|memory|memories|findings)\b/i, "self_replication:save_finding"],
192
- [/\badd_finding\b/i, "self_replication:tool_invocation"],
193
- [/\bremember\s+to\s+always\b/i, "self_replication:persistent_instruction"],
194
- [/\b(?:when|if)\s+you\s+see\s+this\b/i, "self_replication:conditional_trigger"],
195
- [/\bspread\s+(?:this|the)\s+(?:message|finding|memory)\b/i, "self_replication:spread_instruction"],
196
- ];
197
- /**
198
- * Check a finding for integrity issues — prompt injection, dangerous commands,
199
- * authority escalation, and self-replication attempts.
200
- *
201
- * Returns a structured result with risk level and triggered flags.
202
- * Risk levels:
203
- * - "none": no issues detected
204
- * - "low": one minor flag, likely benign but noted
205
- * - "medium": multiple flags or a single concerning pattern
206
- * - "high": strong prompt injection or dangerous command pattern
207
- */
208
- export function checkFindingIntegrity(finding) {
209
- const flags = [];
210
- // Check all pattern categories
211
- for (const [pattern, flag] of PROMPT_INJECTION_PATTERNS) {
212
- pattern.lastIndex = 0;
213
- if (pattern.test(finding))
214
- flags.push(flag);
215
- }
216
- for (const [pattern, flag] of DANGEROUS_COMMAND_PATTERNS) {
217
- pattern.lastIndex = 0;
218
- if (pattern.test(finding))
219
- flags.push(flag);
220
- }
221
- for (const [pattern, flag] of AUTHORITY_ESCALATION_PATTERNS) {
222
- pattern.lastIndex = 0;
223
- if (pattern.test(finding))
224
- flags.push(flag);
225
- }
226
- for (const [pattern, flag] of SELF_REPLICATION_PATTERNS) {
227
- pattern.lastIndex = 0;
228
- if (pattern.test(finding))
229
- flags.push(flag);
230
- }
231
- if (flags.length === 0) {
232
- return { safe: true, risk: "none", flags: [] };
233
- }
234
- // Determine risk level based on count and severity
235
- const hasHighSeverity = flags.some(f => f.startsWith("prompt_injection:") || f.startsWith("dangerous_command:") || f.startsWith("authority_escalation:disable_safety"));
236
- const hasMediumSeverity = flags.some(f => f.startsWith("authority_escalation:") || f.startsWith("self_replication:"));
237
- let risk;
238
- if (hasHighSeverity || flags.length >= 3) {
239
- risk = "high";
240
- }
241
- else if (hasMediumSeverity || flags.length >= 2) {
242
- risk = "medium";
243
- }
244
- else {
245
- risk = "low";
246
- }
247
- return { safe: risk !== "high", risk, flags };
248
- }
@@ -1,5 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Box, Text } from "ink";
3
- export function AgentMessage({ text }) {
4
- return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { color: "magenta", children: ["◆", " ", _jsx(Text, { children: text })] }), _jsx(Text, { children: "" })] }));
5
- }
@@ -1,23 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Box, Text } from "ink";
3
- import { formatToolInput, formatDuration } from "../tool-render.js";
4
- const COMPACT_LINES = 3;
5
- export function ChatMessage({ role, text, toolCalls }) {
6
- if (role === "user") {
7
- return (_jsxs(Box, { flexDirection: "column", marginBottom: 0, children: [_jsx(Text, { bold: true, children: "You: " }), _jsx(Text, { children: text })] }));
8
- }
9
- if (role === "system") {
10
- return (_jsx(Box, { marginBottom: 0, children: _jsx(Text, { dimColor: true, children: text }) }));
11
- }
12
- return (_jsxs(Box, { flexDirection: "column", marginBottom: 0, children: [_jsx(Text, { children: text }), toolCalls?.map((tc, i) => (_jsx(ToolCallLine, { ...tc }, i)))] }));
13
- }
14
- function ToolCallLine({ name, input, output, isError, durationMs }) {
15
- const preview = formatToolInput(name, input);
16
- const dur = formatDuration(durationMs);
17
- const icon = isError ? "✗" : "→";
18
- const iconColor = isError ? "red" : "green";
19
- const allLines = output.split("\n").filter(Boolean);
20
- const shown = allLines.slice(0, COMPACT_LINES);
21
- const overflow = allLines.length - COMPACT_LINES;
22
- return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [" ", _jsx(Text, { color: iconColor, children: icon }), " ", _jsx(Text, { bold: true, children: name }), " ", _jsx(Text, { color: "gray", children: preview }), " ", _jsx(Text, { dimColor: true, children: dur })] }), shown.map((line, j) => (_jsxs(Text, { dimColor: true, children: [" ", line.slice(0, (process.stdout.columns || 80) - 6)] }, j))), overflow > 0 && _jsxs(Text, { dimColor: true, children: [" ", "... +", overflow, " lines"] })] }));
23
- }
@@ -1,8 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Box, Text } from 'ink';
3
- import { highlightCode } from '../../multi/syntax-highlight.js';
4
- export function CodeBlock({ code, language }) {
5
- const lang = language || 'generic';
6
- const highlighted = highlightCode(code, lang);
7
- return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, children: [_jsx(Text, { dimColor: true, children: '```' + lang }), _jsx(Text, { children: highlighted }), _jsx(Text, { dimColor: true, children: '```' })] }));
8
- }
@@ -1,7 +0,0 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import { Text, useStdout } from "ink";
3
- export function Separator() {
4
- const { stdout } = useStdout();
5
- const columns = stdout?.columns || 80;
6
- return _jsx(Text, { dimColor: true, children: "\u2500".repeat(columns) });
7
- }
@@ -1,5 +0,0 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import { Text } from "ink";
3
- export function StreamingText({ text }) {
4
- return _jsx(Text, { children: text });
5
- }
@@ -1,5 +0,0 @@
1
- import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
- import { Box, Text } from "ink";
3
- export function UserMessage({ text }) {
4
- return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { bold: true, children: ["❯", " ", text] }), _jsx(Text, { children: "" })] }));
5
- }
@@ -1,86 +0,0 @@
1
- import { ESC, s } from "./ansi.js";
2
- let menuMod = null;
3
- export async function loadMenuModule() {
4
- if (!menuMod) {
5
- try {
6
- menuMod = await import("@phren/cli/shell/render-api");
7
- }
8
- catch {
9
- menuMod = null;
10
- }
11
- }
12
- return menuMod;
13
- }
14
- export async function renderMenu(ctx) {
15
- const mod = await loadMenuModule();
16
- if (!mod || !ctx.phrenCtx)
17
- return;
18
- const result = await mod.renderMenuFrame(ctx.phrenCtx.phrenPath, ctx.phrenCtx.profile, ctx.menuState);
19
- ctx.onStateChange(ctx.menuState, result.listCount, ctx.menuFilterActive, ctx.menuFilterBuf);
20
- // Full-screen write: single write to avoid flicker
21
- ctx.w.write(`${ESC}?25l${ESC}H${ESC}2J${result.output}${ESC}?25h`);
22
- }
23
- export function enterMenuMode(ctx) {
24
- if (!ctx.phrenCtx) {
25
- ctx.w.write(s.yellow(" phren not configured — menu unavailable\n"));
26
- return;
27
- }
28
- ctx.menuState.project = ctx.phrenCtx.project ?? ctx.menuState.project;
29
- ctx.w.write("\x1b[?1049h"); // enter alternate screen
30
- renderMenu(ctx);
31
- }
32
- export function exitMenuMode(ctx) {
33
- ctx.onStateChange(ctx.menuState, ctx.menuListCount, false, "");
34
- ctx.w.write("\x1b[?1049l"); // leave alternate screen (restores chat)
35
- ctx.onExit();
36
- }
37
- export async function handleMenuKeypress(key, ctx) {
38
- // Filter input mode: capture text for / search
39
- if (ctx.menuFilterActive) {
40
- if (key.name === "escape") {
41
- ctx.menuState = { ...ctx.menuState, filter: undefined, cursor: 0, scroll: 0 };
42
- ctx.onStateChange(ctx.menuState, ctx.menuListCount, false, "");
43
- renderMenu(ctx);
44
- return;
45
- }
46
- if (key.name === "return") {
47
- const filter = ctx.menuFilterBuf || undefined;
48
- ctx.menuState = { ...ctx.menuState, filter, cursor: 0, scroll: 0 };
49
- ctx.onStateChange(ctx.menuState, ctx.menuListCount, false, "");
50
- renderMenu(ctx);
51
- return;
52
- }
53
- if (key.name === "backspace") {
54
- const buf = ctx.menuFilterBuf.slice(0, -1);
55
- ctx.menuState = { ...ctx.menuState, filter: buf || undefined, cursor: 0 };
56
- ctx.onStateChange(ctx.menuState, ctx.menuListCount, ctx.menuFilterActive, buf);
57
- renderMenu(ctx);
58
- return;
59
- }
60
- if (key.sequence && !key.ctrl && !key.meta) {
61
- const buf = ctx.menuFilterBuf + key.sequence;
62
- ctx.menuState = { ...ctx.menuState, filter: buf, cursor: 0 };
63
- ctx.onStateChange(ctx.menuState, ctx.menuListCount, ctx.menuFilterActive, buf);
64
- renderMenu(ctx);
65
- }
66
- return;
67
- }
68
- // "/" starts filter input
69
- if (key.sequence === "/") {
70
- ctx.onStateChange(ctx.menuState, ctx.menuListCount, true, "");
71
- return;
72
- }
73
- const mod = await loadMenuModule();
74
- if (!mod) {
75
- exitMenuMode(ctx);
76
- return;
77
- }
78
- const newState = mod.handleMenuKey(ctx.menuState, key.name ?? "", ctx.menuListCount, ctx.phrenCtx?.phrenPath, ctx.phrenCtx?.profile);
79
- if (newState === null) {
80
- exitMenuMode(ctx);
81
- }
82
- else {
83
- ctx.menuState = newState;
84
- renderMenu(ctx);
85
- }
86
- }
package/dist/tui/mouse.js DELETED
@@ -1,71 +0,0 @@
1
- /**
2
- * Mouse support — SGR extended mode for terminal mouse events.
3
- * Enables click detection for agent tab switching and hyperlink clicks.
4
- */
5
- /**
6
- * Enable mouse tracking on the terminal.
7
- * Uses SGR extended mode (\x1b[?1006h) for coordinates > 223.
8
- * Also enables normal tracking (\x1b[?1000h) for basic button events.
9
- */
10
- export function enableMouse(stdout) {
11
- if (!stdout.isTTY)
12
- return;
13
- stdout.write("\x1b[?1000h"); // Normal tracking (button press/release)
14
- stdout.write("\x1b[?1006h"); // SGR extended mode
15
- }
16
- /** Disable mouse tracking and restore normal terminal behavior. */
17
- export function disableMouse(stdout) {
18
- if (!stdout.isTTY)
19
- return;
20
- stdout.write("\x1b[?1006l");
21
- stdout.write("\x1b[?1000l");
22
- }
23
- /**
24
- * Try to parse an SGR mouse event from raw input.
25
- * SGR format: \x1b[<button;column;row(M|m)
26
- * M = press, m = release
27
- * Returns null if the input is not a mouse event.
28
- */
29
- export function parseMouseEvent(input) {
30
- // SGR extended: \x1b[<Cb;Cx;CyM or \x1b[<Cb;Cx;Cym
31
- const match = input.match(/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/);
32
- if (!match)
33
- return null;
34
- const code = parseInt(match[1], 10);
35
- const x = parseInt(match[2], 10);
36
- const y = parseInt(match[3], 10);
37
- const isRelease = match[4] === "m";
38
- const shift = (code & 4) !== 0;
39
- const alt = (code & 8) !== 0;
40
- const ctrl = (code & 16) !== 0;
41
- const baseCode = code & ~(4 | 8 | 16); // strip modifier bits
42
- let button = "none";
43
- let type = isRelease ? "release" : "press";
44
- if (baseCode === 0)
45
- button = "left";
46
- else if (baseCode === 1)
47
- button = "middle";
48
- else if (baseCode === 2)
49
- button = "right";
50
- else if (baseCode === 64)
51
- button = "scrollUp";
52
- else if (baseCode === 65)
53
- button = "scrollDown";
54
- else if (baseCode === 32) {
55
- button = "left";
56
- type = "move";
57
- }
58
- else if (baseCode === 33) {
59
- button = "middle";
60
- type = "move";
61
- }
62
- else if (baseCode === 34) {
63
- button = "right";
64
- type = "move";
65
- }
66
- else if (baseCode === 35) {
67
- button = "none";
68
- type = "move";
69
- }
70
- return { type, button, x, y, shift, ctrl, alt };
71
- }