agent-termo 1.0.3 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +96 -85
- package/dist/cli.js.map +3 -3
- package/dist/main.js +81 -70
- package/dist/main.js.map +3 -3
- package/package.json +1 -1
- package/src/agents/index.ts +3 -2
- package/src/cli.ts +1 -1
- package/src/llm/client.ts +63 -20
- package/src/llm/tools.ts +21 -7
- package/src/main.ts +91 -85
- package/src/memory/index.ts +49 -13
- package/src/tools/index.ts +22 -2
- package/src/types/index.ts +2 -0
package/package.json
CHANGED
package/src/agents/index.ts
CHANGED
|
@@ -12,7 +12,7 @@ function parseAgentMeta(content: string): { description: string; tools: string[]
|
|
|
12
12
|
const toolsStr = toolsMatch?.[1] ?? '';
|
|
13
13
|
const tools = toolsStr
|
|
14
14
|
? toolsStr.split(',').map((t) => t.trim().replace(/^["']|["']$/g, ''))
|
|
15
|
-
: ['file:read', 'file:write', 'file:edit', 'file:glob', 'grep', 'bash:execute', 'git:status', 'git:commit', 'git:push', 'git:log'];
|
|
15
|
+
: ['file:read', 'file:write', 'file:edit', 'file:delete', 'file:glob', 'grep', 'bash:execute', 'git:status', 'git:commit', 'git:push', 'git:log'];
|
|
16
16
|
return { description: descMatch?.[1]?.trim() ?? '', tools };
|
|
17
17
|
}
|
|
18
18
|
|
|
@@ -68,6 +68,7 @@ Available functions:
|
|
|
68
68
|
- file:read(path) → read a file
|
|
69
69
|
- file:write(path, content) → overwrite a file completely
|
|
70
70
|
- file:edit(path, old_string, new_string) → edit a specific line section
|
|
71
|
+
- file:delete(path) → delete a file after explicit user instruction
|
|
71
72
|
- file:glob(pattern) → list files matching a glob (e.g. "src/**/*.ts")
|
|
72
73
|
- grep(pattern, path, glob?) → search for text in files
|
|
73
74
|
- bash:execute(command) → run a shell command
|
|
@@ -91,4 +92,4 @@ export function buildSystemPrompt(memory: string, timeline: string, _agentDir: s
|
|
|
91
92
|
}
|
|
92
93
|
|
|
93
94
|
return prompt;
|
|
94
|
-
}
|
|
95
|
+
}
|
package/src/cli.ts
CHANGED
|
@@ -96,7 +96,7 @@ async function startAgent(
|
|
|
96
96
|
program
|
|
97
97
|
.name('agent-termo')
|
|
98
98
|
.description('Terminal AI coding agent with Nvidia NIM APIs')
|
|
99
|
-
.version('1.0.
|
|
99
|
+
.version('1.0.3')
|
|
100
100
|
.argument('[project]', 'Project directory to operate in', process.cwd())
|
|
101
101
|
.option('-k, --api-key <key>', 'Nvidia NIM API key')
|
|
102
102
|
.option('-m, --model <model>', 'Model name to use')
|
package/src/llm/client.ts
CHANGED
|
@@ -8,6 +8,27 @@ import { mergeModels, type ModelInfo } from './models.js';
|
|
|
8
8
|
|
|
9
9
|
type NIMTool = OpenAI.Chat.ChatCompletionTool;
|
|
10
10
|
|
|
11
|
+
const TOOL_NAME_ALIASES: Record<string, string> = {
|
|
12
|
+
'file:read': 'file_read',
|
|
13
|
+
'file:write': 'file_write',
|
|
14
|
+
'file:edit': 'file_edit',
|
|
15
|
+
'file:delete': 'file_delete',
|
|
16
|
+
'file:glob': 'file_glob',
|
|
17
|
+
'bash:execute': 'bash_execute',
|
|
18
|
+
'git:status': 'git_status',
|
|
19
|
+
'git:commit': 'git_commit',
|
|
20
|
+
'git:push': 'git_push',
|
|
21
|
+
'git:log': 'git_log',
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export function toWireToolName(name: string): string {
|
|
25
|
+
return TOOL_NAME_ALIASES[name] ?? name.replace(/:/g, '_');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function fromWireToolName(name: string): string {
|
|
29
|
+
return Object.entries(TOOL_NAME_ALIASES).find(([, wireName]) => wireName === name)?.[0] ?? name;
|
|
30
|
+
}
|
|
31
|
+
|
|
11
32
|
export class NimClient {
|
|
12
33
|
private client: OpenAI;
|
|
13
34
|
private model: string;
|
|
@@ -30,7 +51,7 @@ export class NimClient {
|
|
|
30
51
|
return toolSchemas.map((t) => ({
|
|
31
52
|
type: 'function' as const,
|
|
32
53
|
function: {
|
|
33
|
-
|
|
54
|
+
name: toWireToolName(t.name),
|
|
34
55
|
description: t.description,
|
|
35
56
|
parameters: t.parameters as unknown as NIMTool['function']['parameters'],
|
|
36
57
|
},
|
|
@@ -69,7 +90,7 @@ export class NimClient {
|
|
|
69
90
|
* Handles Stepfun's quirks: filters "null" reasoning chunks, strips reasoning field.
|
|
70
91
|
* Yields { content, toolCalls } at the end with clean text.
|
|
71
92
|
*/
|
|
72
|
-
|
|
93
|
+
async *streamComplete(
|
|
73
94
|
messages: ConversationMessage[],
|
|
74
95
|
tools?: NIMTool[],
|
|
75
96
|
onChunk?: (text: string) => void,
|
|
@@ -79,15 +100,26 @@ export class NimClient {
|
|
|
79
100
|
|
|
80
101
|
const stream = await this.client.chat.completions.create({
|
|
81
102
|
model: this.model,
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
103
|
+
messages: messages.map((m) => {
|
|
104
|
+
if (m.role === 'tool') {
|
|
105
|
+
return {
|
|
106
|
+
role: 'tool' as const,
|
|
107
|
+
content: m.content,
|
|
108
|
+
tool_call_id: m.id,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
if (m.role === 'assistant' && m.toolCalls?.length) {
|
|
112
|
+
return {
|
|
113
|
+
role: 'assistant' as const,
|
|
114
|
+
content: m.content || null,
|
|
115
|
+
tool_calls: m.toolCalls.map((tc) => ({
|
|
116
|
+
id: tc.id,
|
|
117
|
+
type: 'function' as const,
|
|
118
|
+
function: { name: toWireToolName(tc.name), arguments: JSON.stringify(tc.arguments) },
|
|
119
|
+
})),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
91
123
|
role: m.role as 'system' | 'user' | 'assistant',
|
|
92
124
|
content: m.content,
|
|
93
125
|
};
|
|
@@ -143,7 +175,7 @@ export class NimClient {
|
|
|
143
175
|
} catch {
|
|
144
176
|
args = { _raw: tc.arguments };
|
|
145
177
|
}
|
|
146
|
-
|
|
178
|
+
return { id: tc.id, name: fromWireToolName(tc.name), arguments: args };
|
|
147
179
|
});
|
|
148
180
|
|
|
149
181
|
yield { content: finalContent, toolCalls };
|
|
@@ -158,11 +190,22 @@ export class NimClient {
|
|
|
158
190
|
): Promise<{ content: string; toolCalls: ToolCall[] }> {
|
|
159
191
|
const response = await this.client.chat.completions.create({
|
|
160
192
|
model: this.model,
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
193
|
+
messages: messages.map((m) => {
|
|
194
|
+
if (m.role === 'tool') {
|
|
195
|
+
return { role: 'tool' as const, content: m.content, tool_call_id: m.id };
|
|
196
|
+
}
|
|
197
|
+
if (m.role === 'assistant' && m.toolCalls?.length) {
|
|
198
|
+
return {
|
|
199
|
+
role: 'assistant' as const,
|
|
200
|
+
content: m.content || null,
|
|
201
|
+
tool_calls: m.toolCalls.map((tc) => ({
|
|
202
|
+
id: tc.id,
|
|
203
|
+
type: 'function' as const,
|
|
204
|
+
function: { name: toWireToolName(tc.name), arguments: JSON.stringify(tc.arguments) },
|
|
205
|
+
})),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
return { role: m.role as 'system' | 'user' | 'assistant', content: m.content };
|
|
166
209
|
}),
|
|
167
210
|
tools: tools,
|
|
168
211
|
temperature: 0.3,
|
|
@@ -185,7 +228,7 @@ export class NimClient {
|
|
|
185
228
|
} catch {
|
|
186
229
|
args = { _raw: tc.function.arguments };
|
|
187
230
|
}
|
|
188
|
-
|
|
231
|
+
return { id: tc.id, name: fromWireToolName(tc.function.name), arguments: args };
|
|
189
232
|
});
|
|
190
233
|
|
|
191
234
|
// If no tool calls but content looks like a tool call request, parse it
|
|
@@ -195,7 +238,7 @@ export class NimClient {
|
|
|
195
238
|
if (parsed.tool_calls?.length) {
|
|
196
239
|
toolCalls.push(...parsed.tool_calls.map((tc: { id?: string; name?: string; function?: { name?: string; arguments?: unknown } }) => ({
|
|
197
240
|
id: tc.id ?? crypto.randomUUID(),
|
|
198
|
-
|
|
241
|
+
name: fromWireToolName(tc.function?.name ?? tc.name ?? ''),
|
|
199
242
|
arguments: typeof tc.function?.arguments === 'string'
|
|
200
243
|
? JSON.parse(tc.function.arguments)
|
|
201
244
|
: tc.function?.arguments ?? {},
|
|
@@ -213,4 +256,4 @@ export class NimClient {
|
|
|
213
256
|
}
|
|
214
257
|
}
|
|
215
258
|
|
|
216
|
-
export { type ToolDef } from '../types/index.js';
|
|
259
|
+
export { type ToolDef } from '../types/index.js';
|
package/src/llm/tools.ts
CHANGED
|
@@ -67,12 +67,26 @@ export const TOOL_DEFINITIONS: ToolDef[] = [
|
|
|
67
67
|
type: 'string',
|
|
68
68
|
description: 'Replacement text',
|
|
69
69
|
},
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
70
|
+
},
|
|
71
|
+
required: ['path', 'old_string', 'new_string'],
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
name: 'file:delete',
|
|
76
|
+
description: 'Delete a file from the project. Use only when the user explicitly asks to remove it.',
|
|
77
|
+
parameters: {
|
|
78
|
+
type: 'object',
|
|
79
|
+
properties: {
|
|
80
|
+
path: {
|
|
81
|
+
type: 'string',
|
|
82
|
+
description: 'File path to delete (relative to project root)',
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
required: ['path'],
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
name: 'file:glob',
|
|
76
90
|
description: 'Find all files matching a glob pattern. Use to discover project structure.',
|
|
77
91
|
parameters: {
|
|
78
92
|
type: 'object',
|
|
@@ -203,4 +217,4 @@ export const TOOL_DEFINITIONS: ToolDef[] = [
|
|
|
203
217
|
},
|
|
204
218
|
},
|
|
205
219
|
},
|
|
206
|
-
];
|
|
220
|
+
];
|
package/src/main.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Agent-Termo — Main REPL entry point
|
|
3
3
|
// =============================================================================
|
|
4
4
|
|
|
5
|
-
import { NimClient } from './llm/client.js';
|
|
5
|
+
import { NimClient, fromWireToolName } from './llm/client.js';
|
|
6
6
|
import { TOOL_DEFINITIONS } from './llm/tools.js';
|
|
7
7
|
import { executeTool, applyFileChange } from './tools/index.js';
|
|
8
8
|
import { loadMemory, logToTimeline, logAgentTermoTimeline } from './memory/index.js';
|
|
@@ -42,16 +42,6 @@ const TOOL_KEYWORDS = [
|
|
|
42
42
|
'test', 'compile', 'typescript', 'javascript', 'python', 'node', 'add', 'delete',
|
|
43
43
|
];
|
|
44
44
|
|
|
45
|
-
/**
|
|
46
|
-
* Tool-capable models to try when the active model rejects the `tools` parameter.
|
|
47
|
-
* Ordered by preference; first one that accepts tool calls wins.
|
|
48
|
-
*/
|
|
49
|
-
const TOOL_MODELS = [
|
|
50
|
-
'qwen/qwen2.5-coder-32b-instruct',
|
|
51
|
-
'moonshotai/kimi-k2-instruct',
|
|
52
|
-
'meta/llama-3.1-405b-instruct',
|
|
53
|
-
];
|
|
54
|
-
|
|
55
45
|
function mightNeedTools(message: string): boolean {
|
|
56
46
|
const lower = message.toLowerCase();
|
|
57
47
|
return TOOL_KEYWORDS.some((w) => lower.includes(w));
|
|
@@ -66,31 +56,6 @@ function dedup(arr: ToolCall[]): ToolCall[] {
|
|
|
66
56
|
});
|
|
67
57
|
}
|
|
68
58
|
|
|
69
|
-
/**
|
|
70
|
-
* Try each tool-capable model in TOOL_MODELS order until one accepts the
|
|
71
|
-
* `tools` parameter. Restores the original model in a finally block.
|
|
72
|
-
* Returns the first successful result, or null if all models fail.
|
|
73
|
-
*/
|
|
74
|
-
async function tryToolModels(
|
|
75
|
-
conversation: ConversationMessage[],
|
|
76
|
-
nimClient: NimClient,
|
|
77
|
-
originalModel: string,
|
|
78
|
-
): Promise<{ content: string; toolCalls: ToolCall[] } | null> {
|
|
79
|
-
for (const toolModel of TOOL_MODELS) {
|
|
80
|
-
if (toolModel === originalModel) continue;
|
|
81
|
-
try {
|
|
82
|
-
nimClient.setModel(toolModel);
|
|
83
|
-
const tools = nimClient.buildToolDefs(TOOL_DEFINITIONS);
|
|
84
|
-
const result = await nimClient.complete(conversation, tools);
|
|
85
|
-
return result;
|
|
86
|
-
} catch {
|
|
87
|
-
// Try the next model
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
nimClient.setModel(originalModel);
|
|
91
|
-
return null;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
59
|
/**
|
|
95
60
|
* Get a plain-text assistant response without tool calling: stream first, fall
|
|
96
61
|
* back to a single non-streaming completion. Appends the assistant message to
|
|
@@ -136,8 +101,42 @@ async function replyWithText(
|
|
|
136
101
|
}
|
|
137
102
|
}
|
|
138
103
|
|
|
104
|
+
/**
|
|
105
|
+
* Parse JSON tool calls that a non-tool-calling model may emit as plain text,
|
|
106
|
+
* e.g. {"tool_calls":[{"id":"call_1","name":"file:write","arguments":{...}}]}.
|
|
107
|
+
* Returns an empty array when nothing parseable is found.
|
|
108
|
+
*/
|
|
109
|
+
function parseToolCallsFromText(text: string): ToolCall[] {
|
|
110
|
+
let cleaned = (text ?? '').trim();
|
|
111
|
+
cleaned = cleaned.replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/i, '').trim();
|
|
112
|
+
|
|
113
|
+
let obj: { tool_calls?: unknown };
|
|
114
|
+
try {
|
|
115
|
+
obj = JSON.parse(cleaned);
|
|
116
|
+
} catch {
|
|
117
|
+
const start = cleaned.indexOf('{');
|
|
118
|
+
const end = cleaned.lastIndexOf('}');
|
|
119
|
+
if (start === -1 || end === -1 || end <= start) return [];
|
|
120
|
+
try {
|
|
121
|
+
obj = JSON.parse(cleaned.slice(start, end + 1));
|
|
122
|
+
} catch {
|
|
123
|
+
return [];
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const rawCalls = Array.isArray(obj.tool_calls) ? obj.tool_calls : [];
|
|
128
|
+
return rawCalls.map((tc: { id?: string; name?: string; function?: { name?: string; arguments?: unknown } }) => ({
|
|
129
|
+
id: tc.id ?? crypto.randomUUID(),
|
|
130
|
+
name: fromWireToolName(tc.name ?? (tc.function?.name ?? '')),
|
|
131
|
+
arguments:
|
|
132
|
+
typeof tc.function?.arguments === 'string'
|
|
133
|
+
? (() => { try { return JSON.parse(tc.function.arguments as string); } catch { return { _raw: tc.function.arguments }; } })()
|
|
134
|
+
: (tc.function?.arguments ?? {}),
|
|
135
|
+
}));
|
|
136
|
+
}
|
|
137
|
+
|
|
139
138
|
function extractProposedChange(toolName: string, resultOutput: string): ProposedFileChange | undefined {
|
|
140
|
-
const isFileTool = toolName === 'file:write' || toolName === 'file:edit';
|
|
139
|
+
const isFileTool = toolName === 'file:write' || toolName === 'file:edit' || toolName === 'file:delete';
|
|
141
140
|
if (!isFileTool) return undefined;
|
|
142
141
|
try {
|
|
143
142
|
const parsed = JSON.parse(resultOutput);
|
|
@@ -258,6 +257,17 @@ async function runToolLoop(
|
|
|
258
257
|
|
|
259
258
|
// Continue looping while the LLM keeps issuing tool calls
|
|
260
259
|
while (toolCalls.length > 0) {
|
|
260
|
+
// OpenAI-compatible APIs require the assistant tool-call message directly
|
|
261
|
+
// before the corresponding tool results. Without this message, the next
|
|
262
|
+
// request is rejected and file operations appear not to work.
|
|
263
|
+
conversation.push({
|
|
264
|
+
id: crypto.randomUUID(),
|
|
265
|
+
role: 'assistant',
|
|
266
|
+
content: finalText || '',
|
|
267
|
+
toolCalls,
|
|
268
|
+
timestamp: new Date(),
|
|
269
|
+
});
|
|
270
|
+
|
|
261
271
|
// Execute all tool calls from this turn
|
|
262
272
|
for (const tc of toolCalls) {
|
|
263
273
|
const execution = await executeToolWithReview(tc.name, tc.arguments, projectRoot, input);
|
|
@@ -266,9 +276,9 @@ async function runToolLoop(
|
|
|
266
276
|
const statusText = toolResult.success ? 'OK' : ('ERR: ' + (toolResult.error ? toolResult.error.slice(0, 80) : 'unknown error'));
|
|
267
277
|
const changeNote = execution.change ? (execution.applied ? ' (applied)' : ' (rejected)') : '';
|
|
268
278
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
279
|
+
conversation.push({
|
|
280
|
+
id: tc.id,
|
|
281
|
+
role: 'tool',
|
|
272
282
|
content: (toolResult.success ? 'Result: ' : 'Error: ') + (toolResult.success ? (toolResult.output ?? '') : toolResult.error) + changeNote,
|
|
273
283
|
timestamp: new Date(),
|
|
274
284
|
});
|
|
@@ -280,22 +290,22 @@ async function runToolLoop(
|
|
|
280
290
|
// Send conversation (including tool results) back to the LLM
|
|
281
291
|
// The LLM will either produce text or more tool calls
|
|
282
292
|
startSpinner('Working');
|
|
283
|
-
let result: { content: string; toolCalls: ToolCall[] }
|
|
293
|
+
let result: { content: string; toolCalls: ToolCall[] };
|
|
284
294
|
try {
|
|
285
295
|
const tools = nimClient.buildToolDefs(TOOL_DEFINITIONS);
|
|
286
296
|
result = await nimClient.complete(conversation, tools);
|
|
287
297
|
} catch {
|
|
288
|
-
// Model doesn't support native tool calling —
|
|
289
|
-
//
|
|
290
|
-
const originalModel = nimClient.getModel();
|
|
298
|
+
// Model doesn't support native tool calling — fall back to plain text
|
|
299
|
+
// and parse any JSON tool calls emitted in the content.
|
|
291
300
|
try {
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
301
|
+
const fallback = await nimClient.complete(conversation, undefined);
|
|
302
|
+
result = {
|
|
303
|
+
content: fallback.content,
|
|
304
|
+
toolCalls: parseToolCallsFromText(fallback.content),
|
|
305
|
+
};
|
|
306
|
+
} catch (err2) {
|
|
297
307
|
stopSpinner();
|
|
298
|
-
printError('LLM error:
|
|
308
|
+
printError('LLM error: ' + (err2 instanceof Error ? err2.message : String(err2)));
|
|
299
309
|
break;
|
|
300
310
|
}
|
|
301
311
|
}
|
|
@@ -306,12 +316,14 @@ async function runToolLoop(
|
|
|
306
316
|
|
|
307
317
|
// If the LLM produced text alongside tool calls, save it
|
|
308
318
|
if (finalText && finalText.trim() && finalText.trim() !== 'null') {
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
319
|
+
if (toolCalls.length === 0) {
|
|
320
|
+
conversation.push({
|
|
321
|
+
id: crypto.randomUUID(),
|
|
322
|
+
role: 'assistant',
|
|
323
|
+
content: finalText.trim(),
|
|
324
|
+
timestamp: new Date(),
|
|
325
|
+
});
|
|
326
|
+
}
|
|
315
327
|
// Narration that comes with more tool calls is shown now; the
|
|
316
328
|
// final answer (no tool calls) is printed by the caller.
|
|
317
329
|
if (toolCalls.length > 0) printAssistantMessage(finalText.trim());
|
|
@@ -507,39 +519,33 @@ export async function runRepl(projectRoot?: string): Promise<void> {
|
|
|
507
519
|
} catch (err) {
|
|
508
520
|
stopSpinner();
|
|
509
521
|
// Tool calling failed (e.g. HTTP 400 because the model does not
|
|
510
|
-
// support the `tools` parameter).
|
|
511
|
-
//
|
|
512
|
-
|
|
513
|
-
let toolResult: { content: string; toolCalls: ToolCall[] } | null = null;
|
|
522
|
+
// support the `tools` parameter). Retry without tools and parse
|
|
523
|
+
// any JSON tool calls the model may have emitted as plain text.
|
|
524
|
+
printInfo('Tool calls not supported by this model — retrying without tools.');
|
|
514
525
|
try {
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
526
|
+
const fallback = await nimClient.complete(conversation, undefined);
|
|
527
|
+
const toolCalls = dedup(
|
|
528
|
+
fallback.toolCalls.length > 0 ? fallback.toolCalls : parseToolCallsFromText(fallback.content),
|
|
529
|
+
);
|
|
530
|
+
if (toolCalls.length > 0) {
|
|
531
|
+
const narration = (fallback.content ?? '').trim().replace(/^null$/, '').trim();
|
|
532
|
+
if (narration && !narration.includes('"tool_calls"')) printAssistantMessage(narration);
|
|
533
|
+
const finalText = await runToolLoop(conversation, projectRoot, toolCalls, input, nimClient);
|
|
534
|
+
if (finalText && finalText.trim() && finalText.trim() !== 'null') {
|
|
535
|
+
printAssistantMessage(finalText.trim());
|
|
536
|
+
}
|
|
537
|
+
} else {
|
|
538
|
+
const cleanText = (fallback.content ?? '').trim().replace(/^null$/, '').trim();
|
|
539
|
+
if (cleanText) {
|
|
540
|
+
conversation.push({ id: crypto.randomUUID(), role: 'assistant', content: cleanText, timestamp: new Date() });
|
|
541
|
+
printAssistantMessage(cleanText);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
} catch (err2) {
|
|
545
|
+
printError('LLM error: ' + (err2 instanceof Error ? err2.message : String(err2)));
|
|
520
546
|
conversation.pop();
|
|
521
547
|
continue mainLoop;
|
|
522
548
|
}
|
|
523
|
-
const fullText = toolResult.content;
|
|
524
|
-
let toolCalls = dedup(toolResult.toolCalls);
|
|
525
|
-
if (fullText && fullText.trim() && fullText.trim() !== 'null') {
|
|
526
|
-
conversation.push({
|
|
527
|
-
id: crypto.randomUUID(),
|
|
528
|
-
role: 'assistant',
|
|
529
|
-
content: fullText.trim(),
|
|
530
|
-
timestamp: new Date(),
|
|
531
|
-
});
|
|
532
|
-
}
|
|
533
|
-
if (toolCalls.length > 0) {
|
|
534
|
-
const narration = fullText.trim().replace(/^null$/, '').trim();
|
|
535
|
-
if (narration) printAssistantMessage(narration);
|
|
536
|
-
const finalText = await runToolLoop(conversation, projectRoot, toolCalls, input, nimClient);
|
|
537
|
-
if (finalText && finalText.trim() && finalText.trim() !== 'null') {
|
|
538
|
-
printAssistantMessage(finalText.trim());
|
|
539
|
-
}
|
|
540
|
-
} else if (fullText && fullText.trim()) {
|
|
541
|
-
printAssistantMessage(fullText.trim());
|
|
542
|
-
}
|
|
543
549
|
}
|
|
544
550
|
} else {
|
|
545
551
|
await replyWithText(conversation, nimClient);
|
package/src/memory/index.ts
CHANGED
|
@@ -72,23 +72,41 @@ export async function loadMemory(projectRoot: string): Promise<string> {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
export async function appendToMemory(projectRoot: string, entry: string): Promise<void> {
|
|
75
|
-
|
|
75
|
+
let path: string;
|
|
76
|
+
try {
|
|
77
|
+
path = ensureProjectDocs(projectRoot).memoryPath;
|
|
78
|
+
} catch {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
76
81
|
const timestamp = new Date().toISOString().split('T')[0];
|
|
77
|
-
|
|
82
|
+
try {
|
|
83
|
+
appendFile(path, '\n\n## ' + timestamp + '\n\n' + entry, 'utf-8');
|
|
84
|
+
} catch {
|
|
85
|
+
// Project memory persistence must not crash the agent.
|
|
86
|
+
}
|
|
78
87
|
}
|
|
79
88
|
|
|
80
89
|
// ── Timeline System ──────────────────────────────────────────────────────────
|
|
81
90
|
|
|
82
91
|
const TIMELINE_TEMPLATE = '# Project Timeline\n\nThis document tracks the complete chronological history of the project.\n\n---\n\n';
|
|
92
|
+
const MEMORY_TEMPLATE = '# Project Memory\n\n## Project Context\n(Add project context here)\n';
|
|
93
|
+
|
|
94
|
+
function ensureProjectDocs(projectRoot: string): { memoryPath: string; timelinePath: string } {
|
|
95
|
+
const docsDir = resolve(projectRoot, 'docs');
|
|
96
|
+
const memoryPath = resolve(docsDir, 'MEMORY.md');
|
|
97
|
+
const timelinePath = resolve(docsDir, 'TIMELINE.md');
|
|
98
|
+
|
|
99
|
+
mkdirSync(docsDir, { recursive: true });
|
|
100
|
+
if (!existsSync(memoryPath)) writeFile(memoryPath, MEMORY_TEMPLATE, 'utf-8');
|
|
101
|
+
if (!existsSync(timelinePath)) writeFile(timelinePath, TIMELINE_TEMPLATE, 'utf-8');
|
|
102
|
+
return { memoryPath, timelinePath };
|
|
103
|
+
}
|
|
83
104
|
|
|
84
105
|
export async function loadTimeline(projectRoot: string): Promise<string> {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
} catch {
|
|
90
|
-
// ignore
|
|
91
|
-
}
|
|
106
|
+
let path: string;
|
|
107
|
+
try {
|
|
108
|
+
path = ensureProjectDocs(projectRoot).timelinePath;
|
|
109
|
+
} catch {
|
|
92
110
|
return '';
|
|
93
111
|
}
|
|
94
112
|
try {
|
|
@@ -105,7 +123,12 @@ export async function appendToTimeline(
|
|
|
105
123
|
actions: string[],
|
|
106
124
|
notes: string[] = [],
|
|
107
125
|
): Promise<void> {
|
|
108
|
-
|
|
126
|
+
let path: string;
|
|
127
|
+
try {
|
|
128
|
+
path = ensureProjectDocs(projectRoot).timelinePath;
|
|
129
|
+
} catch {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
109
132
|
const timestamp = new Date().toISOString().replace('T', ' ').slice(0, 16);
|
|
110
133
|
|
|
111
134
|
const entry =
|
|
@@ -120,11 +143,24 @@ export async function appendToTimeline(
|
|
|
120
143
|
'\n\n### Notes\n' +
|
|
121
144
|
(notes.length > 0 ? notes.map((n) => '- ' + n).join('\n') : '- (none)');
|
|
122
145
|
|
|
123
|
-
|
|
146
|
+
try {
|
|
147
|
+
appendFile(path, entry, 'utf-8');
|
|
148
|
+
} catch {
|
|
149
|
+
// Project logging must never prevent the agent from starting.
|
|
150
|
+
}
|
|
124
151
|
}
|
|
125
152
|
|
|
126
153
|
export async function logToTimeline(projectRoot: string, message: string): Promise<void> {
|
|
127
|
-
|
|
154
|
+
let path: string;
|
|
155
|
+
try {
|
|
156
|
+
path = ensureProjectDocs(projectRoot).timelinePath;
|
|
157
|
+
} catch {
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
128
160
|
const timestamp = new Date().toISOString().replace('T', ' ').slice(0, 16);
|
|
129
|
-
|
|
161
|
+
try {
|
|
162
|
+
appendFile(path, '\n- [' + timestamp + '] ' + message, 'utf-8');
|
|
163
|
+
} catch {
|
|
164
|
+
// Project logging must never prevent the agent from starting.
|
|
165
|
+
}
|
|
130
166
|
}
|
package/src/tools/index.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Agent-Termo Tool Executor — routes tool calls to implementations
|
|
3
3
|
// =============================================================================
|
|
4
4
|
|
|
5
|
-
import { readFile as readFileAsync, writeFile as writeFileAsync } from 'node:fs/promises';
|
|
5
|
+
import { readFile as readFileAsync, writeFile as writeFileAsync, unlink as unlinkAsync } from 'node:fs/promises';
|
|
6
6
|
import { resolve, isAbsolute, relative } from 'node:path';
|
|
7
7
|
import { exec as execAsync } from 'node:child_process';
|
|
8
8
|
import { promisify } from 'node:util';
|
|
@@ -22,6 +22,7 @@ const TOOL_MAP: Record<string, (...args: any[]) => Promise<ToolResult>> = {
|
|
|
22
22
|
'file:read': toolFileRead,
|
|
23
23
|
'file:write': toolFileWrite,
|
|
24
24
|
'file:edit': toolFileEdit,
|
|
25
|
+
'file:delete': toolFileDelete,
|
|
25
26
|
'file:glob': toolFileGlob,
|
|
26
27
|
'grep': toolGrep,
|
|
27
28
|
'bash:execute': toolBash,
|
|
@@ -135,7 +136,7 @@ export async function applyFileChange(change: ProposedFileChange, projectRoot: s
|
|
|
135
136
|
try {
|
|
136
137
|
if (change.isDeletion) {
|
|
137
138
|
if (existsSync(fullPath)) {
|
|
138
|
-
|
|
139
|
+
await unlinkAsync(fullPath);
|
|
139
140
|
}
|
|
140
141
|
} else {
|
|
141
142
|
const dir = resolve(fullPath, '..');
|
|
@@ -227,6 +228,25 @@ async function toolFileEdit(args: Record<string, unknown>, projectRoot: string):
|
|
|
227
228
|
}
|
|
228
229
|
}
|
|
229
230
|
|
|
231
|
+
async function toolFileDelete(args: Record<string, unknown>, projectRoot: string): Promise<ToolResult> {
|
|
232
|
+
const path = String(args.path ?? '');
|
|
233
|
+
if (!path) return { id: '', name: 'file:delete', success: false, error: 'path is required', durationMs: 0 };
|
|
234
|
+
if (!withinProject(path, projectRoot)) {
|
|
235
|
+
return { id: '', name: 'file:delete', success: false, error: 'Access denied: ' + path, durationMs: 0 };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const fullPath = toProjectPath(path, projectRoot);
|
|
239
|
+
try {
|
|
240
|
+
if (!existsSync(fullPath)) {
|
|
241
|
+
return { id: '', name: 'file:delete', success: false, error: 'File not found: ' + path, durationMs: 0 };
|
|
242
|
+
}
|
|
243
|
+
const existingContent = await readFileAsync(fullPath, 'utf-8');
|
|
244
|
+
return proposeFileChange(path, '', projectRoot, 'write', existingContent).result;
|
|
245
|
+
} catch (err) {
|
|
246
|
+
return { id: '', name: 'file:delete', success: false, error: 'Cannot delete ' + path + ': ' + (err instanceof Error ? err.message : String(err)), durationMs: 0 };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
230
250
|
async function toolFileGlob(args: Record<string, unknown>, projectRoot: string): Promise<ToolResult> {
|
|
231
251
|
const globPattern = String(args.pattern ?? '');
|
|
232
252
|
if (!globPattern) return { id: '', name: 'file:glob', success: false, error: 'pattern is required', durationMs: 0 };
|
package/src/types/index.ts
CHANGED
|
@@ -13,6 +13,8 @@ export interface ConversationMessage extends Message {
|
|
|
13
13
|
id: string;
|
|
14
14
|
timestamp: Date;
|
|
15
15
|
agent?: string; // which agent produced this (for display badge)
|
|
16
|
+
/** Native tool calls attached to an assistant message. Required before tool results. */
|
|
17
|
+
toolCalls?: ToolCall[];
|
|
16
18
|
}
|
|
17
19
|
|
|
18
20
|
export interface ToolCall {
|