@phren/agent 0.3.20 → 0.3.22
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/dist/agent-loop/index.js +113 -19
- package/dist/agent-loop/stream.js +3 -1
- package/dist/attach-images.js +57 -0
- package/dist/commands/info.js +6 -2
- package/dist/commands/model.js +55 -13
- package/dist/commands/session.js +79 -18
- package/dist/commands.js +9 -2
- package/dist/config.js +45 -0
- package/dist/context/clear-tool-results.js +43 -0
- package/dist/context/compactor.js +8 -2
- package/dist/context/usage.js +26 -0
- package/dist/cost.js +10 -3
- package/dist/headless.js +41 -0
- package/dist/index.js +180 -56
- package/dist/mcp-client.js +38 -1
- package/dist/mcp-prompts.js +94 -0
- package/dist/multi/child-entry.js +3 -1
- package/dist/multi/spawner.js +27 -15
- package/dist/permissions/allowlist.js +19 -4
- package/dist/permissions/checker.js +37 -20
- package/dist/permissions/kernel-sandbox.js +32 -10
- package/dist/permissions/rules.js +173 -0
- package/dist/permissions/shell-classify.js +173 -0
- package/dist/plan.js +6 -2
- package/dist/repl.js +16 -1
- package/dist/session/persist.js +9 -4
- package/dist/settings.js +14 -0
- package/dist/structured-output.js +85 -0
- package/dist/system-prompt.js +117 -14
- package/dist/tools/apply-patch.js +15 -1
- package/dist/tools/edit-file.js +8 -1
- package/dist/tools/file-state.js +88 -0
- package/dist/tools/glob.js +53 -35
- package/dist/tools/grep.js +139 -53
- package/dist/tools/lint-test.js +24 -0
- package/dist/tools/read-file.js +2 -0
- package/dist/tools/registry.js +8 -1
- package/dist/tools/search-support.js +141 -0
- package/dist/tools/shell.js +3 -1
- package/dist/tools/spawn-agent.js +15 -3
- package/dist/tools/syntax-check.js +116 -0
- package/dist/tools/write-file.js +11 -3
- package/dist/tui/components/App.js +5 -4
- package/dist/tui/components/Banner.js +1 -1
- package/dist/tui/components/ListPicker.js +32 -0
- package/dist/tui/ink-entry.js +57 -16
- package/dist/user-hooks.js +26 -4
- package/package.json +3 -2
package/dist/commands.js
CHANGED
|
@@ -4,7 +4,7 @@ import { sessionCommand, historyCommand, compactCommand, diffCommand, gitCommand
|
|
|
4
4
|
import { memCommand, askCommand } from "./commands/memory.js";
|
|
5
5
|
import { reviewCommand } from "./commands/review.js";
|
|
6
6
|
import { findSkill, getScopedSkills } from "@phren/cli/skill/registry";
|
|
7
|
-
import { modelCommand, providerCommand, presetCommand } from "./commands/model.js";
|
|
7
|
+
import { modelCommand, providerCommand, presetCommand, reasoningCommand } from "./commands/model.js";
|
|
8
8
|
import { configCommand } from "./commands/config.js";
|
|
9
9
|
import { loadInputMode, saveInputMode, savePermissionMode } from "./settings.js";
|
|
10
10
|
import { addAllow } from "./permissions/allowlist.js";
|
|
@@ -20,7 +20,7 @@ export function createCommandContext(session, contextLimit) {
|
|
|
20
20
|
}
|
|
21
21
|
const BUILTIN_COMMAND_NAMES = [
|
|
22
22
|
"/help", "/turns", "/clear", "/cwd", "/files", "/cost", "/plan", "/undo",
|
|
23
|
-
"/context", "/model", "/provider", "/preset", "/session", "/history",
|
|
23
|
+
"/context", "/model", "/provider", "/reasoning", "/preset", "/session", "/history",
|
|
24
24
|
"/compact", "/diff", "/git", "/mem", "/ask", "/resume", "/review", "/config", "/spawn", "/agents",
|
|
25
25
|
"/allow",
|
|
26
26
|
"/mode", "/permissions", "/verbose", "/theme", "/agent", "/rewind", "/fork", "/promote",
|
|
@@ -38,6 +38,12 @@ export function setCustomCommands(commands) {
|
|
|
38
38
|
COMMAND_NAMES.length = 0;
|
|
39
39
|
COMMAND_NAMES.push(...BUILTIN_COMMAND_NAMES, ...customCommands.map((command) => `/${command.name}`));
|
|
40
40
|
}
|
|
41
|
+
/** Extra command names for completion (MCP prompts, found after servers connect). */
|
|
42
|
+
export function addCommandNames(names) {
|
|
43
|
+
for (const name of names)
|
|
44
|
+
if (!COMMAND_NAMES.includes(name))
|
|
45
|
+
COMMAND_NAMES.push(name);
|
|
46
|
+
}
|
|
41
47
|
export function loadAndRegisterCustomCommands(cwd = process.cwd()) {
|
|
42
48
|
const commands = loadCustomCommands(cwd);
|
|
43
49
|
setCustomCommands(commands);
|
|
@@ -122,6 +128,7 @@ export function handleCommand(input, ctx) {
|
|
|
122
128
|
case "/context": return contextCommand(parts, ctx);
|
|
123
129
|
case "/model": return modelCommand(parts, ctx);
|
|
124
130
|
case "/provider": return providerCommand(parts, ctx);
|
|
131
|
+
case "/reasoning": return reasoningCommand(parts, ctx);
|
|
125
132
|
case "/preset": return presetCommand(parts, ctx);
|
|
126
133
|
case "/session": return sessionCommand(parts, ctx);
|
|
127
134
|
case "/history": return historyCommand(parts, ctx);
|
package/dist/config.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as os from "node:os";
|
|
2
2
|
import * as path from "node:path";
|
|
3
|
+
import { parseRuleList } from "./permissions/rules.js";
|
|
3
4
|
import { normalizeReasoningEffort } from "./models.js";
|
|
4
5
|
import { loadPermissionMode } from "./settings.js";
|
|
5
6
|
export const AGENT_CONFIG_DIR = ".phren-agent";
|
|
@@ -34,8 +35,11 @@ Options:
|
|
|
34
35
|
--no-subagents Disable spawn_agent/send_message/list_agents in one-shot mode
|
|
35
36
|
--no-llm-compact Use regex prune summaries instead of LLM compaction
|
|
36
37
|
--sandbox <mode> Kernel write-fence for shell (bwrap): off, auto (default), require
|
|
38
|
+
--no-network Run shell commands without network (bwrap or Seatbelt; fails closed)
|
|
37
39
|
--permissions <mode> Permission mode: suggest (default), auto-confirm, full-auto
|
|
38
40
|
--yolo Full-auto permissions — no confirmations (alias for --permissions full-auto)
|
|
41
|
+
--allowedTools <rules> Allow these without asking, comma-separated: read_file, shell(npm test), edit_file(src/**)
|
|
42
|
+
--disallowedTools <rules> Deny these in every mode, same syntax
|
|
39
43
|
--interactive, -i Interactive REPL mode (multi-turn conversation)
|
|
40
44
|
--resume, -c Resume the newest session's conversation (task optional)
|
|
41
45
|
--session <id> Resume a specific session by id or unique id prefix
|
|
@@ -43,10 +47,18 @@ Options:
|
|
|
43
47
|
-p, --print Headless: no prompts (tool approvals are denied), clean stdout
|
|
44
48
|
--output-format <f> With -p: text (final message), json (one result object),
|
|
45
49
|
stream-json (NDJSON events + result). Implies -p
|
|
50
|
+
--json-schema <s> With -p: end with a JSON value matching this schema (inline JSON or a
|
|
51
|
+
file), in the result's structured_output; implies -p
|
|
52
|
+
--input-format <f> With -p: text (the task, default) or stream-json (user
|
|
53
|
+
messages as JSON lines on stdin, one turn each, same session;
|
|
54
|
+
needs --output-format stream-json)
|
|
46
55
|
--lint-cmd <cmd> Override auto-detected lint command
|
|
47
56
|
--test-cmd <cmd> Override auto-detected test command
|
|
57
|
+
--typecheck-cmd <cmd> Override the auto-detected type check run after edits
|
|
48
58
|
--mcp <command> Connect to an MCP server via stdio (repeatable)
|
|
49
59
|
--mcp-config <path> Load MCP server config from JSON file
|
|
60
|
+
--trust-project-mcp Load this project's .mcp.json and .phren-agent/mcp.json (remembered)
|
|
61
|
+
--strict-mcp-config Use only --mcp-config and --mcp servers, no default config files
|
|
50
62
|
--team <name> Start in team mode with named team coordination
|
|
51
63
|
--multi Start in multi-agent TUI mode
|
|
52
64
|
--dry-run Show system prompt and exit
|
|
@@ -92,6 +104,8 @@ export function parseArgs(argv) {
|
|
|
92
104
|
task: "",
|
|
93
105
|
permissions: "suggest",
|
|
94
106
|
permissionsExplicit: false,
|
|
107
|
+
allowedTools: [],
|
|
108
|
+
disallowedTools: [],
|
|
95
109
|
maxTurns: 50,
|
|
96
110
|
budget: null,
|
|
97
111
|
plan: false,
|
|
@@ -102,6 +116,7 @@ export function parseArgs(argv) {
|
|
|
102
116
|
listSessions: false,
|
|
103
117
|
print: false,
|
|
104
118
|
outputFormat: "text",
|
|
119
|
+
inputFormat: "text",
|
|
105
120
|
noSubagents: false,
|
|
106
121
|
noLlmCompact: false,
|
|
107
122
|
sandbox: "auto",
|
|
@@ -136,6 +151,9 @@ export function parseArgs(argv) {
|
|
|
136
151
|
else if (arg === "--no-llm-compact") {
|
|
137
152
|
args.noLlmCompact = true;
|
|
138
153
|
}
|
|
154
|
+
else if (arg === "--no-network") {
|
|
155
|
+
args.noNetwork = true;
|
|
156
|
+
}
|
|
139
157
|
else if (arg === "--sandbox" && argv[i + 1]) {
|
|
140
158
|
const mode = argv[++i];
|
|
141
159
|
if (mode === "off" || mode === "auto" || mode === "require") {
|
|
@@ -164,6 +182,18 @@ export function parseArgs(argv) {
|
|
|
164
182
|
else if (arg === "--print" || arg === "-p") {
|
|
165
183
|
args.print = true;
|
|
166
184
|
}
|
|
185
|
+
else if (arg === "--json-schema" && argv[i + 1]) {
|
|
186
|
+
args.jsonSchema = argv[++i];
|
|
187
|
+
args.print = true;
|
|
188
|
+
}
|
|
189
|
+
else if (arg === "--input-format" && argv[i + 1]) {
|
|
190
|
+
const format = argv[++i];
|
|
191
|
+
if (format !== "text" && format !== "stream-json")
|
|
192
|
+
throw new Error(`Unknown --input-format "${format}". Use text or stream-json.`);
|
|
193
|
+
args.inputFormat = format;
|
|
194
|
+
if (format === "stream-json")
|
|
195
|
+
args.print = true;
|
|
196
|
+
}
|
|
167
197
|
else if (arg === "--output-format" && argv[i + 1]) {
|
|
168
198
|
const format = argv[++i];
|
|
169
199
|
if (format === "text" || format === "json" || format === "stream-json") {
|
|
@@ -183,12 +213,21 @@ export function parseArgs(argv) {
|
|
|
183
213
|
else if (arg === "--test-cmd" && argv[i + 1]) {
|
|
184
214
|
args.testCmd = argv[++i];
|
|
185
215
|
}
|
|
216
|
+
else if (arg === "--typecheck-cmd" && argv[i + 1]) {
|
|
217
|
+
args.typecheckCmd = argv[++i];
|
|
218
|
+
}
|
|
186
219
|
else if (arg === "--mcp" && argv[i + 1]) {
|
|
187
220
|
args.mcp.push(argv[++i]);
|
|
188
221
|
}
|
|
189
222
|
else if (arg === "--mcp-config" && argv[i + 1]) {
|
|
190
223
|
args.mcpConfig = argv[++i];
|
|
191
224
|
}
|
|
225
|
+
else if (arg === "--trust-project-mcp") {
|
|
226
|
+
args.trustProjectMcp = true;
|
|
227
|
+
}
|
|
228
|
+
else if (arg === "--strict-mcp-config") {
|
|
229
|
+
args.strictMcpConfig = true;
|
|
230
|
+
}
|
|
192
231
|
else if (arg === "--team" && argv[i + 1]) {
|
|
193
232
|
args.team = argv[++i];
|
|
194
233
|
}
|
|
@@ -228,6 +267,12 @@ export function parseArgs(argv) {
|
|
|
228
267
|
else if (arg === "--budget" && argv[i + 1]) {
|
|
229
268
|
args.budget = parseFloat(argv[++i]) || null;
|
|
230
269
|
}
|
|
270
|
+
else if ((arg === "--allowedTools" || arg === "--allowed-tools") && argv[i + 1]) {
|
|
271
|
+
args.allowedTools.push(...parseRuleList(argv[++i]));
|
|
272
|
+
}
|
|
273
|
+
else if ((arg === "--disallowedTools" || arg === "--disallowed-tools") && argv[i + 1]) {
|
|
274
|
+
args.disallowedTools.push(...parseRuleList(argv[++i]));
|
|
275
|
+
}
|
|
231
276
|
else if (arg === "--yolo") {
|
|
232
277
|
args.permissions = "full-auto";
|
|
233
278
|
args.permissionsExplicit = true;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { toolResultText } from "../providers/types.js";
|
|
2
|
+
export const DEFAULT_CLEAR = { keepRecent: 8, minChars: 2_000 };
|
|
3
|
+
const CLEARED_PREFIX = "[Earlier output cleared to save context";
|
|
4
|
+
/** Plan which old tool results to clear. Returns [] when there is nothing worth clearing. */
|
|
5
|
+
export function planToolResultClearing(messages, config = {}) {
|
|
6
|
+
const { keepRecent, minChars } = { ...DEFAULT_CLEAR, ...config };
|
|
7
|
+
const names = new Map();
|
|
8
|
+
const results = [];
|
|
9
|
+
messages.forEach((msg, index) => {
|
|
10
|
+
if (typeof msg.content === "string")
|
|
11
|
+
return;
|
|
12
|
+
for (const block of msg.content) {
|
|
13
|
+
if (block.type === "tool_use")
|
|
14
|
+
names.set(block.id, block.name);
|
|
15
|
+
else if (block.type === "tool_result")
|
|
16
|
+
results.push({ index, block });
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
const clear = new Map();
|
|
20
|
+
for (const { index, block } of results.slice(0, Math.max(0, results.length - keepRecent))) {
|
|
21
|
+
const text = toolResultText(block);
|
|
22
|
+
const hasImage = Array.isArray(block.content) && block.content.some((part) => part.type === "image");
|
|
23
|
+
if (text.startsWith(CLEARED_PREFIX) || (text.length < minChars && !hasImage))
|
|
24
|
+
continue;
|
|
25
|
+
if (!clear.has(index))
|
|
26
|
+
clear.set(index, new Set());
|
|
27
|
+
clear.get(index).add(block);
|
|
28
|
+
}
|
|
29
|
+
return [...clear].map(([index, blocks]) => {
|
|
30
|
+
const content = messages[index].content.map((block) => {
|
|
31
|
+
if (block.type !== "tool_result" || !blocks.has(block))
|
|
32
|
+
return block;
|
|
33
|
+
const text = toolResultText(block);
|
|
34
|
+
const tool = names.get(block.tool_use_id) ?? "the tool";
|
|
35
|
+
const firstLine = text.split("\n", 1)[0].slice(0, 120);
|
|
36
|
+
return {
|
|
37
|
+
...block,
|
|
38
|
+
content: `${CLEARED_PREFIX}: ${tool} returned ${text.length} chars, starting "${firstLine}". Run it again if you need it.]`,
|
|
39
|
+
};
|
|
40
|
+
});
|
|
41
|
+
return { index, message: { ...messages[index], content } };
|
|
42
|
+
});
|
|
43
|
+
}
|
|
@@ -32,6 +32,12 @@ The original task; work completed so far; files created or modified; the current
|
|
|
32
32
|
## Knowledge
|
|
33
33
|
A fenced json block: {"items":[{"text":"...","confidence":0.9,"kind":"finding|gotcha|decision"}]}
|
|
34
34
|
Only durable, non-obvious, project-level knowledge worth remembering across sessions (root causes, architecture decisions with rationale, gotchas, workarounds). Confidence is YOUR certainty the item is true and durable, 0 to 1. Use {"items":[]} if nothing qualifies. Never include secrets or credentials.`;
|
|
35
|
+
function checkpointInstruction(focus) {
|
|
36
|
+
const trimmed = focus?.trim();
|
|
37
|
+
if (!trimmed)
|
|
38
|
+
return CHECKPOINT_INSTRUCTION;
|
|
39
|
+
return `${CHECKPOINT_INSTRUCTION}\n\nThe user asked the summary to focus on: ${trimmed}. Keep everything about it; shorten the rest.`;
|
|
40
|
+
}
|
|
35
41
|
// ── Response parsing ─────────────────────────────────────────────────────────
|
|
36
42
|
const KNOWLEDGE_HEADING_RE = /^##\s*Knowledge\b.*$/im;
|
|
37
43
|
const SUMMARY_HEADING_RE = /^##\s*Checkpoint Summary\b.*$/im;
|
|
@@ -184,12 +190,12 @@ export async function compactWithLlm(provider, systemPrompt, messages, opts = {}
|
|
|
184
190
|
// covers the prefix, so this costs roughly one summary generation.
|
|
185
191
|
const prefixMessages = [
|
|
186
192
|
...messages.slice(0, plan.endIndex + 1),
|
|
187
|
-
{ role: "user", content:
|
|
193
|
+
{ role: "user", content: checkpointInstruction(opts.focus) },
|
|
188
194
|
];
|
|
189
195
|
// A timeout or turn abort settles the wait; finally() then cancels the
|
|
190
196
|
// request itself so it doesn't keep generating (and billing) detached.
|
|
191
197
|
const cancel = new AbortController();
|
|
192
|
-
const response = await withTimeout(provider.chat(systemPrompt, prefixMessages, [], cancel.signal), config.timeoutMs, opts.signal).finally(() => cancel.abort());
|
|
198
|
+
const response = await withTimeout(provider.chat(systemPrompt, prefixMessages, opts.tools ?? [], cancel.signal), config.timeoutMs, opts.signal).finally(() => cancel.abort());
|
|
193
199
|
if (response.usage && opts.costTracker) {
|
|
194
200
|
recordTokenUsage(opts.costTracker, response.usage);
|
|
195
201
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { estimateMessageTokens, estimateTokens } from "./token-counter.js";
|
|
2
|
+
/** Record the size the provider reported, after its reply is in the log. */
|
|
3
|
+
export function reportedContext(usage, log) {
|
|
4
|
+
if (!usage)
|
|
5
|
+
return undefined;
|
|
6
|
+
const prompt = usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
|
|
7
|
+
// A provider that reports nothing useful (0 prompt tokens) leaves the estimate in charge.
|
|
8
|
+
if (prompt <= 0)
|
|
9
|
+
return undefined;
|
|
10
|
+
return { tokens: prompt + usage.output_tokens, messageCount: log.getMessages().length, logLength: log.length };
|
|
11
|
+
}
|
|
12
|
+
/** Tokens the next request will carry: reported plus estimated growth, or the estimate alone. */
|
|
13
|
+
export function contextTokens(systemPrompt, messages, log, reported) {
|
|
14
|
+
if (reported && messages.length >= reported.messageCount && log.length >= reported.logLength && !replacedSince(log, reported.logLength)) {
|
|
15
|
+
return reported.tokens + estimateMessageTokens(messages.slice(reported.messageCount));
|
|
16
|
+
}
|
|
17
|
+
return estimateTokens(systemPrompt) + estimateMessageTokens(messages);
|
|
18
|
+
}
|
|
19
|
+
function replacedSince(log, from) {
|
|
20
|
+
const events = log.all;
|
|
21
|
+
for (let i = from; i < events.length; i++) {
|
|
22
|
+
if (events[i].type === "log/replace")
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
return false;
|
|
26
|
+
}
|
package/dist/cost.js
CHANGED
|
@@ -36,12 +36,12 @@ export function resolvePricing(model, provider, baseUrl) {
|
|
|
36
36
|
/** Prompt-cache writes cost this much more than ordinary input. */
|
|
37
37
|
export const CACHE_WRITE_MULTIPLIER = 1.25;
|
|
38
38
|
export function createCostTracker(model, budget = null, provider, baseUrl) {
|
|
39
|
-
|
|
39
|
+
let { pricing, metered } = resolvePricing(model, provider, baseUrl);
|
|
40
40
|
// Without a cache price, hits bill as ordinary input (no discount assumed).
|
|
41
|
-
|
|
41
|
+
let cacheReadPer1M = pricing.cacheReadPer1M ?? pricing.inputPer1M;
|
|
42
42
|
// Cache writes bill at 1.25x input (Anthropic's 5-minute cache, the one
|
|
43
43
|
// the agent asks for); providers that cache implicitly report none.
|
|
44
|
-
|
|
44
|
+
let cacheWritePer1M = pricing.inputPer1M * CACHE_WRITE_MULTIPLIER;
|
|
45
45
|
const price = (input, output, cacheRead, cacheWrite) => (input / 1_000_000) * pricing.inputPer1M +
|
|
46
46
|
(output / 1_000_000) * pricing.outputPer1M +
|
|
47
47
|
(cacheRead / 1_000_000) * cacheReadPer1M +
|
|
@@ -61,6 +61,13 @@ export function createCostTracker(model, budget = null, provider, baseUrl) {
|
|
|
61
61
|
tracker.totalCacheWriteTokens += cacheWriteTokens;
|
|
62
62
|
tracker.totalCost += price(inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens);
|
|
63
63
|
},
|
|
64
|
+
reprice(nextModel, nextProvider, nextBaseUrl) {
|
|
65
|
+
({ pricing, metered } = resolvePricing(nextModel, nextProvider, nextBaseUrl));
|
|
66
|
+
cacheReadPer1M = pricing.cacheReadPer1M ?? pricing.inputPer1M;
|
|
67
|
+
cacheWritePer1M = pricing.inputPer1M * CACHE_WRITE_MULTIPLIER;
|
|
68
|
+
// Money already spent on a metered model still counts against --budget.
|
|
69
|
+
tracker.metered = metered || tracker.totalCost > 0;
|
|
70
|
+
},
|
|
64
71
|
isOverBudget() {
|
|
65
72
|
return tracker.metered && budget !== null && tracker.totalCost >= budget;
|
|
66
73
|
},
|
package/dist/headless.js
CHANGED
|
@@ -4,6 +4,7 @@ const SUBTYPE = {
|
|
|
4
4
|
budget: "error_budget",
|
|
5
5
|
plan_rejected: "error_plan_rejected",
|
|
6
6
|
aborted: "cancelled",
|
|
7
|
+
hook_blocked: "error_hook_blocked",
|
|
7
8
|
};
|
|
8
9
|
export function buildHeadlessResult(opts) {
|
|
9
10
|
const subtype = opts.stopReason === "error" ? "error_during_execution" : SUBTYPE[opts.stopReason];
|
|
@@ -111,6 +112,46 @@ export function parseOutputFormat(raw) {
|
|
|
111
112
|
return raw;
|
|
112
113
|
return null;
|
|
113
114
|
}
|
|
115
|
+
/**
|
|
116
|
+
* One `--input-format stream-json` line: Claude Code's shape,
|
|
117
|
+
* {"type":"user","message":{"role":"user","content":"…" | [{"type":"text","text":"…"}]}}.
|
|
118
|
+
* Returns the prompt text, or an error naming what was wrong.
|
|
119
|
+
*/
|
|
120
|
+
export function parseStreamJsonInput(line) {
|
|
121
|
+
let event;
|
|
122
|
+
try {
|
|
123
|
+
event = JSON.parse(line);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return { error: "not JSON" };
|
|
127
|
+
}
|
|
128
|
+
const e = event;
|
|
129
|
+
if (e?.type !== "user" || !e.message || e.message.role !== "user")
|
|
130
|
+
return { error: "expected {\"type\":\"user\",\"message\":{\"role\":\"user\",…}}" };
|
|
131
|
+
const content = e.message.content;
|
|
132
|
+
const prompt = typeof content === "string"
|
|
133
|
+
? content
|
|
134
|
+
: Array.isArray(content)
|
|
135
|
+
? content.filter((b) => b?.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n")
|
|
136
|
+
: "";
|
|
137
|
+
return prompt.trim() ? { prompt } : { error: "the message has no text" };
|
|
138
|
+
}
|
|
139
|
+
/** Non-empty lines from a stream, as they arrive. */
|
|
140
|
+
export async function* readLines(stream = process.stdin) {
|
|
141
|
+
let buffer = "";
|
|
142
|
+
for await (const chunk of stream) {
|
|
143
|
+
buffer += typeof chunk === "string" ? chunk : chunk.toString("utf-8");
|
|
144
|
+
let nl;
|
|
145
|
+
while ((nl = buffer.indexOf("\n")) >= 0) {
|
|
146
|
+
const line = buffer.slice(0, nl).trim();
|
|
147
|
+
buffer = buffer.slice(nl + 1);
|
|
148
|
+
if (line)
|
|
149
|
+
yield line;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (buffer.trim())
|
|
153
|
+
yield buffer.trim();
|
|
154
|
+
}
|
|
114
155
|
/** Read the whole of stdin (for `echo task | phren-agent -p`). */
|
|
115
156
|
export async function readStdin(stream = process.stdin) {
|
|
116
157
|
const chunks = [];
|