openfox 2.0.10 → 2.0.12

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
@@ -1172,13 +1182,22 @@ function stripTailPipe(command) {
1172
1182
  }
1173
1183
 
1174
1184
  // src/server/tools/shell.ts
1185
+ function hasBackgroundAmpersand(command) {
1186
+ const trimmed = command.replace(/[;\s]+$/, "");
1187
+ if (trimmed.endsWith("&")) {
1188
+ const before = trimmed[trimmed.length - 2];
1189
+ if (before === "&" || before === "|") return false;
1190
+ return true;
1191
+ }
1192
+ return false;
1193
+ }
1175
1194
  var runCommandTool = createTool(
1176
1195
  "run_command",
1177
1196
  {
1178
1197
  type: "function",
1179
1198
  function: {
1180
1199
  name: "run_command",
1181
- description: "Execute a shell command. Returns stdout, stderr, and exit code.",
1200
+ description: 'Execute a shell command. Returns stdout, stderr, and exit code. Does NOT support trailing "&" for backgrounding \u2014 use background_process tool instead.',
1182
1201
  parameters: {
1183
1202
  type: "object",
1184
1203
  properties: {
@@ -1201,6 +1220,11 @@ var runCommandTool = createTool(
1201
1220
  },
1202
1221
  async (args, context, helpers) => {
1203
1222
  const timeout = args.timeout ?? 12e4;
1223
+ if (hasBackgroundAmpersand(args.command)) {
1224
+ return helpers.error(
1225
+ `Use background_process tool (action: "start") for background/long-running commands instead of '&'. See the tool description for details.`
1226
+ );
1227
+ }
1204
1228
  const workingDir = args.cwd ? helpers.resolvePath(args.cwd) : context.workdir;
1205
1229
  const pathsToCheck = [workingDir];
1206
1230
  const commandPaths = extractAbsolutePathsFromCommand(args.command);
@@ -1739,655 +1763,6 @@ async function deleteAgent(configDir, agentId) {
1739
1763
  return { success: false };
1740
1764
  }
1741
1765
 
1742
- // src/server/chat/prompts.ts
1743
- function buildBasePrompt(workdir, customInstructions, skills, modelName) {
1744
- const instructionsSection = customInstructions ? `
1745
-
1746
- ## CUSTOM INSTRUCTIONS
1747
-
1748
- ${customInstructions}` : "";
1749
- const modelLine = modelName ? `
1750
- Model: ${modelName}` : "";
1751
- return `You are OpenFox, an agentic assistant.
1752
-
1753
- Today's date is ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0].replace(/-/g, "/")}
1754
-
1755
- ## ENVIRONMENT
1756
- Working directory: ${workdir}
1757
- Platform: ${process.platform} (${process.arch})${modelLine}
1758
-
1759
- ## CORE BEHAVIOR
1760
- - Help the user complete any tasks safely and efficiently.
1761
- - Do everything in your capacity to satisfy user requirements.
1762
- - Read code before changing it.
1763
- - Prefer precise, minimal changes.
1764
- - Use available tools when needed.
1765
- - Explain tradeoffs clearly when requirements are ambiguous.
1766
- - Follow repository and project instructions exactly.
1767
-
1768
- ## MODE CONTROL
1769
- - OpenFox may append system-generated runtime control messages as USER-role messages wrapped in <system-reminder>...</system-reminder>.
1770
- - These reminders are authoritative framework instructions from OpenFox.
1771
- - Treat them as higher-priority operational constraints than normal user task wording for the current turn.
1772
- - Do not describe them as "the user reminded me"; they are runtime mode/control metadata injected by OpenFox.
1773
-
1774
- ## WORKFLOW
1775
- - If the current runtime reminder says planning mode, focus on understanding, exploration, clarification, and criteria quality.
1776
- - If the current runtime reminder says build mode, focus on implementation, verification, and completing approved criteria.
1777
- - Respect tool and permission constraints enforced by the server even if the conversation suggests otherwise.
1778
-
1779
- ## IMPORTANT GUARDRAILS
1780
- - NEVER delete/git checkout an already modified file: that would result in a data loss.
1781
-
1782
-
1783
- # Tone and style
1784
- 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).
1785
- 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.
1786
- 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.
1787
- 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.
1788
- Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
1789
- 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.
1790
- 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.
1791
- 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:
1792
- <example>
1793
- user: 2 + 2
1794
- assistant: 4
1795
- </example>
1796
-
1797
- <example>
1798
- user: what is 2+2?
1799
- assistant: 4
1800
- </example>
1801
-
1802
- <example>
1803
- user: is 11 a prime number?
1804
- assistant: Yes
1805
- </example>
1806
-
1807
- <example>
1808
- user: what command should I run to list files in the current directory?
1809
- assistant: ls
1810
- </example>
1811
-
1812
- <example>
1813
- user: what command should I run to watch files in the current directory?
1814
- 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]
1815
- npm run dev
1816
- </example>
1817
-
1818
- <example>
1819
- user: How many golf balls fit inside a jetta?
1820
- assistant: 150000
1821
- </example>
1822
-
1823
- <example>
1824
- user: what files are in the directory src/?
1825
- assistant: [runs ls and sees foo.c, bar.c, baz.c]
1826
- user: which file contains the implementation of foo?
1827
- assistant: src/foo.c
1828
- </example>
1829
-
1830
- <example>
1831
- user: write tests for new feature
1832
- 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]
1833
- </example>
1834
-
1835
- # Proactiveness
1836
- You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
1837
- 1. Doing the right thing when asked, including taking actions and follow-up actions
1838
- 2. Not surprising the user with actions you take without asking
1839
- 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.
1840
- 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.
1841
-
1842
- # Following conventions
1843
- When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
1844
- - 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).
1845
- - 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.
1846
- - 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.
1847
- - Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
1848
-
1849
- # Code style
1850
- - IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
1851
-
1852
- # Doing tasks
1853
- 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:
1854
- - 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.
1855
- - Implement the solution using all tools available to you
1856
- - 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.
1857
- - 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.
1858
- 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.
1859
-
1860
- - 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.
1861
-
1862
- # Tool usage policy
1863
- - When doing file search, prefer to use the Task tool in order to reduce context usage.
1864
- - 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.
1865
-
1866
- You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
1867
-
1868
- ${instructionsSection}
1869
- ${buildSkillsSection(skills)}
1870
- `;
1871
- }
1872
- function buildSkillsSection(skills) {
1873
- if (!skills || skills.length === 0) return "";
1874
- const listing = skills.map((s, i) => `${i + 1}. **${s.id}** - ${s.description}`).join("\n");
1875
- return `
1876
- ## AVAILABLE SKILLS
1877
-
1878
- You can load specialized knowledge using the load_skill tool. Only load a skill when you need its instructions for the current task.
1879
-
1880
- ${listing}
1881
-
1882
- To load a skill, call load_skill with the skill ID. The skill's detailed instructions will be returned as a tool result.
1883
- `;
1884
- }
1885
- function buildSubAgentsSection(subAgentDefs) {
1886
- if (subAgentDefs.length === 0) return "";
1887
- const listing = subAgentDefs.map((agent, i) => {
1888
- const tools = (agent.metadata.allowedTools || []).join(", ");
1889
- return `${i + 1}. **${agent.metadata.id}** - ${agent.metadata.description}
1890
- - Has access to: ${tools}`;
1891
- }).join("\n\n");
1892
- return `
1893
- ## AVAILABLE SUB-AGENTS
1894
-
1895
- You can call specialized sub-agents for specific tasks using the call_sub_agent tool:
1896
-
1897
- ${listing}
1898
-
1899
- To call a sub-agent, use the call_sub_agent tool with:
1900
- - subAgentType: The ID of the sub-agent
1901
- - prompt: Clear description of what you need
1902
- `;
1903
- }
1904
- function buildTopLevelSystemPrompt(workdir, customInstructions, skills, subAgentDefs, modelName) {
1905
- const base = buildBasePrompt(workdir, customInstructions, skills, modelName);
1906
- const subAgents = subAgentDefs ? buildSubAgentsSection(subAgentDefs) : "";
1907
- return base + subAgents;
1908
- }
1909
- function buildSubAgentSystemPrompt(workdir, agentDef, skills, modelName) {
1910
- const base = buildBasePrompt(workdir, void 0, skills, modelName);
1911
- return base + "\n\n" + agentDef.prompt;
1912
- }
1913
- function buildToolPermissionsSection(allowedTools, isSubAgent) {
1914
- if (!allowedTools || allowedTools.length === 0) {
1915
- return "\n\n## AVAILABLE TOOLS\n\nYou have no tools available.";
1916
- }
1917
- const toolPermissions = /* @__PURE__ */ new Map();
1918
- const baseTools = [];
1919
- for (const entry of allowedTools) {
1920
- const colonIdx = entry.indexOf(":");
1921
- if (colonIdx === -1) {
1922
- if (entry !== "return_value" || isSubAgent) {
1923
- baseTools.push(entry);
1924
- }
1925
- } else {
1926
- const toolName = entry.slice(0, colonIdx);
1927
- const actionsStr = entry.slice(colonIdx + 1);
1928
- const actions = actionsStr.split(",").filter(Boolean);
1929
- const existing = toolPermissions.get(toolName) || [];
1930
- toolPermissions.set(toolName, [...existing, ...actions]);
1931
- }
1932
- }
1933
- if (isSubAgent && !baseTools.includes("return_value") && !toolPermissions.has("return_value")) {
1934
- baseTools.push("return_value");
1935
- }
1936
- const parts = [];
1937
- for (const [toolName, actions] of toolPermissions) {
1938
- parts.push(`${toolName}: ${actions.join(", ")}`);
1939
- }
1940
- for (const tool of baseTools) {
1941
- if (!toolPermissions.has(tool)) {
1942
- parts.push(tool);
1943
- }
1944
- }
1945
- const toolsList = parts.join(", ");
1946
- return `
1947
-
1948
- ## AVAILABLE TOOLS
1949
-
1950
- You have access to these tools: ${toolsList}`;
1951
- }
1952
- function buildAgentReminder(agentDef) {
1953
- const toolPermissions = buildToolPermissionsSection(agentDef.metadata.allowedTools, agentDef.metadata.subagent);
1954
- return `<system-reminder>
1955
- ${agentDef.prompt}${toolPermissions}
1956
- </system-reminder>`;
1957
- }
1958
- function buildAgentSmallReminder(name) {
1959
- return `<system-reminder>
1960
- Reminder: you are in '${name}' mode.
1961
- </system-reminder>`;
1962
- }
1963
- var WORKFLOW_KICKOFF_PROMPT = (criteriaCount) => `Implement the task and make sure you fulfil the ${criteriaCount} criteria.`;
1964
- var COMPACTION_PROMPT = `You are a helpful AI assistant tasked with summarizing conversations for continuation.
1965
-
1966
- Summarize the conversation history concisely, preserving:
1967
- 1. What was done and what is currently being worked on
1968
- 2. All file modifications made (file paths and what changed)
1969
- 3. All errors encountered and how they were resolved
1970
- 4. Current progress on each task
1971
- 5. Important technical decisions and WHY they were made
1972
- 6. Requirements that should persist
1973
- 7. Next steps or pending actions that should be continued after compaction
1974
- 8. The user's current question, prompt, or active request
1975
-
1976
- Do not respond to any questions in the conversation, only output the summary.
1977
- Be thorough but concise. Output as a structured summary.`;
1978
-
1979
- // src/server/chat/auto-patterns.ts
1980
- function matchRetryPatterns(content, thinking, patterns) {
1981
- const matches = [];
1982
- for (const config of patterns) {
1983
- if (!config.active) continue;
1984
- let regex;
1985
- try {
1986
- regex = new RegExp(config.pattern);
1987
- } catch {
1988
- continue;
1989
- }
1990
- const testContent = config.field === "thinking" ? false : regex.test(content);
1991
- const testThinking = config.field === "content" ? false : thinking !== void 0 && regex.test(thinking);
1992
- if (testContent) {
1993
- matches.push({ pattern: config.pattern, field: config.field, matchedContent: content });
1994
- }
1995
- if (testThinking) {
1996
- matches.push({ pattern: config.pattern, field: config.field, matchedContent: thinking });
1997
- }
1998
- }
1999
- return matches;
2000
- }
2001
-
2002
- // src/server/chat/stream-utils.ts
2003
- function buildStreamRequestObject(params) {
2004
- const { messages, tools, toolChoice, reasoningEffort, signal, modelSettings } = params;
2005
- return {
2006
- messages,
2007
- ...tools && { tools },
2008
- ...toolChoice && { toolChoice },
2009
- ...reasoningEffort && { reasoningEffort },
2010
- ...signal && { signal },
2011
- ...modelSettings && { modelSettings }
2012
- };
2013
- }
2014
- function buildStreamRequest(client, options) {
2015
- return streamWithSegments(client, buildStreamRequestObject(options));
2016
- }
2017
-
2018
- // src/server/chat/stats.ts
2019
- var roundTo1 = (n) => Math.round(n * 10) / 10;
2020
- function computeAggregatedStats(input) {
2021
- const {
2022
- identity,
2023
- mode,
2024
- totalPrefillTokens,
2025
- totalPrefillIncrement,
2026
- totalGenTokens,
2027
- totalPrefillTime,
2028
- totalGenTime,
2029
- totalToolTime,
2030
- totalTime,
2031
- llmCalls
2032
- } = input;
2033
- const prefillSource = totalPrefillIncrement ?? totalPrefillTokens;
2034
- return {
2035
- ...identity,
2036
- mode,
2037
- totalTime,
2038
- toolTime: totalToolTime,
2039
- prefillTokens: totalPrefillTokens,
2040
- ...totalPrefillIncrement !== void 0 && { prefTokenIncrement: totalPrefillIncrement },
2041
- prefillSpeed: totalPrefillTime > 0 ? roundTo1(prefillSource / totalPrefillTime) : 0,
2042
- generationTokens: totalGenTokens,
2043
- generationSpeed: totalGenTime > 0 ? roundTo1(totalGenTokens / totalGenTime) : 0,
2044
- ...llmCalls ? { llmCalls } : {}
2045
- };
2046
- }
2047
-
2048
- // src/server/chat/stream-pure.ts
2049
- function createEmptyStreamResult(aborted, modelParams, patternMatch) {
2050
- return {
2051
- content: "",
2052
- toolCalls: [],
2053
- segments: [],
2054
- usage: { promptTokens: 0, completionTokens: 0 },
2055
- timing: { ttft: 0, completionTime: 0, tps: 0, prefillTps: 0 },
2056
- aborted,
2057
- modelParams,
2058
- finishReason: "stop",
2059
- ...patternMatch ? { patternMatch } : {}
2060
- };
2061
- }
2062
- async function* streamLLMPure(options) {
2063
- const { messageId, systemPrompt, llmClient, messages, tools, toolChoice, signal, reasoningEffort, retryPatterns } = options;
2064
- const llmMessages = [{ role: "system", content: systemPrompt }, ...messages];
2065
- const profile = getModelProfile(llmClient.getModel());
2066
- const backend = getBackendCapabilities(llmClient.getBackend());
2067
- const userTemp = options.modelSettings?.temperature;
2068
- const userTopP = options.modelSettings?.topP;
2069
- const userTopK = options.modelSettings?.topK;
2070
- const userMaxTokens = options.modelSettings?.maxTokens;
2071
- const temperature = userTemp ?? profile.temperature;
2072
- const maxTokens = userMaxTokens ?? profile.defaultMaxTokens;
2073
- const topP = userTopP ?? profile.topP;
2074
- const topK = userTopK ?? (backend.supportsTopK ? profile.topK : void 0);
2075
- const modelParams = buildModelParams({ temperature, topP, topK, maxTokens });
2076
- logger.debug("LLM request settings", {
2077
- model: llmClient.getModel(),
2078
- profile: profile.name,
2079
- temperature,
2080
- maxTokens,
2081
- topP,
2082
- topK,
2083
- userConfigured: {
2084
- temperature: userTemp !== void 0 ? `user:${userTemp}` : "default",
2085
- topP: userTopP !== void 0 ? `user:${userTopP}` : "default",
2086
- topK: userTopK !== void 0 ? `user:${userTopK}` : "default",
2087
- maxTokens: userMaxTokens !== void 0 ? `user:${userMaxTokens}` : "default"
2088
- }
2089
- });
2090
- const patternAbortController = new AbortController();
2091
- const combinedSignal = signal ? AbortSignal.any([signal, patternAbortController.signal]) : patternAbortController.signal;
2092
- const stream = buildStreamRequest(llmClient, {
2093
- messages: llmMessages,
2094
- tools,
2095
- toolChoice,
2096
- reasoningEffort,
2097
- signal: combinedSignal,
2098
- modelSettings: options.modelSettings
2099
- });
2100
- const seenToolIndices = /* @__PURE__ */ new Set();
2101
- const toolNames = /* @__PURE__ */ new Map();
2102
- const toolIds = /* @__PURE__ */ new Map();
2103
- const returnValueArgs = /* @__PURE__ */ new Map();
2104
- const toolArgs = /* @__PURE__ */ new Map();
2105
- let result = null;
2106
- let aborted = false;
2107
- let accumulatedContent = "";
2108
- let accumulatedThinking = "";
2109
- let patternMatch;
2110
- const activePatterns = retryPatterns?.filter((p) => p.active) ?? [];
2111
- try {
2112
- while (true) {
2113
- if (signal?.aborted) {
2114
- aborted = true;
2115
- break;
2116
- }
2117
- const { value, done } = await stream.next();
2118
- if (done) {
2119
- result = value;
2120
- break;
2121
- }
2122
- switch (value.type) {
2123
- case "text_delta":
2124
- accumulatedContent += value.content;
2125
- yield {
2126
- type: "message.delta",
2127
- data: { messageId, content: value.content }
2128
- };
2129
- break;
2130
- case "thinking_delta":
2131
- accumulatedThinking += value.content;
2132
- yield {
2133
- type: "message.thinking",
2134
- data: { messageId, content: value.content }
2135
- };
2136
- break;
2137
- case "tool_call_delta": {
2138
- if (value.name) {
2139
- const existingName = toolNames.get(value.index) ?? "";
2140
- toolNames.set(value.index, existingName + value.name);
2141
- }
2142
- if (value.id) {
2143
- toolIds.set(value.index, value.id);
2144
- }
2145
- if (value.arguments) {
2146
- const existingArgs = toolArgs.get(value.index) ?? "";
2147
- toolArgs.set(value.index, existingArgs + value.arguments);
2148
- }
2149
- const fullName = toolNames.get(value.index);
2150
- if (!seenToolIndices.has(value.index) && fullName) {
2151
- seenToolIndices.add(value.index);
2152
- const accumulatedArgs = toolArgs.get(value.index);
2153
- yield {
2154
- type: "tool.preparing",
2155
- data: {
2156
- messageId,
2157
- index: value.index,
2158
- name: fullName,
2159
- ...accumulatedArgs ? { arguments: accumulatedArgs } : {}
2160
- }
2161
- };
2162
- } else if (seenToolIndices.has(value.index) && value.arguments) {
2163
- const name = toolNames.get(value.index);
2164
- if (name === "run_command" || name === "return_value") {
2165
- const accumulatedArgs = toolArgs.get(value.index);
2166
- if (accumulatedArgs) {
2167
- yield {
2168
- type: "tool.preparing",
2169
- data: { messageId, index: value.index, name, arguments: accumulatedArgs }
2170
- };
2171
- }
2172
- }
2173
- }
2174
- if (fullName === "return_value" && value.arguments) {
2175
- const toolCallId = toolIds.get(value.index);
2176
- if (toolCallId) {
2177
- const prevRaw = returnValueArgs.get(value.index) ?? "";
2178
- const newRaw = prevRaw + value.arguments;
2179
- returnValueArgs.set(value.index, newRaw);
2180
- const contentStart = newRaw.indexOf('"content"');
2181
- if (contentStart >= 0) {
2182
- const colonPos = newRaw.indexOf(":", contentStart + 9);
2183
- if (colonPos >= 0) {
2184
- const valueStart = newRaw.indexOf('"', colonPos + 1);
2185
- if (valueStart >= 0) {
2186
- const prevContent = prevRaw.length > valueStart + 1 ? prevRaw.slice(valueStart + 1).replace(/"\s*\}\s*$/, "") : "";
2187
- const currentContent = newRaw.slice(valueStart + 1).replace(/"\s*\}\s*$/, "");
2188
- const delta = currentContent.slice(prevContent.length);
2189
- if (delta) {
2190
- const unescaped = delta.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
2191
- yield {
2192
- type: "tool.output",
2193
- data: { messageId, toolCallId, stream: "stdout", content: unescaped }
2194
- };
2195
- }
2196
- }
2197
- }
2198
- }
2199
- }
2200
- }
2201
- break;
2202
- }
2203
- case "error":
2204
- yield {
2205
- type: "chat.error",
2206
- data: { error: value.error, recoverable: true }
2207
- };
2208
- break;
2209
- }
2210
- if (activePatterns.length > 0 && (accumulatedContent || accumulatedThinking)) {
2211
- const matches = matchRetryPatterns(accumulatedContent, accumulatedThinking || void 0, activePatterns);
2212
- if (matches.length > 0) {
2213
- patternMatch = matches[0];
2214
- patternAbortController.abort();
2215
- break;
2216
- }
2217
- }
2218
- }
2219
- } catch (error) {
2220
- if (error instanceof Error && error.message === "Aborted") {
2221
- aborted = true;
2222
- } else {
2223
- throw error;
2224
- }
2225
- }
2226
- if (patternMatch) {
2227
- return createEmptyStreamResult(false, modelParams, patternMatch);
2228
- }
2229
- if (!result) {
2230
- return createEmptyStreamResult(aborted, modelParams);
2231
- }
2232
- const baseResult = {
2233
- content: result.content,
2234
- toolCalls: result.toolCalls,
2235
- segments: result.segments,
2236
- usage: {
2237
- promptTokens: result.response.usage.promptTokens,
2238
- completionTokens: result.response.usage.completionTokens
2239
- },
2240
- timing: result.timing,
2241
- aborted,
2242
- modelParams,
2243
- finishReason: result.response.finishReason
2244
- };
2245
- if (result.thinkingContent) {
2246
- baseResult.thinkingContent = result.thinkingContent;
2247
- }
2248
- return baseResult;
2249
- }
2250
- var TurnMetrics = class {
2251
- startTime;
2252
- totalPrefillTokens = 0;
2253
- totalPrefillIncrement = 0;
2254
- totalPrefillTime = 0;
2255
- // seconds
2256
- totalGenTokens = 0;
2257
- totalGenTime = 0;
2258
- // seconds
2259
- totalToolTime = 0;
2260
- // seconds
2261
- llmCalls = [];
2262
- modelParams = {};
2263
- constructor() {
2264
- this.startTime = performance.now();
2265
- }
2266
- /** Add metrics from an LLM call.
2267
- * @param previousContextTokens - context size BEFORE this LLM call (for computing the non-cached increment)
2268
- */
2269
- addLLMCall(timing, promptTokens, completionTokens, previousContextTokens, modelParams) {
2270
- const callIndex = this.llmCalls.length + 1;
2271
- this.totalPrefillTokens += promptTokens;
2272
- this.totalPrefillTime += timing.ttft;
2273
- this.totalGenTokens += completionTokens;
2274
- this.totalGenTime += timing.completionTime;
2275
- if (modelParams) {
2276
- this.modelParams = modelParams;
2277
- }
2278
- const prefTokenIncrement = previousContextTokens !== void 0 ? Math.max(0, promptTokens - previousContextTokens) : void 0;
2279
- if (prefTokenIncrement !== void 0) {
2280
- this.totalPrefillIncrement += prefTokenIncrement;
2281
- }
2282
- const prefillSource = prefTokenIncrement ?? promptTokens;
2283
- this.llmCalls = [
2284
- ...this.llmCalls,
2285
- {
2286
- callIndex,
2287
- promptTokens,
2288
- completionTokens,
2289
- ...prefTokenIncrement !== void 0 && { prefTokenIncrement },
2290
- ttft: timing.ttft,
2291
- completionTime: timing.completionTime,
2292
- prefillSpeed: timing.ttft > 0 ? Math.round(prefillSource / timing.ttft * 10) / 10 : 0,
2293
- generationSpeed: timing.completionTime > 0 ? Math.round(completionTokens / timing.completionTime * 10) / 10 : 0,
2294
- totalTime: Math.round((timing.ttft + timing.completionTime) * 10) / 10,
2295
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2296
- ...this.modelParams.temperature !== void 0 && { temperature: this.modelParams.temperature },
2297
- ...this.modelParams.topP !== void 0 && { topP: this.modelParams.topP },
2298
- ...this.modelParams.topK !== void 0 && { topK: this.modelParams.topK },
2299
- ...this.modelParams.maxTokens !== void 0 && { maxTokens: this.modelParams.maxTokens }
2300
- }
2301
- ];
2302
- }
2303
- /** Set model parameters for tracking */
2304
- setModelParams(params) {
2305
- this.modelParams = params;
2306
- }
2307
- /** Add tool execution time (in milliseconds) */
2308
- addToolTime(durationMs) {
2309
- this.totalToolTime += durationMs / 1e3;
2310
- }
2311
- /** Build final stats object */
2312
- buildStats(identity, mode) {
2313
- return computeAggregatedStats({
2314
- identity,
2315
- mode,
2316
- totalPrefillTokens: this.totalPrefillTokens,
2317
- ...this.totalPrefillIncrement > 0 && { totalPrefillIncrement: this.totalPrefillIncrement },
2318
- totalGenTokens: this.totalGenTokens,
2319
- totalPrefillTime: this.totalPrefillTime,
2320
- totalGenTime: this.totalGenTime,
2321
- totalToolTime: this.totalToolTime,
2322
- totalTime: (performance.now() - this.startTime) / 1e3,
2323
- llmCalls: this.llmCalls.map((call) => ({
2324
- ...identity,
2325
- ...call
2326
- }))
2327
- });
2328
- }
2329
- };
2330
- function createMessageStartEvent(messageId, role, content, options) {
2331
- return {
2332
- type: "message.start",
2333
- data: {
2334
- messageId,
2335
- role,
2336
- ...content !== void 0 && { content },
2337
- ...options?.contextWindowId && { contextWindowId: options.contextWindowId },
2338
- ...options?.subAgentId && { subAgentId: options.subAgentId },
2339
- ...options?.subAgentType && { subAgentType: options.subAgentType },
2340
- ...options?.isSystemGenerated && { isSystemGenerated: options.isSystemGenerated },
2341
- ...options?.messageKind && { messageKind: options.messageKind },
2342
- ...options?.metadata && { metadata: options.metadata }
2343
- }
2344
- };
2345
- }
2346
- function createMessageDoneEvent(messageId, options) {
2347
- return {
2348
- type: "message.done",
2349
- data: {
2350
- messageId,
2351
- ...options?.stats && { stats: options.stats },
2352
- ...options?.segments && { segments: options.segments },
2353
- ...options?.partial && { partial: options.partial }
2354
- }
2355
- };
2356
- }
2357
- function createToolCallEvent(messageId, toolCall) {
2358
- return {
2359
- type: "tool.call",
2360
- data: { messageId, toolCall }
2361
- };
2362
- }
2363
- function createToolResultEvent(messageId, toolCallId, result) {
2364
- return {
2365
- type: "tool.result",
2366
- data: { messageId, toolCallId, result }
2367
- };
2368
- }
2369
- function createChatDoneEvent(messageId, reason, stats, agentType) {
2370
- return {
2371
- type: "chat.done",
2372
- data: {
2373
- messageId,
2374
- reason,
2375
- ...stats && { stats },
2376
- ...agentType && { agentType }
2377
- }
2378
- };
2379
- }
2380
- async function consumeStreamGenerator(gen, onEvent) {
2381
- let result;
2382
- while (true) {
2383
- result = await gen.next();
2384
- if (result.done) {
2385
- return result.value;
2386
- }
2387
- onEvent(result.value);
2388
- }
2389
- }
2390
-
2391
1766
  // src/server/context/instructions.ts
2392
1767
  import { readFile as readFile6, access as access3 } from "fs/promises";
2393
1768
  import { join as join5, dirname as dirname3 } from "path";
@@ -2829,7 +2204,7 @@ async function runTopLevelAgentLoop(config, turnMetrics) {
2829
2204
  let returnValueResult;
2830
2205
  let currentMaxTokensOverride;
2831
2206
  let lastPatternMatch;
2832
- let compacting = false;
2207
+ let compacting = config.initialCompacting ?? false;
2833
2208
  let returnValueNudgeCount = 0;
2834
2209
  for (; ; ) {
2835
2210
  if (signal?.aborted) throw new Error("Aborted");
@@ -2952,18 +2327,9 @@ ${CONTINUE_PROMPT}` : CONTINUE_PROMPT;
2952
2327
  sessionManager.setCurrentContextSize(sessionId, result.usage.promptTokens);
2953
2328
  if (!compacting) {
2954
2329
  const contextState = sessionManager.getContextState(sessionId);
2955
- const { shouldCompact } = await import("./compactor-5VQNEYQX.js");
2330
+ const { shouldCompact, appendCompactionPrompt } = await import("./compactor-R7GRFBOU.js");
2956
2331
  if (shouldCompact(contextState.currentTokens, contextState.maxTokens, runtimeConfig.context.compactionThreshold)) {
2957
- const compactPromptMsgId = crypto.randomUUID();
2958
- append(
2959
- createMessageStartEvent(compactPromptMsgId, "user", COMPACTION_PROMPT, {
2960
- ...currentWindowMessageOptions ?? {},
2961
- isSystemGenerated: true,
2962
- messageKind: "auto-prompt",
2963
- metadata: { type: "compaction", name: "Compaction", color: "#64748b" }
2964
- })
2965
- );
2966
- append({ type: "message.done", data: { messageId: compactPromptMsgId } });
2332
+ appendCompactionPrompt(sessionId, append);
2967
2333
  compacting = true;
2968
2334
  continue;
2969
2335
  }
@@ -3112,6 +2478,7 @@ ${COMPACTION_PROMPT}`,
3112
2478
  });
3113
2479
  logger.warn("Compaction produced empty summary, continuing", { sessionId });
3114
2480
  compacting = false;
2481
+ if (config.initialCompacting) break;
3115
2482
  continue;
3116
2483
  }
3117
2484
  const closedWindowId = getCurrentContextWindowId(sessionId) ?? "";
@@ -3135,6 +2502,7 @@ ${COMPACTION_PROMPT}`,
3135
2502
  append(createChatDoneEvent(assistantMsgId, "complete"));
3136
2503
  config.injectAgentReminder?.();
3137
2504
  compacting = false;
2505
+ if (config.initialCompacting) break;
3138
2506
  continue;
3139
2507
  }
3140
2508
  if (config.requireReturnValue && !returnValueContent) {
@@ -3763,7 +3131,7 @@ var callSubAgentTool = {
3763
3131
  };
3764
3132
  }
3765
3133
  try {
3766
- const { getToolRegistryForAgent: getToolRegistryForAgent2 } = await import("./tools-SPZBVI7Y.js");
3134
+ const { getToolRegistryForAgent: getToolRegistryForAgent2 } = await import("./tools-THXBQJ7A.js");
3767
3135
  const toolRegistry = getToolRegistryForAgent2(agentDef);
3768
3136
  const turnMetrics = new TurnMetrics();
3769
3137
  const result = await executeSubAgent({
@@ -4583,6 +3951,9 @@ function validateToolAction(toolName, action, permissions) {
4583
3951
  }
4584
3952
  return void 0;
4585
3953
  }
3954
+ function extractSubAgentPrompt(args) {
3955
+ return args["prompt"] || args["query"] || args["task"] || "";
3956
+ }
4586
3957
  function createRegistryFromTools(tools, allowedTools, toolPermissions) {
4587
3958
  const toolMap = /* @__PURE__ */ new Map();
4588
3959
  const allowedToolsSet = new Set(allowedTools || []);
@@ -4595,6 +3966,22 @@ function createRegistryFromTools(tools, allowedTools, toolPermissions) {
4595
3966
  async execute(name, args, context) {
4596
3967
  const tool = toolMap.get(name);
4597
3968
  if (!tool) {
3969
+ if (toolMap.has("call_sub_agent")) {
3970
+ try {
3971
+ const agents = await loadAllAgentsDefault();
3972
+ const agentDef = findAgentById(name, agents);
3973
+ if (agentDef?.metadata.subagent) {
3974
+ const prompt = extractSubAgentPrompt(args);
3975
+ logger.warn("Sub-agent alias redirect", { from: name, to: "call_sub_agent", subAgentType: name });
3976
+ return callSubAgentTool.execute({ subAgentType: name, prompt }, context);
3977
+ }
3978
+ } catch (err) {
3979
+ logger.warn("Sub-agent alias resolution failed", {
3980
+ tool: name,
3981
+ error: err instanceof Error ? err.message : String(err)
3982
+ });
3983
+ }
3984
+ }
4598
3985
  return {
4599
3986
  success: false,
4600
3987
  error: `Unknown tool: ${name}. Available tools: ${tools.map((t) => t.name).join(", ")}`,
@@ -4768,20 +4155,6 @@ export {
4768
4155
  agentExists,
4769
4156
  saveAgent,
4770
4157
  deleteAgent,
4771
- buildBasePrompt,
4772
- buildTopLevelSystemPrompt,
4773
- buildAgentReminder,
4774
- buildAgentSmallReminder,
4775
- WORKFLOW_KICKOFF_PROMPT,
4776
- COMPACTION_PROMPT,
4777
- streamLLMPure,
4778
- TurnMetrics,
4779
- createMessageStartEvent,
4780
- createMessageDoneEvent,
4781
- createToolCallEvent,
4782
- createToolResultEvent,
4783
- createChatDoneEvent,
4784
- consumeStreamGenerator,
4785
4158
  getAllInstructions,
4786
4159
  loadDefaultSkills,
4787
4160
  loadUserSkills,
@@ -4813,4 +4186,4 @@ export {
4813
4186
  getToolRegistryForAgent,
4814
4187
  createToolRegistry
4815
4188
  };
4816
- //# sourceMappingURL=chunk-KGZMKMEZ.js.map
4189
+ //# sourceMappingURL=chunk-2VDLXCLO.js.map