agent-termo 1.0.2 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-termo",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Terminal-based AI coding agent that replicates Claude Code experience",
5
5
  "type": "module",
6
6
  "main": "dist/main.js",
@@ -49,6 +49,7 @@
49
49
  "chalk": "^5.3.0",
50
50
  "commander": "^12.1.0",
51
51
  "fs-extra": "^11.2.0",
52
+ "glob": "^7.2.3",
52
53
  "marked": "^12.0.0",
53
54
  "openai": "^4.50.0",
54
55
  "simple-git": "^3.24.0",
@@ -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.2')
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
- name: t.name,
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
- async *streamComplete(
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
- messages: messages.map((m) => {
83
- if (m.role === 'tool') {
84
- return {
85
- role: 'tool' as const,
86
- content: m.content,
87
- tool_call_id: m.id,
88
- };
89
- }
90
- return {
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
- return { id: tc.id, name: tc.name, arguments: args };
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
- messages: messages.map((m) => {
162
- if (m.role === 'tool') {
163
- return { role: 'tool' as const, content: m.content, tool_call_id: m.id };
164
- }
165
- return { role: m.role as 'system' | 'user' | 'assistant', content: m.content };
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
- return { id: tc.id, name: tc.function.name, arguments: args };
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
- name: tc.function?.name ?? tc.name ?? '',
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
- required: ['path', 'old_string', 'new_string'],
72
- },
73
- },
74
- {
75
- name: 'file:glob',
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';
@@ -127,7 +127,7 @@ function parseToolCallsFromText(text: string): ToolCall[] {
127
127
  const rawCalls = Array.isArray(obj.tool_calls) ? obj.tool_calls : [];
128
128
  return rawCalls.map((tc: { id?: string; name?: string; function?: { name?: string; arguments?: unknown } }) => ({
129
129
  id: tc.id ?? crypto.randomUUID(),
130
- name: tc.name ?? (tc.function?.name ?? ''),
130
+ name: fromWireToolName(tc.name ?? (tc.function?.name ?? '')),
131
131
  arguments:
132
132
  typeof tc.function?.arguments === 'string'
133
133
  ? (() => { try { return JSON.parse(tc.function.arguments as string); } catch { return { _raw: tc.function.arguments }; } })()
@@ -136,7 +136,7 @@ function parseToolCallsFromText(text: string): ToolCall[] {
136
136
  }
137
137
 
138
138
  function extractProposedChange(toolName: string, resultOutput: string): ProposedFileChange | undefined {
139
- const isFileTool = toolName === 'file:write' || toolName === 'file:edit';
139
+ const isFileTool = toolName === 'file:write' || toolName === 'file:edit' || toolName === 'file:delete';
140
140
  if (!isFileTool) return undefined;
141
141
  try {
142
142
  const parsed = JSON.parse(resultOutput);
@@ -257,6 +257,17 @@ async function runToolLoop(
257
257
 
258
258
  // Continue looping while the LLM keeps issuing tool calls
259
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
+
260
271
  // Execute all tool calls from this turn
261
272
  for (const tc of toolCalls) {
262
273
  const execution = await executeToolWithReview(tc.name, tc.arguments, projectRoot, input);
@@ -265,9 +276,9 @@ async function runToolLoop(
265
276
  const statusText = toolResult.success ? 'OK' : ('ERR: ' + (toolResult.error ? toolResult.error.slice(0, 80) : 'unknown error'));
266
277
  const changeNote = execution.change ? (execution.applied ? ' (applied)' : ' (rejected)') : '';
267
278
 
268
- conversation.push({
269
- id: crypto.randomUUID(),
270
- role: 'tool',
279
+ conversation.push({
280
+ id: tc.id,
281
+ role: 'tool',
271
282
  content: (toolResult.success ? 'Result: ' : 'Error: ') + (toolResult.success ? (toolResult.output ?? '') : toolResult.error) + changeNote,
272
283
  timestamp: new Date(),
273
284
  });
@@ -305,12 +316,14 @@ async function runToolLoop(
305
316
 
306
317
  // If the LLM produced text alongside tool calls, save it
307
318
  if (finalText && finalText.trim() && finalText.trim() !== 'null') {
308
- conversation.push({
309
- id: crypto.randomUUID(),
310
- role: 'assistant',
311
- content: finalText.trim(),
312
- timestamp: new Date(),
313
- });
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
+ }
314
327
  // Narration that comes with more tool calls is shown now; the
315
328
  // final answer (no tool calls) is printed by the caller.
316
329
  if (toolCalls.length > 0) printAssistantMessage(finalText.trim());
@@ -511,27 +524,23 @@ export async function runRepl(projectRoot?: string): Promise<void> {
511
524
  printInfo('Tool calls not supported by this model — retrying without tools.');
512
525
  try {
513
526
  const fallback = await nimClient.complete(conversation, undefined);
514
- const text = (fallback.content ?? '').trim();
515
- // Strip any leading/trailing "null" reasoning noise
516
- const cleanText = text.replace(/^null$/, '').trim();
517
- if (cleanText) {
518
- conversation.push({
519
- id: crypto.randomUUID(),
520
- role: 'assistant',
521
- content: cleanText,
522
- timestamp: new Date(),
523
- });
524
- }
525
- const narration = cleanText.replace(/^null$/, '').trim();
526
- if (narration) printAssistantMessage(narration);
527
-
528
- const toolCalls = dedup(parseToolCallsFromText(fallback.content));
527
+ const toolCalls = dedup(
528
+ fallback.toolCalls.length > 0 ? fallback.toolCalls : parseToolCallsFromText(fallback.content),
529
+ );
529
530
  if (toolCalls.length > 0) {
531
+ const narration = (fallback.content ?? '').trim().replace(/^null$/, '').trim();
532
+ if (narration && !narration.includes('"tool_calls"')) printAssistantMessage(narration);
530
533
  const finalText = await runToolLoop(conversation, projectRoot, toolCalls, input, nimClient);
531
534
  if (finalText && finalText.trim() && finalText.trim() !== 'null') {
532
535
  printAssistantMessage(finalText.trim());
533
536
  }
534
- }
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
+ }
535
544
  } catch (err2) {
536
545
  printError('LLM error: ' + (err2 instanceof Error ? err2.message : String(err2)));
537
546
  conversation.pop();
@@ -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
- const path = resolve(projectRoot, 'docs', 'MEMORY.md');
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
- appendFile(path, '\n\n## ' + timestamp + '\n\n' + entry, 'utf-8');
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
- const path = resolve(projectRoot, 'docs', 'TIMELINE.md');
86
- if (!existsSync(path)) {
87
- try {
88
- writeFile(path, TIMELINE_TEMPLATE, 'utf-8');
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
- const path = resolve(projectRoot, 'docs', 'TIMELINE.md');
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
- appendFile(path, entry, 'utf-8');
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
- const path = resolve(projectRoot, 'docs', 'TIMELINE.md');
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
- appendFile(path, '\n- [' + timestamp + '] ' + message, 'utf-8');
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
  }
@@ -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
- await writeFileAsync(fullPath, '');
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 };
@@ -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 {