@vietor/agent-core 0.7.2 → 0.7.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/README.md CHANGED
@@ -425,7 +425,7 @@ interface Tool {
425
425
  readOnly?: boolean;
426
426
  description: string;
427
427
  parameters: Record<string, unknown>; // JSON Schema object
428
- summaryKeys?: string[]; // parameter keys used for display summary
428
+ argSummaryKeys?: string[]; // parameter keys used for display summary
429
429
  summarizeArgs?: (args: Record<string, unknown>) => string; // custom summary function
430
430
  summarizeResult?(result: TextResult): string; // result summary for timeline display
431
431
  execute(args: Record<string, unknown>, ctx: ToolContext): Promise<TextResult>;
@@ -436,7 +436,7 @@ interface Tool {
436
436
  - `parameters` is passed to the LLM as a JSON Schema to describe the tool's arguments.
437
437
  - When the LLM calls a tool, `execute` receives the parsed arguments and a context object.
438
438
  - `execute` returns a `TextResult` (`{ content, isError? }`). Expected failures return `toolError(...)` (exported from the package); unexpected errors may throw and are wrapped by the registry.
439
- - `summaryKeys` / `summarizeArgs` control what appears in the tool log entry's `argsSummary` field.
439
+ - `argSummaryKeys` / `summarizeArgs` control what appears in the tool log entry's `argsSummary` field.
440
440
  - `summarizeResult` (optional) returns a short result summary for timeline display. Called after execution with the result; the registry prefixes the wall-clock duration. Falls back to a default summary (byte/line count) when not defined.
441
441
 
442
442
  ### `ToolContext`
@@ -2,7 +2,7 @@ import { createLLM } from "./llm/client.js";
2
2
  import { Session } from "./runtime/session.js";
3
3
  import { ToolRegistry } from "./tools/registry.js";
4
4
  import { MCPServerManager } from "./mcp/manager.js";
5
- import { TOOL_USE_PROMPT } from "./runtime/prompts.js";
5
+ import { renderToolUsePrompt } from "./runtime/prompts.js";
6
6
  import { DEFAULT_MAX_TURNS } from "./util/constants.js";
7
7
  import { TODO_WRITE_GUIDANCE } from "./tools/todo-write.js";
8
8
  import { ASK_USER_GUIDANCE } from "./tools/ask-user.js";
@@ -13,7 +13,7 @@ function contextLimitFor(maxInputTokens) {
13
13
  }
14
14
  function buildSystemPrompt(base, skills, builtInTools, maxTurns) {
15
15
  const parts = [base];
16
- const toolUseLines = [TOOL_USE_PROMPT, `- Turn budget: ${maxTurns} tool-calling turns per run.`];
16
+ const toolUseLines = [renderToolUsePrompt(maxTurns)];
17
17
  if (typeof builtInTools === "object") {
18
18
  if (builtInTools.todoWrite)
19
19
  toolUseLines.push(TODO_WRITE_GUIDANCE);
@@ -125,12 +125,12 @@ export class MCPServerManager {
125
125
  this.markFailed(name, entry.type, error ?? "MCP server connection closed");
126
126
  }
127
127
  adapt(server, client, tool) {
128
- const summaryKeys = summaryCandidates(tool.inputSchema);
128
+ const argSummaryKeys = summaryCandidates(tool.inputSchema);
129
129
  return {
130
130
  name: mcpToolName(server, tool.name),
131
131
  description: tool.description ?? `${server} ${tool.name}`,
132
132
  parameters: tool.inputSchema,
133
- ...(summaryKeys.length ? { summaryKeys } : {}),
133
+ ...(argSummaryKeys.length ? { argSummaryKeys } : {}),
134
134
  async execute(args, ctx) {
135
135
  const result = await withTimeoutFn((signal) => client.callTool(tool.name, args, signal), CALL_TIMEOUT_MS, ctx.signal, `MCP tool call timed out (${CALL_TIMEOUT_MS / 1000}s)`);
136
136
  const text = extractContent(result);
@@ -1,5 +1,6 @@
1
1
  import type { Todo } from "../tools/types.js";
2
2
  export declare const TOOL_USE_PROMPT: string;
3
+ export declare function renderToolUsePrompt(maxTurns: number): string;
3
4
  export declare const COMPACT_PROMPT: string;
4
5
  export declare function renderTodoReminder(todos: readonly Todo[]): string;
5
6
  export declare function renderIncompleteTodoNudge(todos: readonly Todo[]): string;
@@ -8,6 +8,9 @@ export const TOOL_USE_PROMPT = [
8
8
  "- For file operations (read/write/edit/glob/grep) and fetching URLs, use the dedicated tool. Fall back to Shell only when no dedicated tool covers the task and Shell is available. A runtime error does not make Shell the fallback; do not retry that same operation through Shell.",
9
9
  "- If a tool call fails, read the error, adjust the arguments or approach, and continue; do not repeat the identical call and do not abandon the task over a single failure.",
10
10
  ].join("\n");
11
+ export function renderToolUsePrompt(maxTurns) {
12
+ return [TOOL_USE_PROMPT, `- Turn budget: ${maxTurns} tool-calling turns per run.`].join("\n");
13
+ }
11
14
  export const COMPACT_PROMPT = [
12
15
  "Summarize the conversation above for context continuation. Preserve:\n",
13
16
  "1. Primary goal, sub-goals, constraints, acceptance criteria.\n",
@@ -34,7 +37,7 @@ export function renderTodoReminder(todos) {
34
37
  const focusLine = focus ? ` Current focus: ${focus.content}` : "";
35
38
  const incomplete = todos.filter(t => t.status !== "completed");
36
39
  const warning = incomplete.length > 0
37
- ? ` ${incomplete.length} incomplete. You MUST complete EVERY task before your final text-only response update status via TodoWrite after each task finishes.`
40
+ ? ` ${incomplete.length} incomplete. You MUST complete EVERY task before your final text-only response. Mark them complete via TodoWrite as they finish; the final update may go in the same turn as your last tool call.`
38
41
  : "";
39
42
  return `<system-reminder>Tasks: ${items.join(" | ")}${focusLine}${warning}</system-reminder>`;
40
43
  }
@@ -30,6 +30,7 @@ export declare class SessionMessages {
30
30
  add(msg: SessionMessage): void;
31
31
  toLLM(): LLMMessage[];
32
32
  export(): SessionMessage[];
33
+ lastAssistantText(): string;
33
34
  import(messages: SessionMessage[]): void;
34
35
  normalizeInterruptedToolCalls(): void;
35
36
  clear(): void;
@@ -86,6 +86,9 @@ export class SessionMessages {
86
86
  export() {
87
87
  return this.messages.slice();
88
88
  }
89
+ lastAssistantText() {
90
+ return lastAssistantText(this.messages);
91
+ }
89
92
  import(messages) {
90
93
  this.resetMessages(messages.slice(), messages.reduce((sum, m) => sum + estimateTokens(messageText(m)), 0));
91
94
  this.normalizeInterruptedToolCalls();
@@ -1,10 +1,10 @@
1
- import { SessionMessages, lastAssistantText } from "./session-messages.js";
1
+ import { SessionMessages } from "./session-messages.js";
2
2
  import { Agent } from "./agent.js";
3
- import { TOOL_USE_PROMPT } from "./prompts.js";
3
+ import { renderToolUsePrompt } from "./prompts.js";
4
4
  import { ToolRegistry } from "../tools/registry.js";
5
5
  export function createSubAgentRunner(opts) {
6
6
  return async (systemPrompt, task, signal) => {
7
- const conversation = new SessionMessages([systemPrompt, TOOL_USE_PROMPT, `- Turn budget: ${opts.maxTurns} tool-calling turns per run.`].join("\n\n"));
7
+ const conversation = new SessionMessages([systemPrompt, renderToolUsePrompt(opts.maxTurns)].join("\n\n"));
8
8
  const subTools = new ToolRegistry();
9
9
  subTools.registerAll(opts.tools.filter((t) => t.readOnly === true));
10
10
  const subAgent = new Agent({
@@ -19,8 +19,8 @@ export function createSubAgentRunner(opts) {
19
19
  contextLimit: opts.contextLimit,
20
20
  });
21
21
  const status = await subAgent.run(task, undefined, signal);
22
- const messages = conversation.export();
23
- const reply = lastAssistantText(messages) || `(sub-agent produced no final text; status ${status})`;
22
+ const reply = conversation.lastAssistantText() || `(sub-agent produced no final text; status ${status})`;
23
+ const messages = status !== "ok" ? conversation.export() : [];
24
24
  return { status, reply, messages };
25
25
  };
26
26
  }
@@ -21,6 +21,6 @@ export function createAskUserTool(ask) {
21
21
  }
22
22
  return { content: await ask(question, options) };
23
23
  },
24
- summaryKeys: ["question"],
24
+ argSummaryKeys: ["question"],
25
25
  };
26
26
  }
@@ -39,5 +39,5 @@ export const fileEditTool = {
39
39
  return "Edit failed";
40
40
  return "Edit completed";
41
41
  },
42
- summaryKeys: ["path"],
42
+ argSummaryKeys: ["path"],
43
43
  };
@@ -89,5 +89,5 @@ export const fileReadTool = {
89
89
  summarizeResult(result) {
90
90
  return summaryBytes("Read", result, "Read failed");
91
91
  },
92
- summaryKeys: ["path"],
92
+ argSummaryKeys: ["path"],
93
93
  };
@@ -21,5 +21,5 @@ export const fileWriteTool = {
21
21
  return "Write failed";
22
22
  return "Write completed";
23
23
  },
24
- summaryKeys: ["path"],
24
+ argSummaryKeys: ["path"],
25
25
  };
@@ -27,5 +27,5 @@ export const globTool = {
27
27
  summarizeResult(result) {
28
28
  return ripgrepResultSummary("file", result, "Glob failed", "Found 0 files");
29
29
  },
30
- summaryKeys: ["pattern", "path"],
30
+ argSummaryKeys: ["pattern", "path"],
31
31
  };
@@ -63,5 +63,5 @@ export const grepTool = {
63
63
  summarizeResult(result) {
64
64
  return ripgrepResultSummary("match", result, "Grep failed", "Found 0 matches");
65
65
  },
66
- summaryKeys: ["pattern", "path", "glob"],
66
+ argSummaryKeys: ["pattern", "path", "glob"],
67
67
  };
@@ -76,10 +76,10 @@ export class ToolRegistry {
76
76
  return "";
77
77
  if (tool.summarizeArgs)
78
78
  return tool.summarizeArgs(args);
79
- if (!tool.summaryKeys)
79
+ if (!tool.argSummaryKeys)
80
80
  return "";
81
81
  const parts = [];
82
- for (const k of tool.summaryKeys) {
82
+ for (const k of tool.argSummaryKeys) {
83
83
  const v = args[k];
84
84
  if (typeof v === "string" && v) {
85
85
  parts.push(v);
@@ -53,5 +53,5 @@ export const shellTool = {
53
53
  summarizeResult(result) {
54
54
  return summaryBytes("Command executed", result, "Command failed");
55
55
  },
56
- summaryKeys: ["command"],
56
+ argSummaryKeys: ["command"],
57
57
  };
@@ -12,7 +12,7 @@ export function createSkillTool(resolve) {
12
12
  },
13
13
  required: ["name"],
14
14
  },
15
- summaryKeys: ["name"],
15
+ argSummaryKeys: ["name"],
16
16
  async execute(args, _ctx) {
17
17
  const name = (args.name || "").trim();
18
18
  if (!name) {
@@ -55,7 +55,7 @@ export function createSubAgentTool(deps) {
55
55
  },
56
56
  required: ["type", "task"],
57
57
  },
58
- summaryKeys: ["type"],
58
+ argSummaryKeys: ["type"],
59
59
  async execute(args, ctx) {
60
60
  const type = args.type;
61
61
  const task = (args.task ?? "").trim();
@@ -69,11 +69,16 @@ export function createSubAgentTool(deps) {
69
69
  const { status, reply, messages } = await deps.runSubAgent(def.systemPrompt, task, ctx.signal);
70
70
  if (status === "ok")
71
71
  return { content: reply };
72
- const stallReason = status === "stalled"
73
- ? [...messages].reverse()
74
- .map((m) => m.content)
75
- .find((c) => typeof c === "string" && c.startsWith(NOT_EXECUTED_PREFIX))
76
- : undefined;
72
+ let stallReason;
73
+ if (status === "stalled") {
74
+ for (let i = messages.length - 1; i >= 0; i--) {
75
+ const content = messages[i].content;
76
+ if (typeof content === "string" && content.startsWith(NOT_EXECUTED_PREFIX)) {
77
+ stallReason = content;
78
+ break;
79
+ }
80
+ }
81
+ }
77
82
  const suffix = stallReason ? ` ${stallReason}` : "";
78
83
  return { content: `Sub-agent "${type}" ended with status ${status}.${suffix}\n\n${reply}`, isError: true };
79
84
  },
@@ -1,3 +1,3 @@
1
1
  import type { Tool, Todo } from "./types.js";
2
- export declare const TODO_WRITE_GUIDANCE = "- For multi-step tasks (3+ steps), you MUST use TodoWrite: create the task list first, then update each task's status as you execute. Never execute a multi-step task without a TodoWrite task list.";
2
+ export declare const TODO_WRITE_GUIDANCE = "- For multi-step tasks (5+ steps), you MUST use TodoWrite: create the task list first, then update statuses as tasks complete. Never execute a 5+ step task without a TodoWrite task list.";
3
3
  export declare function createTodoWriteTool(setTodos: (todos: Todo[]) => void): Tool;
@@ -1,7 +1,7 @@
1
1
  import { toolError } from "./types.js";
2
- export const TODO_WRITE_GUIDANCE = "- For multi-step tasks (3+ steps), you MUST use TodoWrite: create the task list first, then update each task's status as you execute. Never execute a multi-step task without a TodoWrite task list.";
2
+ export const TODO_WRITE_GUIDANCE = "- For multi-step tasks (5+ steps), you MUST use TodoWrite: create the task list first, then update statuses as tasks complete. Never execute a 5+ step task without a TodoWrite task list.";
3
3
  const STATUSES = ["pending", "inProgress", "completed"];
4
- const DESCRIPTION = "Manage the task list for tasks with 3+ steps. Pass the FULL list each call; it replaces the previous list. Keep one inProgress at a time. status: pending, inProgress, completed.";
4
+ const DESCRIPTION = "Manage the task list for tasks with 5+ steps. Pass the FULL list each call; it replaces the previous list. Keep one inProgress at a time. status: pending, inProgress, completed.";
5
5
  function parseTodos(args) {
6
6
  const raw = args.todos;
7
7
  if (!Array.isArray(raw)) {
@@ -32,6 +32,13 @@ function parseTodos(args) {
32
32
  }
33
33
  todos.push({ content, status });
34
34
  }
35
+ if (!seenInProgress) {
36
+ const firstPending = todos.find((t) => t.status === "pending");
37
+ if (firstPending) {
38
+ firstPending.status = "inProgress";
39
+ normalized++;
40
+ }
41
+ }
35
42
  return { todos, done, normalized };
36
43
  }
37
44
  export function createTodoWriteTool(setTodos) {
@@ -25,7 +25,7 @@ export interface Tool {
25
25
  readOnly?: boolean;
26
26
  description: string;
27
27
  parameters: Record<string, unknown>;
28
- summaryKeys?: string[];
28
+ argSummaryKeys?: string[];
29
29
  summarizeArgs?: (args: Record<string, unknown>) => string;
30
30
  summarizeResult?(result: TextResult): string;
31
31
  execute(args: Record<string, unknown>, ctx: ToolContext): Promise<TextResult>;
@@ -100,5 +100,5 @@ export const webFetchTool = {
100
100
  summarizeResult(result) {
101
101
  return summaryBytes("Fetched", result, "Fetch failed");
102
102
  },
103
- summaryKeys: ["url"],
103
+ argSummaryKeys: ["url"],
104
104
  };
package/dist/util/net.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ProxyAgent } from "undici";
1
+ import { fetch, ProxyAgent } from "undici";
2
2
  let proxyAgent;
3
3
  let noProxyList;
4
4
  let proxyInitialized = false;
@@ -11,11 +11,12 @@ function ensureProxy() {
11
11
  proxyAgent = proxyUrl ? new ProxyAgent(proxyUrl) : null;
12
12
  noProxyList = noProxy?.split(",").map((s) => s.trim()).filter(Boolean);
13
13
  }
14
+ const undiciFetch = fetch;
14
15
  export async function netFetch(input, init) {
15
16
  if (!proxyInitialized)
16
17
  ensureProxy();
17
18
  if (!proxyAgent)
18
- return fetch(input, init);
19
+ return undiciFetch(input, init);
19
20
  const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
20
21
  if (noProxyList) {
21
22
  const hostname = new URL(url).hostname;
@@ -25,7 +26,7 @@ export async function netFetch(input, init) {
25
26
  return hostname === p || hostname.endsWith("." + p);
26
27
  });
27
28
  if (shouldBypass)
28
- return fetch(input, init);
29
+ return undiciFetch(input, init);
29
30
  }
30
- return fetch(input, { ...init, dispatcher: proxyAgent });
31
+ return undiciFetch(input, { ...init, dispatcher: proxyAgent });
31
32
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vietor/agent-core",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",