openfox 2.0.11 → 2.0.13

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.
@@ -1,3 +1,17 @@
1
+ import {
2
+ COMPACTION_PROMPT,
3
+ TurnMetrics,
4
+ buildBasePrompt,
5
+ buildSubAgentSystemPrompt,
6
+ buildTopLevelSystemPrompt,
7
+ consumeStreamGenerator,
8
+ createChatDoneEvent,
9
+ createMessageDoneEvent,
10
+ createMessageStartEvent,
11
+ createToolCallEvent,
12
+ createToolResultEvent,
13
+ streamLLMPure
14
+ } from "./chunk-L7TDUIQY.js";
1
15
  import {
2
16
  startInspectProxy
3
17
  } from "./chunk-DL6ZILAF.js";
@@ -52,11 +66,7 @@ import {
52
66
  getGlobalConfigDir
53
67
  } from "./chunk-CQGTEGKL.js";
54
68
  import {
55
- buildModelParams,
56
- getBackendCapabilities,
57
- getModelProfile,
58
- modelSupportsVision,
59
- streamWithSegments
69
+ modelSupportsVision
60
70
  } from "./chunk-Z4SWOUWC.js";
61
71
  import {
62
72
  logger
@@ -1753,655 +1763,6 @@ async function deleteAgent(configDir, agentId) {
1753
1763
  return { success: false };
1754
1764
  }
1755
1765
 
1756
- // src/server/chat/prompts.ts
1757
- function buildBasePrompt(workdir, customInstructions, skills, modelName) {
1758
- const instructionsSection = customInstructions ? `
1759
-
1760
- ## CUSTOM INSTRUCTIONS
1761
-
1762
- ${customInstructions}` : "";
1763
- const modelLine = modelName ? `
1764
- Model: ${modelName}` : "";
1765
- return `You are OpenFox, an agentic assistant.
1766
-
1767
- Today's date is ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0].replace(/-/g, "/")}
1768
-
1769
- ## ENVIRONMENT
1770
- Working directory: ${workdir}
1771
- Platform: ${process.platform} (${process.arch})${modelLine}
1772
-
1773
- ## CORE BEHAVIOR
1774
- - Help the user complete any tasks safely and efficiently.
1775
- - Do everything in your capacity to satisfy user requirements.
1776
- - Read code before changing it.
1777
- - Prefer precise, minimal changes.
1778
- - Use available tools when needed.
1779
- - Explain tradeoffs clearly when requirements are ambiguous.
1780
- - Follow repository and project instructions exactly.
1781
-
1782
- ## MODE CONTROL
1783
- - OpenFox may append system-generated runtime control messages as USER-role messages wrapped in <system-reminder>...</system-reminder>.
1784
- - These reminders are authoritative framework instructions from OpenFox.
1785
- - Treat them as higher-priority operational constraints than normal user task wording for the current turn.
1786
- - Do not describe them as "the user reminded me"; they are runtime mode/control metadata injected by OpenFox.
1787
-
1788
- ## WORKFLOW
1789
- - If the current runtime reminder says planning mode, focus on understanding, exploration, clarification, and criteria quality.
1790
- - If the current runtime reminder says build mode, focus on implementation, verification, and completing approved criteria.
1791
- - Respect tool and permission constraints enforced by the server even if the conversation suggests otherwise.
1792
-
1793
- ## IMPORTANT GUARDRAILS
1794
- - NEVER delete/git checkout an already modified file: that would result in a data loss.
1795
-
1796
-
1797
- # Tone and style
1798
- You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
1799
- Remember that your output will be displayed on a command line interface. Your responses can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
1800
- Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
1801
- If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
1802
- Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
1803
- IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
1804
- IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
1805
- IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
1806
- <example>
1807
- user: 2 + 2
1808
- assistant: 4
1809
- </example>
1810
-
1811
- <example>
1812
- user: what is 2+2?
1813
- assistant: 4
1814
- </example>
1815
-
1816
- <example>
1817
- user: is 11 a prime number?
1818
- assistant: Yes
1819
- </example>
1820
-
1821
- <example>
1822
- user: what command should I run to list files in the current directory?
1823
- assistant: ls
1824
- </example>
1825
-
1826
- <example>
1827
- user: what command should I run to watch files in the current directory?
1828
- assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
1829
- npm run dev
1830
- </example>
1831
-
1832
- <example>
1833
- user: How many golf balls fit inside a jetta?
1834
- assistant: 150000
1835
- </example>
1836
-
1837
- <example>
1838
- user: what files are in the directory src/?
1839
- assistant: [runs ls and sees foo.c, bar.c, baz.c]
1840
- user: which file contains the implementation of foo?
1841
- assistant: src/foo.c
1842
- </example>
1843
-
1844
- <example>
1845
- user: write tests for new feature
1846
- assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
1847
- </example>
1848
-
1849
- # Proactiveness
1850
- You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
1851
- 1. Doing the right thing when asked, including taking actions and follow-up actions
1852
- 2. Not surprising the user with actions you take without asking
1853
- For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
1854
- 3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
1855
-
1856
- # Following conventions
1857
- When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
1858
- - NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
1859
- - When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
1860
- - When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
1861
- - Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
1862
-
1863
- # Code style
1864
- - IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
1865
-
1866
- # Doing tasks
1867
- The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
1868
- - Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
1869
- - Implement the solution using all tools available to you
1870
- - Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
1871
- - VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
1872
- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
1873
-
1874
- - Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
1875
-
1876
- # Tool usage policy
1877
- - When doing file search, prefer to use the Task tool in order to reduce context usage.
1878
- - You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
1879
-
1880
- You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
1881
-
1882
- ${instructionsSection}
1883
- ${buildSkillsSection(skills)}
1884
- `;
1885
- }
1886
- function buildSkillsSection(skills) {
1887
- if (!skills || skills.length === 0) return "";
1888
- const listing = skills.map((s, i) => `${i + 1}. **${s.id}** - ${s.description}`).join("\n");
1889
- return `
1890
- ## AVAILABLE SKILLS
1891
-
1892
- You can load specialized knowledge using the load_skill tool. Only load a skill when you need its instructions for the current task.
1893
-
1894
- ${listing}
1895
-
1896
- To load a skill, call load_skill with the skill ID. The skill's detailed instructions will be returned as a tool result.
1897
- `;
1898
- }
1899
- function buildSubAgentsSection(subAgentDefs) {
1900
- if (subAgentDefs.length === 0) return "";
1901
- const listing = subAgentDefs.map((agent, i) => {
1902
- const tools = (agent.metadata.allowedTools || []).join(", ");
1903
- return `${i + 1}. **${agent.metadata.id}** - ${agent.metadata.description}
1904
- - Has access to: ${tools}`;
1905
- }).join("\n\n");
1906
- return `
1907
- ## AVAILABLE SUB-AGENTS
1908
-
1909
- You can call specialized sub-agents for specific tasks using the call_sub_agent tool:
1910
-
1911
- ${listing}
1912
-
1913
- To call a sub-agent, use the call_sub_agent tool with:
1914
- - subAgentType: The ID of the sub-agent
1915
- - prompt: Clear description of what you need
1916
- `;
1917
- }
1918
- function buildTopLevelSystemPrompt(workdir, customInstructions, skills, subAgentDefs, modelName) {
1919
- const base = buildBasePrompt(workdir, customInstructions, skills, modelName);
1920
- const subAgents = subAgentDefs ? buildSubAgentsSection(subAgentDefs) : "";
1921
- return base + subAgents;
1922
- }
1923
- function buildSubAgentSystemPrompt(workdir, agentDef, skills, modelName) {
1924
- const base = buildBasePrompt(workdir, void 0, skills, modelName);
1925
- return base + "\n\n" + agentDef.prompt;
1926
- }
1927
- function buildToolPermissionsSection(allowedTools, isSubAgent) {
1928
- if (!allowedTools || allowedTools.length === 0) {
1929
- return "\n\n## AVAILABLE TOOLS\n\nYou have no tools available.";
1930
- }
1931
- const toolPermissions = /* @__PURE__ */ new Map();
1932
- const baseTools = [];
1933
- for (const entry of allowedTools) {
1934
- const colonIdx = entry.indexOf(":");
1935
- if (colonIdx === -1) {
1936
- if (entry !== "return_value" || isSubAgent) {
1937
- baseTools.push(entry);
1938
- }
1939
- } else {
1940
- const toolName = entry.slice(0, colonIdx);
1941
- const actionsStr = entry.slice(colonIdx + 1);
1942
- const actions = actionsStr.split(",").filter(Boolean);
1943
- const existing = toolPermissions.get(toolName) || [];
1944
- toolPermissions.set(toolName, [...existing, ...actions]);
1945
- }
1946
- }
1947
- if (isSubAgent && !baseTools.includes("return_value") && !toolPermissions.has("return_value")) {
1948
- baseTools.push("return_value");
1949
- }
1950
- const parts = [];
1951
- for (const [toolName, actions] of toolPermissions) {
1952
- parts.push(`${toolName}: ${actions.join(", ")}`);
1953
- }
1954
- for (const tool of baseTools) {
1955
- if (!toolPermissions.has(tool)) {
1956
- parts.push(tool);
1957
- }
1958
- }
1959
- const toolsList = parts.join(", ");
1960
- return `
1961
-
1962
- ## AVAILABLE TOOLS
1963
-
1964
- You have access to these tools: ${toolsList}`;
1965
- }
1966
- function buildAgentReminder(agentDef) {
1967
- const toolPermissions = buildToolPermissionsSection(agentDef.metadata.allowedTools, agentDef.metadata.subagent);
1968
- return `<system-reminder>
1969
- ${agentDef.prompt}${toolPermissions}
1970
- </system-reminder>`;
1971
- }
1972
- function buildAgentSmallReminder(name) {
1973
- return `<system-reminder>
1974
- Reminder: you are in '${name}' mode.
1975
- </system-reminder>`;
1976
- }
1977
- var WORKFLOW_KICKOFF_PROMPT = (criteriaCount) => `Implement the task and make sure you fulfil the ${criteriaCount} criteria.`;
1978
- var COMPACTION_PROMPT = `You are a helpful AI assistant tasked with summarizing conversations for continuation.
1979
-
1980
- Summarize the conversation history concisely, preserving:
1981
- 1. What was done and what is currently being worked on
1982
- 2. All file modifications made (file paths and what changed)
1983
- 3. All errors encountered and how they were resolved
1984
- 4. Current progress on each task
1985
- 5. Important technical decisions and WHY they were made
1986
- 6. Requirements that should persist
1987
- 7. Next steps or pending actions that should be continued after compaction
1988
- 8. The user's current question, prompt, or active request
1989
-
1990
- Do not respond to any questions in the conversation, only output the summary.
1991
- Be thorough but concise. Output as a structured summary.`;
1992
-
1993
- // src/server/chat/auto-patterns.ts
1994
- function matchRetryPatterns(content, thinking, patterns) {
1995
- const matches = [];
1996
- for (const config of patterns) {
1997
- if (!config.active) continue;
1998
- let regex;
1999
- try {
2000
- regex = new RegExp(config.pattern);
2001
- } catch {
2002
- continue;
2003
- }
2004
- const testContent = config.field === "thinking" ? false : regex.test(content);
2005
- const testThinking = config.field === "content" ? false : thinking !== void 0 && regex.test(thinking);
2006
- if (testContent) {
2007
- matches.push({ pattern: config.pattern, field: config.field, matchedContent: content });
2008
- }
2009
- if (testThinking) {
2010
- matches.push({ pattern: config.pattern, field: config.field, matchedContent: thinking });
2011
- }
2012
- }
2013
- return matches;
2014
- }
2015
-
2016
- // src/server/chat/stream-utils.ts
2017
- function buildStreamRequestObject(params) {
2018
- const { messages, tools, toolChoice, reasoningEffort, signal, modelSettings } = params;
2019
- return {
2020
- messages,
2021
- ...tools && { tools },
2022
- ...toolChoice && { toolChoice },
2023
- ...reasoningEffort && { reasoningEffort },
2024
- ...signal && { signal },
2025
- ...modelSettings && { modelSettings }
2026
- };
2027
- }
2028
- function buildStreamRequest(client, options) {
2029
- return streamWithSegments(client, buildStreamRequestObject(options));
2030
- }
2031
-
2032
- // src/server/chat/stats.ts
2033
- var roundTo1 = (n) => Math.round(n * 10) / 10;
2034
- function computeAggregatedStats(input) {
2035
- const {
2036
- identity,
2037
- mode,
2038
- totalPrefillTokens,
2039
- totalPrefillIncrement,
2040
- totalGenTokens,
2041
- totalPrefillTime,
2042
- totalGenTime,
2043
- totalToolTime,
2044
- totalTime,
2045
- llmCalls
2046
- } = input;
2047
- const prefillSource = totalPrefillIncrement ?? totalPrefillTokens;
2048
- return {
2049
- ...identity,
2050
- mode,
2051
- totalTime,
2052
- toolTime: totalToolTime,
2053
- prefillTokens: totalPrefillTokens,
2054
- ...totalPrefillIncrement !== void 0 && { prefTokenIncrement: totalPrefillIncrement },
2055
- prefillSpeed: totalPrefillTime > 0 ? roundTo1(prefillSource / totalPrefillTime) : 0,
2056
- generationTokens: totalGenTokens,
2057
- generationSpeed: totalGenTime > 0 ? roundTo1(totalGenTokens / totalGenTime) : 0,
2058
- ...llmCalls ? { llmCalls } : {}
2059
- };
2060
- }
2061
-
2062
- // src/server/chat/stream-pure.ts
2063
- function createEmptyStreamResult(aborted, modelParams, patternMatch) {
2064
- return {
2065
- content: "",
2066
- toolCalls: [],
2067
- segments: [],
2068
- usage: { promptTokens: 0, completionTokens: 0 },
2069
- timing: { ttft: 0, completionTime: 0, tps: 0, prefillTps: 0 },
2070
- aborted,
2071
- modelParams,
2072
- finishReason: "stop",
2073
- ...patternMatch ? { patternMatch } : {}
2074
- };
2075
- }
2076
- async function* streamLLMPure(options) {
2077
- const { messageId, systemPrompt, llmClient, messages, tools, toolChoice, signal, reasoningEffort, retryPatterns } = options;
2078
- const llmMessages = [{ role: "system", content: systemPrompt }, ...messages];
2079
- const profile = getModelProfile(llmClient.getModel());
2080
- const backend = getBackendCapabilities(llmClient.getBackend());
2081
- const userTemp = options.modelSettings?.temperature;
2082
- const userTopP = options.modelSettings?.topP;
2083
- const userTopK = options.modelSettings?.topK;
2084
- const userMaxTokens = options.modelSettings?.maxTokens;
2085
- const temperature = userTemp ?? profile.temperature;
2086
- const maxTokens = userMaxTokens ?? profile.defaultMaxTokens;
2087
- const topP = userTopP ?? profile.topP;
2088
- const topK = userTopK ?? (backend.supportsTopK ? profile.topK : void 0);
2089
- const modelParams = buildModelParams({ temperature, topP, topK, maxTokens });
2090
- logger.debug("LLM request settings", {
2091
- model: llmClient.getModel(),
2092
- profile: profile.name,
2093
- temperature,
2094
- maxTokens,
2095
- topP,
2096
- topK,
2097
- userConfigured: {
2098
- temperature: userTemp !== void 0 ? `user:${userTemp}` : "default",
2099
- topP: userTopP !== void 0 ? `user:${userTopP}` : "default",
2100
- topK: userTopK !== void 0 ? `user:${userTopK}` : "default",
2101
- maxTokens: userMaxTokens !== void 0 ? `user:${userMaxTokens}` : "default"
2102
- }
2103
- });
2104
- const patternAbortController = new AbortController();
2105
- const combinedSignal = signal ? AbortSignal.any([signal, patternAbortController.signal]) : patternAbortController.signal;
2106
- const stream = buildStreamRequest(llmClient, {
2107
- messages: llmMessages,
2108
- tools,
2109
- toolChoice,
2110
- reasoningEffort,
2111
- signal: combinedSignal,
2112
- modelSettings: options.modelSettings
2113
- });
2114
- const seenToolIndices = /* @__PURE__ */ new Set();
2115
- const toolNames = /* @__PURE__ */ new Map();
2116
- const toolIds = /* @__PURE__ */ new Map();
2117
- const returnValueArgs = /* @__PURE__ */ new Map();
2118
- const toolArgs = /* @__PURE__ */ new Map();
2119
- let result = null;
2120
- let aborted = false;
2121
- let accumulatedContent = "";
2122
- let accumulatedThinking = "";
2123
- let patternMatch;
2124
- const activePatterns = retryPatterns?.filter((p) => p.active) ?? [];
2125
- try {
2126
- while (true) {
2127
- if (signal?.aborted) {
2128
- aborted = true;
2129
- break;
2130
- }
2131
- const { value, done } = await stream.next();
2132
- if (done) {
2133
- result = value;
2134
- break;
2135
- }
2136
- switch (value.type) {
2137
- case "text_delta":
2138
- accumulatedContent += value.content;
2139
- yield {
2140
- type: "message.delta",
2141
- data: { messageId, content: value.content }
2142
- };
2143
- break;
2144
- case "thinking_delta":
2145
- accumulatedThinking += value.content;
2146
- yield {
2147
- type: "message.thinking",
2148
- data: { messageId, content: value.content }
2149
- };
2150
- break;
2151
- case "tool_call_delta": {
2152
- if (value.name) {
2153
- const existingName = toolNames.get(value.index) ?? "";
2154
- toolNames.set(value.index, existingName + value.name);
2155
- }
2156
- if (value.id) {
2157
- toolIds.set(value.index, value.id);
2158
- }
2159
- if (value.arguments) {
2160
- const existingArgs = toolArgs.get(value.index) ?? "";
2161
- toolArgs.set(value.index, existingArgs + value.arguments);
2162
- }
2163
- const fullName = toolNames.get(value.index);
2164
- if (!seenToolIndices.has(value.index) && fullName) {
2165
- seenToolIndices.add(value.index);
2166
- const accumulatedArgs = toolArgs.get(value.index);
2167
- yield {
2168
- type: "tool.preparing",
2169
- data: {
2170
- messageId,
2171
- index: value.index,
2172
- name: fullName,
2173
- ...accumulatedArgs ? { arguments: accumulatedArgs } : {}
2174
- }
2175
- };
2176
- } else if (seenToolIndices.has(value.index) && value.arguments) {
2177
- const name = toolNames.get(value.index);
2178
- if (name === "run_command" || name === "return_value") {
2179
- const accumulatedArgs = toolArgs.get(value.index);
2180
- if (accumulatedArgs) {
2181
- yield {
2182
- type: "tool.preparing",
2183
- data: { messageId, index: value.index, name, arguments: accumulatedArgs }
2184
- };
2185
- }
2186
- }
2187
- }
2188
- if (fullName === "return_value" && value.arguments) {
2189
- const toolCallId = toolIds.get(value.index);
2190
- if (toolCallId) {
2191
- const prevRaw = returnValueArgs.get(value.index) ?? "";
2192
- const newRaw = prevRaw + value.arguments;
2193
- returnValueArgs.set(value.index, newRaw);
2194
- const contentStart = newRaw.indexOf('"content"');
2195
- if (contentStart >= 0) {
2196
- const colonPos = newRaw.indexOf(":", contentStart + 9);
2197
- if (colonPos >= 0) {
2198
- const valueStart = newRaw.indexOf('"', colonPos + 1);
2199
- if (valueStart >= 0) {
2200
- const prevContent = prevRaw.length > valueStart + 1 ? prevRaw.slice(valueStart + 1).replace(/"\s*\}\s*$/, "") : "";
2201
- const currentContent = newRaw.slice(valueStart + 1).replace(/"\s*\}\s*$/, "");
2202
- const delta = currentContent.slice(prevContent.length);
2203
- if (delta) {
2204
- const unescaped = delta.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
2205
- yield {
2206
- type: "tool.output",
2207
- data: { messageId, toolCallId, stream: "stdout", content: unescaped }
2208
- };
2209
- }
2210
- }
2211
- }
2212
- }
2213
- }
2214
- }
2215
- break;
2216
- }
2217
- case "error":
2218
- yield {
2219
- type: "chat.error",
2220
- data: { error: value.error, recoverable: true }
2221
- };
2222
- break;
2223
- }
2224
- if (activePatterns.length > 0 && (accumulatedContent || accumulatedThinking)) {
2225
- const matches = matchRetryPatterns(accumulatedContent, accumulatedThinking || void 0, activePatterns);
2226
- if (matches.length > 0) {
2227
- patternMatch = matches[0];
2228
- patternAbortController.abort();
2229
- break;
2230
- }
2231
- }
2232
- }
2233
- } catch (error) {
2234
- if (error instanceof Error && error.message === "Aborted") {
2235
- aborted = true;
2236
- } else {
2237
- throw error;
2238
- }
2239
- }
2240
- if (patternMatch) {
2241
- return createEmptyStreamResult(false, modelParams, patternMatch);
2242
- }
2243
- if (!result) {
2244
- return createEmptyStreamResult(aborted, modelParams);
2245
- }
2246
- const baseResult = {
2247
- content: result.content,
2248
- toolCalls: result.toolCalls,
2249
- segments: result.segments,
2250
- usage: {
2251
- promptTokens: result.response.usage.promptTokens,
2252
- completionTokens: result.response.usage.completionTokens
2253
- },
2254
- timing: result.timing,
2255
- aborted,
2256
- modelParams,
2257
- finishReason: result.response.finishReason
2258
- };
2259
- if (result.thinkingContent) {
2260
- baseResult.thinkingContent = result.thinkingContent;
2261
- }
2262
- return baseResult;
2263
- }
2264
- var TurnMetrics = class {
2265
- startTime;
2266
- totalPrefillTokens = 0;
2267
- totalPrefillIncrement = 0;
2268
- totalPrefillTime = 0;
2269
- // seconds
2270
- totalGenTokens = 0;
2271
- totalGenTime = 0;
2272
- // seconds
2273
- totalToolTime = 0;
2274
- // seconds
2275
- llmCalls = [];
2276
- modelParams = {};
2277
- constructor() {
2278
- this.startTime = performance.now();
2279
- }
2280
- /** Add metrics from an LLM call.
2281
- * @param previousContextTokens - context size BEFORE this LLM call (for computing the non-cached increment)
2282
- */
2283
- addLLMCall(timing, promptTokens, completionTokens, previousContextTokens, modelParams) {
2284
- const callIndex = this.llmCalls.length + 1;
2285
- this.totalPrefillTokens += promptTokens;
2286
- this.totalPrefillTime += timing.ttft;
2287
- this.totalGenTokens += completionTokens;
2288
- this.totalGenTime += timing.completionTime;
2289
- if (modelParams) {
2290
- this.modelParams = modelParams;
2291
- }
2292
- const prefTokenIncrement = previousContextTokens !== void 0 ? Math.max(0, promptTokens - previousContextTokens) : void 0;
2293
- if (prefTokenIncrement !== void 0) {
2294
- this.totalPrefillIncrement += prefTokenIncrement;
2295
- }
2296
- const prefillSource = prefTokenIncrement ?? promptTokens;
2297
- this.llmCalls = [
2298
- ...this.llmCalls,
2299
- {
2300
- callIndex,
2301
- promptTokens,
2302
- completionTokens,
2303
- ...prefTokenIncrement !== void 0 && { prefTokenIncrement },
2304
- ttft: timing.ttft,
2305
- completionTime: timing.completionTime,
2306
- prefillSpeed: timing.ttft > 0 ? Math.round(prefillSource / timing.ttft * 10) / 10 : 0,
2307
- generationSpeed: timing.completionTime > 0 ? Math.round(completionTokens / timing.completionTime * 10) / 10 : 0,
2308
- totalTime: Math.round((timing.ttft + timing.completionTime) * 10) / 10,
2309
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2310
- ...this.modelParams.temperature !== void 0 && { temperature: this.modelParams.temperature },
2311
- ...this.modelParams.topP !== void 0 && { topP: this.modelParams.topP },
2312
- ...this.modelParams.topK !== void 0 && { topK: this.modelParams.topK },
2313
- ...this.modelParams.maxTokens !== void 0 && { maxTokens: this.modelParams.maxTokens }
2314
- }
2315
- ];
2316
- }
2317
- /** Set model parameters for tracking */
2318
- setModelParams(params) {
2319
- this.modelParams = params;
2320
- }
2321
- /** Add tool execution time (in milliseconds) */
2322
- addToolTime(durationMs) {
2323
- this.totalToolTime += durationMs / 1e3;
2324
- }
2325
- /** Build final stats object */
2326
- buildStats(identity, mode) {
2327
- return computeAggregatedStats({
2328
- identity,
2329
- mode,
2330
- totalPrefillTokens: this.totalPrefillTokens,
2331
- ...this.totalPrefillIncrement > 0 && { totalPrefillIncrement: this.totalPrefillIncrement },
2332
- totalGenTokens: this.totalGenTokens,
2333
- totalPrefillTime: this.totalPrefillTime,
2334
- totalGenTime: this.totalGenTime,
2335
- totalToolTime: this.totalToolTime,
2336
- totalTime: (performance.now() - this.startTime) / 1e3,
2337
- llmCalls: this.llmCalls.map((call) => ({
2338
- ...identity,
2339
- ...call
2340
- }))
2341
- });
2342
- }
2343
- };
2344
- function createMessageStartEvent(messageId, role, content, options) {
2345
- return {
2346
- type: "message.start",
2347
- data: {
2348
- messageId,
2349
- role,
2350
- ...content !== void 0 && { content },
2351
- ...options?.contextWindowId && { contextWindowId: options.contextWindowId },
2352
- ...options?.subAgentId && { subAgentId: options.subAgentId },
2353
- ...options?.subAgentType && { subAgentType: options.subAgentType },
2354
- ...options?.isSystemGenerated && { isSystemGenerated: options.isSystemGenerated },
2355
- ...options?.messageKind && { messageKind: options.messageKind },
2356
- ...options?.metadata && { metadata: options.metadata }
2357
- }
2358
- };
2359
- }
2360
- function createMessageDoneEvent(messageId, options) {
2361
- return {
2362
- type: "message.done",
2363
- data: {
2364
- messageId,
2365
- ...options?.stats && { stats: options.stats },
2366
- ...options?.segments && { segments: options.segments },
2367
- ...options?.partial && { partial: options.partial }
2368
- }
2369
- };
2370
- }
2371
- function createToolCallEvent(messageId, toolCall) {
2372
- return {
2373
- type: "tool.call",
2374
- data: { messageId, toolCall }
2375
- };
2376
- }
2377
- function createToolResultEvent(messageId, toolCallId, result) {
2378
- return {
2379
- type: "tool.result",
2380
- data: { messageId, toolCallId, result }
2381
- };
2382
- }
2383
- function createChatDoneEvent(messageId, reason, stats, agentType) {
2384
- return {
2385
- type: "chat.done",
2386
- data: {
2387
- messageId,
2388
- reason,
2389
- ...stats && { stats },
2390
- ...agentType && { agentType }
2391
- }
2392
- };
2393
- }
2394
- async function consumeStreamGenerator(gen, onEvent) {
2395
- let result;
2396
- while (true) {
2397
- result = await gen.next();
2398
- if (result.done) {
2399
- return result.value;
2400
- }
2401
- onEvent(result.value);
2402
- }
2403
- }
2404
-
2405
1766
  // src/server/context/instructions.ts
2406
1767
  import { readFile as readFile6, access as access3 } from "fs/promises";
2407
1768
  import { join as join5, dirname as dirname3 } from "path";
@@ -2843,7 +2204,7 @@ async function runTopLevelAgentLoop(config, turnMetrics) {
2843
2204
  let returnValueResult;
2844
2205
  let currentMaxTokensOverride;
2845
2206
  let lastPatternMatch;
2846
- let compacting = false;
2207
+ let compacting = config.initialCompacting ?? false;
2847
2208
  let returnValueNudgeCount = 0;
2848
2209
  for (; ; ) {
2849
2210
  if (signal?.aborted) throw new Error("Aborted");
@@ -2966,18 +2327,9 @@ ${CONTINUE_PROMPT}` : CONTINUE_PROMPT;
2966
2327
  sessionManager.setCurrentContextSize(sessionId, result.usage.promptTokens);
2967
2328
  if (!compacting) {
2968
2329
  const contextState = sessionManager.getContextState(sessionId);
2969
- const { shouldCompact } = await import("./compactor-5VQNEYQX.js");
2330
+ const { shouldCompact, appendCompactionPrompt } = await import("./compactor-R7GRFBOU.js");
2970
2331
  if (shouldCompact(contextState.currentTokens, contextState.maxTokens, runtimeConfig.context.compactionThreshold)) {
2971
- const compactPromptMsgId = crypto.randomUUID();
2972
- append(
2973
- createMessageStartEvent(compactPromptMsgId, "user", COMPACTION_PROMPT, {
2974
- ...currentWindowMessageOptions ?? {},
2975
- isSystemGenerated: true,
2976
- messageKind: "auto-prompt",
2977
- metadata: { type: "compaction", name: "Compaction", color: "#64748b" }
2978
- })
2979
- );
2980
- append({ type: "message.done", data: { messageId: compactPromptMsgId } });
2332
+ appendCompactionPrompt(sessionId, append);
2981
2333
  compacting = true;
2982
2334
  continue;
2983
2335
  }
@@ -3126,6 +2478,7 @@ ${COMPACTION_PROMPT}`,
3126
2478
  });
3127
2479
  logger.warn("Compaction produced empty summary, continuing", { sessionId });
3128
2480
  compacting = false;
2481
+ if (config.initialCompacting) break;
3129
2482
  continue;
3130
2483
  }
3131
2484
  const closedWindowId = getCurrentContextWindowId(sessionId) ?? "";
@@ -3149,6 +2502,7 @@ ${COMPACTION_PROMPT}`,
3149
2502
  append(createChatDoneEvent(assistantMsgId, "complete"));
3150
2503
  config.injectAgentReminder?.();
3151
2504
  compacting = false;
2505
+ if (config.initialCompacting) break;
3152
2506
  continue;
3153
2507
  }
3154
2508
  if (config.requireReturnValue && !returnValueContent) {
@@ -3777,7 +3131,7 @@ var callSubAgentTool = {
3777
3131
  };
3778
3132
  }
3779
3133
  try {
3780
- const { getToolRegistryForAgent: getToolRegistryForAgent2 } = await import("./tools-UT5WFO7R.js");
3134
+ const { getToolRegistryForAgent: getToolRegistryForAgent2 } = await import("./tools-THXBQJ7A.js");
3781
3135
  const toolRegistry = getToolRegistryForAgent2(agentDef);
3782
3136
  const turnMetrics = new TurnMetrics();
3783
3137
  const result = await executeSubAgent({
@@ -4801,20 +4155,6 @@ export {
4801
4155
  agentExists,
4802
4156
  saveAgent,
4803
4157
  deleteAgent,
4804
- buildBasePrompt,
4805
- buildTopLevelSystemPrompt,
4806
- buildAgentReminder,
4807
- buildAgentSmallReminder,
4808
- WORKFLOW_KICKOFF_PROMPT,
4809
- COMPACTION_PROMPT,
4810
- streamLLMPure,
4811
- TurnMetrics,
4812
- createMessageStartEvent,
4813
- createMessageDoneEvent,
4814
- createToolCallEvent,
4815
- createToolResultEvent,
4816
- createChatDoneEvent,
4817
- consumeStreamGenerator,
4818
4158
  getAllInstructions,
4819
4159
  loadDefaultSkills,
4820
4160
  loadUserSkills,
@@ -4846,4 +4186,4 @@ export {
4846
4186
  getToolRegistryForAgent,
4847
4187
  createToolRegistry
4848
4188
  };
4849
- //# sourceMappingURL=chunk-M53OBFMI.js.map
4189
+ //# sourceMappingURL=chunk-2VDLXCLO.js.map