upfynai-code 2.9.0 → 2.9.2
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/README.md +91 -66
- package/client/dist/api-docs.html +838 -0
- package/client/dist/assets/AppContent-BXZDeSIC.js +545 -0
- package/client/dist/assets/CanvasFullScreen-mnpCnLZ9.js +1 -0
- package/client/dist/assets/CanvasWorkspace-4CqmjAVQ.js +163 -0
- package/client/dist/assets/DashboardPanel-zFIFlw56.js +1 -0
- package/client/dist/assets/FileTree-B0c_GaB3.js +1 -0
- package/client/dist/assets/GitPanel-DUP4zVU4.js +2 -0
- package/client/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/client/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/client/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/client/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/client/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/client/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/client/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/client/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/client/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/client/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/client/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/client/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/client/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/client/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/client/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/client/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/client/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/client/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/client/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/client/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/client/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/client/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/client/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/client/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/client/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/client/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/client/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/client/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/client/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/client/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/client/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/client/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/client/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/client/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/client/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/client/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/client/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/client/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/client/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/client/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/client/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/client/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/client/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/client/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/client/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/client/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/client/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/client/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/client/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/client/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/client/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/client/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/client/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/client/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/client/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/client/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/client/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/client/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/client/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/client/dist/assets/LoginModal-BRycfsyD.js +13 -0
- package/client/dist/assets/MarkdownPreview-DHmk3qzu.js +1 -0
- package/client/dist/assets/MermaidBlock-BuBc_G-F.js +2 -0
- package/client/dist/assets/Onboarding-BcnaZZ0o.js +1 -0
- package/client/dist/assets/PreviewPanel-CqCa92Tf.js +32 -0
- package/client/dist/assets/SetupForm-S0g6u5yT.js +1 -0
- package/client/dist/assets/WorkflowsPanel-CouH9JDO.js +1 -0
- package/client/dist/assets/index-BFuqS0tY.css +1 -0
- package/client/dist/assets/index-CNDcVl2g.js +68 -0
- package/client/dist/assets/pdf-CE_K4jFx.js +12 -0
- package/client/dist/assets/vendor-canvas-BZV40eAE.css +1 -0
- package/client/dist/assets/vendor-canvas-D39yWul6.js +49 -0
- package/client/dist/assets/vendor-codemirror-CbtmxxaB.js +35 -0
- package/client/dist/assets/vendor-diff-DNQpbhrT.js +69 -0
- package/client/dist/assets/vendor-i18n-DCFGyhQR.js +1 -0
- package/client/dist/assets/vendor-icons-BaD0x9SL.js +711 -0
- package/client/dist/assets/vendor-markdown-CimbIo6Y.js +296 -0
- package/client/dist/assets/vendor-mermaid-CH7SGc99.js +2556 -0
- package/client/dist/assets/vendor-react-96lCPsRK.js +67 -0
- package/client/dist/assets/vendor-syntax-DuHI9Ok6.js +16 -0
- package/client/dist/assets/vendor-xterm-CZq1hqo1.js +66 -0
- package/client/dist/assets/vendor-xterm-qxJ8_QYu.css +32 -0
- package/client/dist/clear-cache.html +85 -0
- package/client/dist/convert-icons.md +53 -0
- package/client/dist/favicon.png +0 -0
- package/client/dist/favicon.svg +5 -0
- package/client/dist/generate-icons.js +49 -0
- package/client/dist/icons/claude-ai-icon.svg +1 -0
- package/client/dist/icons/codex-white.svg +3 -0
- package/client/dist/icons/codex.svg +3 -0
- package/client/dist/icons/cursor-white.svg +12 -0
- package/client/dist/icons/cursor.svg +1 -0
- package/client/dist/icons/icon-128x128.png +0 -0
- package/client/dist/icons/icon-128x128.svg +5 -0
- package/client/dist/icons/icon-144x144.png +0 -0
- package/client/dist/icons/icon-144x144.svg +5 -0
- package/client/dist/icons/icon-152x152.png +0 -0
- package/client/dist/icons/icon-152x152.svg +5 -0
- package/client/dist/icons/icon-192x192.png +0 -0
- package/client/dist/icons/icon-192x192.svg +5 -0
- package/client/dist/icons/icon-384x384.png +0 -0
- package/client/dist/icons/icon-384x384.svg +5 -0
- package/client/dist/icons/icon-512x512.png +0 -0
- package/client/dist/icons/icon-512x512.svg +5 -0
- package/client/dist/icons/icon-72x72.png +0 -0
- package/client/dist/icons/icon-72x72.svg +5 -0
- package/client/dist/icons/icon-96x96.png +0 -0
- package/client/dist/icons/icon-96x96.svg +5 -0
- package/client/dist/icons/icon-template.svg +5 -0
- package/client/dist/index.html +119 -0
- package/client/dist/logo-128.png +0 -0
- package/client/dist/logo-256.png +0 -0
- package/client/dist/logo-32.png +0 -0
- package/client/dist/logo-512.png +0 -0
- package/client/dist/logo-64.png +0 -0
- package/client/dist/logo.svg +14 -0
- package/client/dist/manifest.json +61 -0
- package/client/dist/mcp-docs.html +108 -0
- package/client/dist/offline.html +84 -0
- package/client/dist/screenshots/cli-selection.png +0 -0
- package/client/dist/screenshots/desktop-main.png +0 -0
- package/client/dist/screenshots/mobile-chat.png +0 -0
- package/client/dist/screenshots/tools-modal.png +0 -0
- package/client/dist/sw.js +82 -0
- package/commands/upfynai-connect.md +59 -0
- package/commands/upfynai-disconnect.md +31 -0
- package/commands/upfynai-doctor.md +99 -0
- package/commands/upfynai-export.md +49 -0
- package/commands/upfynai-local.md +82 -0
- package/commands/upfynai-status.md +75 -0
- package/commands/upfynai-stop.md +49 -0
- package/commands/upfynai-uninstall.md +58 -0
- package/commands/upfynai.md +69 -0
- package/package.json +143 -82
- package/scripts/build-client.js +17 -0
- package/scripts/fix-node-pty.js +67 -0
- package/scripts/install-commands.js +78 -0
- package/server/agent-loop.js +242 -0
- package/server/auto-compact.js +99 -0
- package/server/claude-sdk.js +797 -0
- package/server/cli-ui.js +785 -0
- package/server/cli.js +596 -0
- package/server/constants/config.js +31 -0
- package/server/cursor-cli.js +270 -0
- package/server/database/auth.db +0 -0
- package/server/database/db.js +1391 -0
- package/server/database/init.sql +70 -0
- package/server/index.js +3799 -0
- package/server/load-env.js +26 -0
- package/server/mcp-server.js +621 -0
- package/server/middleware/auth.js +176 -0
- package/server/middleware/relayHelpers.js +44 -0
- package/server/middleware/sandboxRouter.js +174 -0
- package/server/openai-codex.js +403 -0
- package/server/openrouter.js +137 -0
- package/server/projects.js +1807 -0
- package/server/provider-factory.js +174 -0
- package/server/relay-client.js +379 -0
- package/server/routes/agent.js +1226 -0
- package/server/routes/auth.js +554 -0
- package/server/routes/canvas.js +53 -0
- package/server/routes/cli-auth.js +263 -0
- package/server/routes/codex.js +396 -0
- package/server/routes/commands.js +707 -0
- package/server/routes/composio.js +176 -0
- package/server/routes/cursor.js +770 -0
- package/server/routes/dashboard.js +295 -0
- package/server/routes/git.js +1208 -0
- package/server/routes/keys.js +34 -0
- package/server/routes/mcp-utils.js +48 -0
- package/server/routes/mcp.js +661 -0
- package/server/routes/payments.js +227 -0
- package/server/routes/projects.js +655 -0
- package/server/routes/sessions.js +146 -0
- package/server/routes/settings.js +261 -0
- package/server/routes/taskmaster.js +1928 -0
- package/server/routes/user.js +106 -0
- package/server/routes/vapi-chat.js +624 -0
- package/server/routes/voice.js +235 -0
- package/server/routes/webhooks.js +166 -0
- package/server/routes/workflows.js +312 -0
- package/server/sandbox.js +120 -0
- package/server/services/composio.js +204 -0
- package/server/services/sessionRegistry.js +139 -0
- package/server/services/whisperService.js +84 -0
- package/server/services/workflowScheduler.js +206 -0
- package/server/tests/relay-flow.test.js +570 -0
- package/server/tests/sessions.test.js +259 -0
- package/server/utils/commandParser.js +303 -0
- package/server/utils/email.js +61 -0
- package/server/utils/gitConfig.js +24 -0
- package/server/utils/mcp-detector.js +198 -0
- package/server/utils/taskmaster-websocket.js +129 -0
- package/shared/integrationCatalog.d.ts +12 -0
- package/shared/integrationCatalog.js +172 -0
- package/shared/modelConstants.js +96 -0
- package/bin/cli.js +0 -97
- package/dist/agents/claude.js +0 -229
- package/dist/agents/codex.js +0 -48
- package/dist/agents/cursor.js +0 -48
- package/dist/agents/detect.js +0 -51
- package/dist/agents/exec.js +0 -31
- package/dist/agents/files.js +0 -105
- package/dist/agents/git.js +0 -18
- package/dist/agents/gitagent.js +0 -67
- package/dist/agents/index.js +0 -88
- package/dist/agents/shell.js +0 -38
- package/dist/agents/utils.js +0 -136
- package/scripts/postinstall.js +0 -9
- package/scripts/prepublish.js +0 -58
- package/src/animation.js +0 -228
- package/src/auth.js +0 -122
- package/src/config.js +0 -40
- package/src/connect.js +0 -416
- package/src/launch.js +0 -78
- package/src/mcp.js +0 -57
- package/src/permissions.js +0 -140
- package/src/persistent-shell.js +0 -261
- package/src/server.js +0 -54
- /package/{dist → shared}/gitagent/index.js +0 -0
- /package/{dist → shared}/gitagent/parser.js +0 -0
- /package/{dist → shared}/gitagent/prompt-builder.js +0 -0
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent Loop: Stream → Tool Execute → Loop
|
|
3
|
+
* Ported from opencode-ai/opencode internal/llm/agent/agent.go
|
|
4
|
+
*
|
|
5
|
+
* For cloud mode (BYOK): when the AI returns tool_use calls, execute them
|
|
6
|
+
* server-side (or via relay), append results, and loop until no more tool calls.
|
|
7
|
+
*
|
|
8
|
+
* This implements the core agentic loop pattern:
|
|
9
|
+
* 1. Stream response from LLM
|
|
10
|
+
* 2. Collect tool calls from the response
|
|
11
|
+
* 3. Execute tools (file read, shell, etc.)
|
|
12
|
+
* 4. Append tool results to message history
|
|
13
|
+
* 5. Loop back to step 1 until AI finishes without tool calls
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { streamChat, calculateCost } from './provider-factory.js';
|
|
17
|
+
import { checkNeedsCompact, buildSummarizationPrompt, compactMessages } from './auto-compact.js';
|
|
18
|
+
|
|
19
|
+
const MAX_TOOL_LOOPS = 25; // Safety limit to prevent infinite loops
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Available server-side tools (opencode pattern: tool registry per agent type)
|
|
23
|
+
* These are tools the AI can call during the agent loop.
|
|
24
|
+
* For relay mode, tool execution is forwarded to the CLI.
|
|
25
|
+
* For cloud mode, tools execute on the server or sandbox.
|
|
26
|
+
*/
|
|
27
|
+
const TOOLS_SCHEMA = [
|
|
28
|
+
{
|
|
29
|
+
type: 'function',
|
|
30
|
+
function: {
|
|
31
|
+
name: 'read_file',
|
|
32
|
+
description: 'Read the contents of a file',
|
|
33
|
+
parameters: {
|
|
34
|
+
type: 'object',
|
|
35
|
+
properties: {
|
|
36
|
+
path: { type: 'string', description: 'File path to read' },
|
|
37
|
+
},
|
|
38
|
+
required: ['path'],
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
type: 'function',
|
|
44
|
+
function: {
|
|
45
|
+
name: 'write_file',
|
|
46
|
+
description: 'Write content to a file',
|
|
47
|
+
parameters: {
|
|
48
|
+
type: 'object',
|
|
49
|
+
properties: {
|
|
50
|
+
path: { type: 'string', description: 'File path to write' },
|
|
51
|
+
content: { type: 'string', description: 'File content' },
|
|
52
|
+
},
|
|
53
|
+
required: ['path', 'content'],
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
type: 'function',
|
|
59
|
+
function: {
|
|
60
|
+
name: 'run_command',
|
|
61
|
+
description: 'Execute a shell command',
|
|
62
|
+
parameters: {
|
|
63
|
+
type: 'object',
|
|
64
|
+
properties: {
|
|
65
|
+
command: { type: 'string', description: 'Shell command to run' },
|
|
66
|
+
cwd: { type: 'string', description: 'Working directory (optional)' },
|
|
67
|
+
},
|
|
68
|
+
required: ['command'],
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
type: 'function',
|
|
74
|
+
function: {
|
|
75
|
+
name: 'list_files',
|
|
76
|
+
description: 'List files in a directory',
|
|
77
|
+
parameters: {
|
|
78
|
+
type: 'object',
|
|
79
|
+
properties: {
|
|
80
|
+
path: { type: 'string', description: 'Directory path' },
|
|
81
|
+
pattern: { type: 'string', description: 'Glob pattern (optional)' },
|
|
82
|
+
},
|
|
83
|
+
required: ['path'],
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
type: 'function',
|
|
89
|
+
function: {
|
|
90
|
+
name: 'search_files',
|
|
91
|
+
description: 'Search for text in files',
|
|
92
|
+
parameters: {
|
|
93
|
+
type: 'object',
|
|
94
|
+
properties: {
|
|
95
|
+
query: { type: 'string', description: 'Search query (regex)' },
|
|
96
|
+
path: { type: 'string', description: 'Directory to search in' },
|
|
97
|
+
},
|
|
98
|
+
required: ['query'],
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
];
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Run the agent loop (opencode pattern: processGeneration).
|
|
106
|
+
*
|
|
107
|
+
* @param {string} model - LLM model name
|
|
108
|
+
* @param {Array} messages - Message history
|
|
109
|
+
* @param {object} options - { apiKey, systemPrompt, onEvent, executeTool, maxLoops }
|
|
110
|
+
* @returns {Promise<{ messages, usage, cost }>}
|
|
111
|
+
*
|
|
112
|
+
* options.onEvent(event) - Called for each streaming event:
|
|
113
|
+
* { type: 'content_delta', content: '...' }
|
|
114
|
+
* { type: 'tool_call', name: '...', input: {...} }
|
|
115
|
+
* { type: 'tool_result', name: '...', output: '...' }
|
|
116
|
+
* { type: 'complete' }
|
|
117
|
+
* { type: 'error', error: '...' }
|
|
118
|
+
*
|
|
119
|
+
* options.executeTool(name, input) - Executes a tool, returns string result.
|
|
120
|
+
* If not provided, tool calls are skipped (text-only mode).
|
|
121
|
+
*/
|
|
122
|
+
export async function runAgentLoop(model, messages, options = {}) {
|
|
123
|
+
const {
|
|
124
|
+
apiKey,
|
|
125
|
+
systemPrompt,
|
|
126
|
+
onEvent = () => {},
|
|
127
|
+
executeTool,
|
|
128
|
+
maxLoops = MAX_TOOL_LOOPS,
|
|
129
|
+
} = options;
|
|
130
|
+
|
|
131
|
+
let totalUsage = { promptTokens: 0, completionTokens: 0 };
|
|
132
|
+
let loopCount = 0;
|
|
133
|
+
let currentMessages = [...messages];
|
|
134
|
+
|
|
135
|
+
// Add system prompt if provided
|
|
136
|
+
if (systemPrompt && (!currentMessages.length || currentMessages[0].role !== 'system')) {
|
|
137
|
+
currentMessages.unshift({ role: 'system', content: systemPrompt });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
while (loopCount < maxLoops) {
|
|
141
|
+
loopCount++;
|
|
142
|
+
|
|
143
|
+
// Check if we need auto-compact (opencode pattern: summarize at 85% context)
|
|
144
|
+
const compactCheck = checkNeedsCompact(currentMessages, model);
|
|
145
|
+
if (compactCheck.needsCompact) {
|
|
146
|
+
onEvent({ type: 'system', message: 'Compacting conversation context...' });
|
|
147
|
+
// In a real implementation, this would call the LLM to summarize
|
|
148
|
+
// For now, just trim old messages
|
|
149
|
+
if (currentMessages.length > 10) {
|
|
150
|
+
const recent = currentMessages.slice(-6);
|
|
151
|
+
currentMessages = [currentMessages[0], ...recent]; // keep system + recent
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Stream response from LLM
|
|
156
|
+
let assistantContent = '';
|
|
157
|
+
let toolCalls = [];
|
|
158
|
+
let currentToolCall = null;
|
|
159
|
+
|
|
160
|
+
try {
|
|
161
|
+
for await (const event of streamChat(model, currentMessages, {
|
|
162
|
+
apiKey,
|
|
163
|
+
tools: executeTool ? TOOLS_SCHEMA : undefined,
|
|
164
|
+
})) {
|
|
165
|
+
if (event.type === 'content_delta') {
|
|
166
|
+
assistantContent += event.content;
|
|
167
|
+
onEvent({ type: 'content_delta', content: event.content });
|
|
168
|
+
} else if (event.type === 'tool_call_start') {
|
|
169
|
+
currentToolCall = { name: event.name, id: event.id, input: '' };
|
|
170
|
+
} else if (event.type === 'tool_call_delta') {
|
|
171
|
+
if (currentToolCall) currentToolCall.input += event.content;
|
|
172
|
+
} else if (event.type === 'tool_call_end') {
|
|
173
|
+
if (currentToolCall) {
|
|
174
|
+
try { currentToolCall.input = JSON.parse(currentToolCall.input); } catch {}
|
|
175
|
+
toolCalls.push(currentToolCall);
|
|
176
|
+
onEvent({ type: 'tool_call', name: currentToolCall.name, input: currentToolCall.input });
|
|
177
|
+
currentToolCall = null;
|
|
178
|
+
}
|
|
179
|
+
} else if (event.type === 'usage') {
|
|
180
|
+
totalUsage.promptTokens += event.promptTokens;
|
|
181
|
+
totalUsage.completionTokens += event.completionTokens;
|
|
182
|
+
} else if (event.type === 'complete') {
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
} catch (err) {
|
|
187
|
+
onEvent({ type: 'error', error: err.message });
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Append assistant message
|
|
192
|
+
const assistantMsg = { role: 'assistant', content: assistantContent };
|
|
193
|
+
if (toolCalls.length > 0) {
|
|
194
|
+
assistantMsg.tool_calls = toolCalls.map(tc => ({
|
|
195
|
+
id: tc.id || `call_${Date.now()}`,
|
|
196
|
+
type: 'function',
|
|
197
|
+
function: { name: tc.name, arguments: JSON.stringify(tc.input) },
|
|
198
|
+
}));
|
|
199
|
+
}
|
|
200
|
+
currentMessages.push(assistantMsg);
|
|
201
|
+
|
|
202
|
+
// If no tool calls, we're done (opencode pattern: finish reason != ToolUse → return)
|
|
203
|
+
if (toolCalls.length === 0 || !executeTool) {
|
|
204
|
+
onEvent({ type: 'complete' });
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Execute tools and append results (opencode pattern: tool execution loop)
|
|
209
|
+
for (const tc of toolCalls) {
|
|
210
|
+
let result;
|
|
211
|
+
try {
|
|
212
|
+
result = await executeTool(tc.name, tc.input);
|
|
213
|
+
onEvent({ type: 'tool_result', name: tc.name, output: result });
|
|
214
|
+
} catch (err) {
|
|
215
|
+
result = `Error: ${err.message}`;
|
|
216
|
+
onEvent({ type: 'tool_result', name: tc.name, output: result, isError: true });
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
currentMessages.push({
|
|
220
|
+
role: 'tool',
|
|
221
|
+
tool_call_id: tc.id || `call_${Date.now()}`,
|
|
222
|
+
content: typeof result === 'string' ? result : JSON.stringify(result),
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// Loop back to get next response (step 5 → step 1)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (loopCount >= maxLoops) {
|
|
230
|
+
onEvent({ type: 'error', error: `Agent loop exceeded maximum iterations (${maxLoops})` });
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const cost = calculateCost(model, totalUsage.promptTokens, totalUsage.completionTokens);
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
messages: currentMessages,
|
|
237
|
+
usage: totalUsage,
|
|
238
|
+
costCents: cost,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export { TOOLS_SCHEMA };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auto-Compact Context Summarization
|
|
3
|
+
* Ported from opencode-ai/opencode internal/llm/agent/agent.go (summarize logic)
|
|
4
|
+
*
|
|
5
|
+
* When a conversation approaches the context window limit, this module
|
|
6
|
+
* summarizes the conversation and returns a condensed version.
|
|
7
|
+
*
|
|
8
|
+
* Used for BYOK cloud mode (OpenRouter, direct API calls) where the server
|
|
9
|
+
* manages the message history. For relay mode, the CLI handles context internally.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
// Model context windows (opencode pattern: models.go ContextWindow)
|
|
13
|
+
const CONTEXT_WINDOWS = {
|
|
14
|
+
'claude-sonnet-4-20250514': 200000,
|
|
15
|
+
'claude-opus-4-20250514': 200000,
|
|
16
|
+
'claude-haiku-4-5-20251001': 200000,
|
|
17
|
+
'gpt-4o': 128000,
|
|
18
|
+
'gpt-4o-mini': 128000,
|
|
19
|
+
'o1': 200000,
|
|
20
|
+
'o3-mini': 200000,
|
|
21
|
+
'deepseek-chat': 64000,
|
|
22
|
+
'deepseek-reasoner': 64000,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// Rough token estimation (~4 chars per token)
|
|
26
|
+
function estimateTokens(text) {
|
|
27
|
+
return Math.ceil((text || '').length / 4);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Check if a message history needs compaction.
|
|
32
|
+
* @param {Array} messages - Array of { role, content } messages
|
|
33
|
+
* @param {string} model - Model name
|
|
34
|
+
* @param {number} threshold - Fraction of context window to trigger (default 0.85)
|
|
35
|
+
* @returns {{ needsCompact: boolean, estimatedTokens: number, contextWindow: number }}
|
|
36
|
+
*/
|
|
37
|
+
export function checkNeedsCompact(messages, model, threshold = 0.85) {
|
|
38
|
+
const contextWindow = CONTEXT_WINDOWS[model] || 128000;
|
|
39
|
+
const totalTokens = messages.reduce((sum, m) => sum + estimateTokens(m.content), 0);
|
|
40
|
+
return {
|
|
41
|
+
needsCompact: totalTokens > contextWindow * threshold,
|
|
42
|
+
estimatedTokens: totalTokens,
|
|
43
|
+
contextWindow,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Build a summarization prompt for compacting conversation history.
|
|
49
|
+
* Returns messages array suitable for sending to an LLM.
|
|
50
|
+
*
|
|
51
|
+
* @param {Array} messages - Full message history
|
|
52
|
+
* @param {string} systemPrompt - Original system prompt
|
|
53
|
+
* @returns {Array} Messages for the summarization call
|
|
54
|
+
*/
|
|
55
|
+
export function buildSummarizationPrompt(messages, systemPrompt = '') {
|
|
56
|
+
// Take the conversation content and ask for a summary
|
|
57
|
+
// (opencode pattern: AgentSummarizer with dedicated prompt)
|
|
58
|
+
const conversationText = messages
|
|
59
|
+
.map(m => `[${m.role}]: ${(m.content || '').slice(0, 2000)}`)
|
|
60
|
+
.join('\n\n');
|
|
61
|
+
|
|
62
|
+
return [
|
|
63
|
+
{
|
|
64
|
+
role: 'system',
|
|
65
|
+
content: `You are a conversation summarizer. Summarize the following conversation between a user and an AI coding assistant. Focus on:
|
|
66
|
+
1. Key decisions made
|
|
67
|
+
2. Files modified and why
|
|
68
|
+
3. Current state of the task
|
|
69
|
+
4. Any unresolved issues or next steps
|
|
70
|
+
|
|
71
|
+
Keep the summary concise but preserve all critical technical details. The summary will be used as context for continuing the conversation.`,
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
role: 'user',
|
|
75
|
+
content: `Summarize this conversation:\n\n${conversationText}`,
|
|
76
|
+
},
|
|
77
|
+
];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Compact a message history by replacing old messages with a summary.
|
|
82
|
+
* The summary becomes the first message, preserving the most recent messages.
|
|
83
|
+
*
|
|
84
|
+
* @param {Array} messages - Full message history
|
|
85
|
+
* @param {string} summary - Generated summary text
|
|
86
|
+
* @param {number} keepRecent - Number of recent messages to keep verbatim (default 4)
|
|
87
|
+
* @returns {Array} Compacted messages
|
|
88
|
+
*/
|
|
89
|
+
export function compactMessages(messages, summary, keepRecent = 4) {
|
|
90
|
+
const recentMessages = messages.slice(-keepRecent);
|
|
91
|
+
|
|
92
|
+
return [
|
|
93
|
+
{
|
|
94
|
+
role: 'system',
|
|
95
|
+
content: `[Conversation Summary]\n${summary}\n\n[The conversation continues below with the most recent messages]`,
|
|
96
|
+
},
|
|
97
|
+
...recentMessages,
|
|
98
|
+
];
|
|
99
|
+
}
|