forked from TinyAGI/tinyagi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvoke.ts
More file actions
238 lines (202 loc) · 8.35 KB
/
invoke.ts
File metadata and controls
238 lines (202 loc) · 8.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import { spawn } from 'child_process';
import fs from 'fs';
import path from 'path';
import { AgentConfig, TeamConfig } from './types';
import { SCRIPT_DIR, resolveClaudeModel, resolveCodexModel, resolveGeminiModel, resolveOpenCodeModel } from './config';
import { log } from './logging';
import { ensureAgentDirectory, updateAgentTeammates } from './agent';
export async function runCommand(command: string, args: string[], cwd?: string): Promise<string> {
return new Promise((resolve, reject) => {
const env = { ...process.env };
delete env.CLAUDECODE;
const child = spawn(command, args, {
cwd: cwd || SCRIPT_DIR,
stdio: ['ignore', 'pipe', 'pipe'],
env,
});
let stdout = '';
let stderr = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk: string) => {
stdout += chunk;
});
child.stderr.on('data', (chunk: string) => {
stderr += chunk;
});
child.on('error', (error) => {
reject(error);
});
child.on('close', (code) => {
if (code === 0) {
resolve(stdout);
return;
}
const errorMessage = stderr.trim() || `Command exited with code ${code}`;
reject(new Error(errorMessage));
});
});
}
/**
* Invoke a single agent with a message. Contains provider-specific invocation logic.
* Returns the raw response text.
*/
export async function invokeAgent(
agent: AgentConfig,
agentId: string,
message: string,
workspacePath: string,
shouldReset: boolean,
agents: Record<string, AgentConfig> = {},
teams: Record<string, TeamConfig> = {}
): Promise<string> {
// Ensure agent directory exists with config files
const agentDir = path.join(workspacePath, agentId);
const isNewAgent = !fs.existsSync(agentDir);
ensureAgentDirectory(agentDir);
if (isNewAgent) {
log('INFO', `Initialized agent directory with config files: ${agentDir}`);
}
// Update AGENTS.md with current teammate info
updateAgentTeammates(agentDir, agentId, agents, teams);
// Resolve working directory
const workingDir = agent.working_directory
? (path.isAbsolute(agent.working_directory)
? agent.working_directory
: path.join(workspacePath, agent.working_directory))
: agentDir;
const provider = agent.provider || 'anthropic';
if (provider === 'openai') {
log('INFO', `Using Codex CLI (agent: ${agentId})`);
const shouldResume = !shouldReset;
if (shouldReset) {
log('INFO', `🔄 Resetting Codex conversation for agent: ${agentId}`);
}
const modelId = resolveCodexModel(agent.model);
const codexArgs = ['exec'];
if (shouldResume) {
codexArgs.push('resume', '--last');
}
if (modelId) {
codexArgs.push('--model', modelId);
}
codexArgs.push('--skip-git-repo-check', '--dangerously-bypass-approvals-and-sandbox', '--json', message);
const codexOutput = await runCommand('codex', codexArgs, workingDir);
// Parse JSONL output and extract final agent_message
let response = '';
const lines = codexOutput.trim().split('\n');
for (const line of lines) {
try {
const json = JSON.parse(line);
if (json.type === 'item.completed' && json.item?.type === 'agent_message') {
response = json.item.text;
}
} catch (e) {
// Ignore lines that aren't valid JSON
}
}
return response || 'Sorry, I could not generate a response from Codex.';
} else if (provider === 'opencode') {
// OpenCode CLI — non-interactive mode via `opencode run`.
// Outputs JSONL with --format json; extract "text" type events for the response.
// Model passed via --model in provider/model format (e.g. opencode/claude-sonnet-4-5).
// Supports -c flag for conversation continuation (resumes last session).
const modelId = resolveOpenCodeModel(agent.model);
log('INFO', `Using OpenCode CLI (agent: ${agentId}, model: ${modelId})`);
const continueConversation = !shouldReset;
if (shouldReset) {
log('INFO', `🔄 Resetting OpenCode conversation for agent: ${agentId}`);
}
const opencodeArgs = ['run', '--format', 'json'];
if (modelId) {
opencodeArgs.push('--model', modelId);
}
if (continueConversation) {
opencodeArgs.push('-c');
}
opencodeArgs.push(message);
const opencodeOutput = await runCommand('opencode', opencodeArgs, workingDir);
// Parse JSONL output and collect all text parts
let response = '';
const lines = opencodeOutput.trim().split('\n');
for (const line of lines) {
try {
const json = JSON.parse(line);
if (json.type === 'text' && json.part?.text) {
response = json.part.text;
}
} catch (e) {
// Ignore lines that aren't valid JSON
}
}
return response || 'Sorry, I could not generate a response from OpenCode.';
} else if (provider === 'gemini') {
// Gemini CLI — non-interactive mode via --prompt.
// Uses --output-format json to return a single JSON object with a "response" field.
// Uses --resume latest for session continuation and retries fresh if resume is unavailable.
const modelId = resolveGeminiModel(agent.model);
log('INFO', `Using Gemini CLI (agent: ${agentId}, model: ${modelId || 'auto'})`);
const continueConversation = !shouldReset;
if (shouldReset) {
log('INFO', `🔄 Resetting Gemini conversation for agent: ${agentId}`);
}
const buildGeminiArgs = (withResume: boolean) => {
const args = ['--output-format', 'json', '--approval-mode', 'yolo'];
if (modelId) {
args.push('--model', modelId);
}
if (withResume) {
args.push('--resume', 'latest');
}
args.push('--prompt', message);
return args;
};
const parseGeminiOutput = (output: string): string | null => {
const trimmed = output.trim();
if (!trimmed) return null;
try {
const json = JSON.parse(trimmed);
if (typeof json.response === 'string' && json.response.trim()) {
return json.response;
}
if (json?.error?.message) {
return `Gemini CLI error: ${json.error.message}`;
}
} catch {
return trimmed;
}
return null;
};
let geminiOutput: string;
try {
geminiOutput = await runCommand('gemini', buildGeminiArgs(continueConversation), workingDir);
} catch (err: any) {
const errMsg = String(err?.message || '');
const resumeUnavailable = /(error resuming session|no .*session|session not found)/i.test(errMsg);
if (continueConversation && resumeUnavailable) {
log('INFO', `No resumable Gemini session for agent ${agentId}, starting fresh`);
geminiOutput = await runCommand('gemini', buildGeminiArgs(false), workingDir);
} else {
throw err;
}
}
return parseGeminiOutput(geminiOutput) || 'Sorry, I could not generate a response from Gemini.';
} else {
// Default to Claude (Anthropic)
log('INFO', `Using Claude provider (agent: ${agentId})`);
const continueConversation = !shouldReset;
if (shouldReset) {
log('INFO', `🔄 Resetting conversation for agent: ${agentId}`);
}
const modelId = resolveClaudeModel(agent.model);
const claudeArgs = ['--dangerously-skip-permissions'];
if (modelId) {
claudeArgs.push('--model', modelId);
}
if (continueConversation) {
claudeArgs.push('-c');
}
claudeArgs.push('-p', message);
return await runCommand('claude', claudeArgs, workingDir);
}
}