{"_rev":"3-2fb77661f4e6d6f5bc5f8ea53f708cf8","time":{"created":"2026-07-06T18:02:58.492Z","modified":"2026-07-06T18:02:58.998Z","0.78.1":"2026-06-08T08:15:32.233Z","0.1.0":"2026-07-06T18:02:58.798Z"},"_id":"@aaditri-globaltech/aria-agent","name":"@aaditri-globaltech/aria-agent","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@aaditri-globaltech/aria-agent","version":"0.1.0","description":"General-purpose agent with transport abstraction, state management, and attachment support","type":"module","main":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"},"./node":{"types":"./dist/node.d.ts","import":"./dist/node.js"},"./package.json":"./package.json"},"scripts":{"clean":"shx rm -rf dist","build":"tsgo -p tsconfig.build.json","test":"vitest --run","test:harness":"vitest --run --config vitest.harness.config.ts","coverage:harness":"vitest --run --config vitest.harness.config.ts --coverage","prepublishOnly":"npm run clean && npm run build"},"dependencies":{"@aaditri-globaltech/aria-ai":"^0.1.0","ignore":"7.0.5","typebox":"1.1.38","yaml":"2.9.0"},"keywords":["ai","agent","llm","transport","state-management"],"author":{"name":"Kumar R Anand"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/Aaditri-GlobalTech/aria.git","directory":"packages/agent"},"engines":{"node":">=22.19.0"},"devDependencies":{"@types/node":"24.12.4","@vitest/coverage-v8":"3.2.4","typescript":"5.9.3","vitest":"3.2.4"},"_id":"@aaditri-globaltech/aria-agent@0.1.0","gitHead":"c0ea139e82cc1be93117b4356620a15dbd5371e2","bugs":{"url":"https://github.com/Aaditri-GlobalTech/aria/issues"},"homepage":"https://github.com/Aaditri-GlobalTech/aria#readme","_nodeVersion":"22.23.1","_npmVersion":"10.9.8","dist":{"integrity":"sha512-G/QuGn7fAd3EN/ZygpwTZnFakf5ExqXbVSACB/rrJLthKNOnWBNoBbm9auMdUwZNnDqXIWYWJ6GRNIQwQy8Opg==","shasum":"bad677f2548524a577c9a3365290b08b8199db1b","tarball":"https://registry.npmjs.org/@aaditri-globaltech/aria-agent/-/aria-agent-0.1.0.tgz","fileCount":102,"unpackedSize":1125901,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIFkqqU4HLo8G4vvUS/b9C/X+E6brl2FT7QcYLojCatHiAiAV1o4o2EsJhS0MzuXlOdy4O0/H9vMtB4Ue1CE1gmpBPQ=="}]},"_npmUser":{"name":"kumaranand","email":"aaditriglobaltech@gmail.com"},"directories":{},"maintainers":[{"name":"kumaranand","email":"aaditriglobaltech@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/aria-agent_0.1.0_1783360978619_0.3161618874735179"},"_hasShrinkwrap":false}},"maintainers":[{"name":"kumaranand","email":"aaditriglobaltech@gmail.com"}],"description":"General-purpose agent with transport abstraction, state management, and attachment support","homepage":"https://github.com/Aaditri-GlobalTech/aria#readme","keywords":["ai","agent","llm","transport","state-management"],"repository":{"type":"git","url":"git+https://github.com/Aaditri-GlobalTech/aria.git","directory":"packages/agent"},"author":{"name":"Kumar R Anand"},"bugs":{"url":"https://github.com/Aaditri-GlobalTech/aria/issues"},"license":"MIT","readme":"# @aaditri-globaltech/aria-agent\n\nStateful agent with tool execution and event streaming. Built on `@aaditri-globaltech/aria-ai`.\n\n## Installation\n\n```bash\nnpm install @aaditri-globaltech/aria-agent\n```\n\n## Quick Start\n\n```typescript\nimport { Agent } from \"@aaditri-globaltech/aria-agent\";\nimport { getModel } from \"@aaditri-globaltech/aria-ai\";\n\nconst agent = new Agent({\n  initialState: {\n    systemPrompt: \"You are a helpful assistant.\",\n    model: getModel(\"anthropic\", \"claude-sonnet-4-20250514\"),\n  },\n});\n\nagent.subscribe((event) => {\n  if (event.type === \"message_update\" && event.assistantMessageEvent.type === \"text_delta\") {\n    // Stream just the new text chunk\n    process.stdout.write(event.assistantMessageEvent.delta);\n  }\n});\n\nawait agent.prompt(\"Hello!\");\n```\n\n## Core Concepts\n\n### AgentMessage vs LLM Message\n\nThe agent works with `AgentMessage`, a flexible type that can include:\n- Standard LLM messages (`user`, `assistant`, `toolResult`)\n- Custom app-specific message types via declaration merging\n\nLLMs only understand `user`, `assistant`, and `toolResult`. The `convertToLlm` function bridges this gap by filtering and transforming messages before each LLM call.\n\n### Message Flow\n\n```\nAgentMessage[] → transformContext() → AgentMessage[] → convertToLlm() → Message[] → LLM\n                    (optional)                           (required)\n```\n\n1. **transformContext**: Prune old messages, inject external context\n2. **convertToLlm**: Filter out UI-only messages, convert custom types to LLM format\n\n## Event Flow\n\nThe agent emits events for UI updates. Understanding the event sequence helps build responsive interfaces.\n\n### prompt() Event Sequence\n\nWhen you call `prompt(\"Hello\")`:\n\n```\nprompt(\"Hello\")\n├─ agent_start\n├─ turn_start\n├─ message_start   { message: userMessage }      // Your prompt\n├─ message_end     { message: userMessage }\n├─ message_start   { message: assistantMessage } // LLM starts responding\n├─ message_update  { message: partial... }       // Streaming chunks\n├─ message_update  { message: partial... }\n├─ message_end     { message: assistantMessage } // Complete response\n├─ turn_end        { message, toolResults: [] }\n└─ agent_end       { messages: [...] }\n```\n\n### With Tool Calls\n\nIf the assistant calls tools, the loop continues:\n\n```\nprompt(\"Read config.json\")\n├─ agent_start\n├─ turn_start\n├─ message_start/end  { userMessage }\n├─ message_start      { assistantMessage with toolCall }\n├─ message_update...\n├─ message_end        { assistantMessage }\n├─ tool_execution_start  { toolCallId, toolName, args }\n├─ tool_execution_update { partialResult }           // If tool streams\n├─ tool_execution_end    { toolCallId, result }\n├─ message_start/end  { toolResultMessage }\n├─ turn_end           { message, toolResults: [toolResult] }\n│\n├─ turn_start                                        // Next turn\n├─ message_start      { assistantMessage }           // LLM responds to tool result\n├─ message_update...\n├─ message_end\n├─ turn_end\n└─ agent_end\n```\n\nTool execution mode is configurable:\n\n- `parallel` (default): preflight tool calls sequentially, execute allowed tools concurrently, emit `tool_execution_end` as soon as each tool is finalized, then emit toolResult messages and `turn_end.toolResults` in assistant source order\n- `sequential`: execute tool calls one by one, matching the historical behavior\n\nIn parallel mode, tool completion events follow tool completion order, but persisted toolResult messages still follow assistant source order.\n\nThe mode can be set globally via `toolExecution` in the agent config, or per-tool via `executionMode` on `AgentTool`. If any tool call in a batch targets a tool with `executionMode: \"sequential\"`, the entire batch executes sequentially regardless of the global setting.\n\nThe `beforeToolCall` hook runs after `tool_execution_start` and validated argument parsing. It can block execution. The `afterToolCall` hook runs after tool execution finishes and before `tool_execution_end` and final tool result message events are emitted.\n\nTools can also return `terminate: true` to hint that the automatic follow-up LLM call should be skipped. The loop only stops early when every finalized tool result in that batch sets `terminate: true`. Mixed batches continue normally.\n\nLow-level loop callers can set `shouldStopAfterTurn` to stop gracefully after the current turn completes:\n\n```typescript\nconst stream = agentLoop(prompts, context, {\n  model,\n  convertToLlm,\n  shouldStopAfterTurn: async ({ message, toolResults, context, newMessages }) => {\n    return shouldCompactBeforeNextTurn(context.messages);\n  },\n});\n```\n\n`shouldStopAfterTurn` runs after `turn_end` is emitted and after the assistant response and any tool executions have completed normally. If it returns `true`, the loop emits `agent_end` and exits before polling steering or follow-up queues, and before starting another LLM call. It does not abort the provider stream, does not cancel running tools, and does not alter the assistant message stop reason.\n\nWhen you use the `Agent` class, assistant `message_end` processing is treated as a barrier before tool preflight begins. That means `beforeToolCall` sees agent state that already includes the assistant message that requested the tool call.\n\n### continue() Event Sequence\n\n`continue()` resumes from existing context without adding a new message. Use it for retries after errors.\n\n```typescript\n// After an error, retry from current state\nawait agent.continue();\n```\n\nThe last message in context must be `user` or `toolResult` (not `assistant`).\n\n### Event Types\n\n| Event | Description |\n|-------|-------------|\n| `agent_start` | Agent begins processing |\n| `agent_end` | Final event for the run. Awaited subscribers for this event still count toward settlement |\n| `turn_start` | New turn begins (one LLM call + tool executions) |\n| `turn_end` | Turn completes with assistant message and tool results |\n| `message_start` | Any message begins (user, assistant, toolResult) |\n| `message_update` | **Assistant only.** Includes `assistantMessageEvent` with delta |\n| `message_end` | Message completes |\n| `tool_execution_start` | Tool begins |\n| `tool_execution_update` | Tool streams progress |\n| `tool_execution_end` | Tool completes |\n\n`Agent.subscribe()` listeners are awaited in registration order. `agent_end` means no more loop events will be emitted, but `await agent.waitForIdle()` and `await agent.prompt(...)` only settle after awaited `agent_end` listeners finish.\n\n## Agent Options\n\n```typescript\nconst agent = new Agent({\n  // Initial state\n  initialState: {\n    systemPrompt: string,\n    model: Model<any>,\n    thinkingLevel: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\",\n    tools: AgentTool<any>[],\n    messages: AgentMessage[],\n  },\n\n  // Convert AgentMessage[] to LLM Message[] (required for custom message types)\n  convertToLlm: (messages) => messages.filter(...),\n\n  // Transform context before convertToLlm (for pruning, compaction)\n  transformContext: async (messages, signal) => pruneOldMessages(messages),\n\n  // Steering mode: \"one-at-a-time\" (default) or \"all\"\n  steeringMode: \"one-at-a-time\",\n\n  // Follow-up mode: \"one-at-a-time\" (default) or \"all\"\n  followUpMode: \"one-at-a-time\",\n\n  // Custom stream function (for proxy backends)\n  streamFn: streamProxy,\n\n  // Session ID for provider caching\n  sessionId: \"session-123\",\n\n  // Dynamic API key resolution (for expiring OAuth tokens)\n  getApiKey: async (provider) => refreshToken(),\n\n  // Tool execution mode: \"parallel\" (default) or \"sequential\"\n  toolExecution: \"parallel\",\n\n  // Preflight each tool call after args are validated. Can block execution.\n  beforeToolCall: async ({ toolCall, args, context }) => {\n    if (toolCall.name === \"bash\") {\n      return { block: true, reason: \"bash is disabled\" };\n    }\n  },\n\n  // Postprocess each tool result before final tool events are emitted.\n  afterToolCall: async ({ toolCall, result, isError, context }) => {\n    if (toolCall.name === \"notify_done\" && !isError) {\n      return { terminate: true };\n    }\n    if (!isError) {\n      return { details: { ...result.details, audited: true } };\n    }\n  },\n\n  // Custom thinking budgets for token-based providers\n  thinkingBudgets: {\n    minimal: 128,\n    low: 512,\n    medium: 1024,\n    high: 2048,\n  },\n});\n```\n\n## Agent State\n\n```typescript\ninterface AgentState {\n  systemPrompt: string;\n  model: Model<any>;\n  thinkingLevel: ThinkingLevel;\n  tools: AgentTool<any>[];\n  messages: AgentMessage[];\n  readonly isStreaming: boolean;\n  readonly streamingMessage?: AgentMessage;\n  readonly pendingToolCalls: ReadonlySet<string>;\n  readonly errorMessage?: string;\n}\n```\n\nAccess state via `agent.state`.\n\nAssigning `agent.state.tools = [...]` or `agent.state.messages = [...]` copies the top-level array before storing it. Mutating the returned array mutates the current agent state.\n\nDuring streaming, `agent.state.streamingMessage` contains the current partial assistant message.\n\n`agent.state.isStreaming` remains `true` until the run fully settles, including awaited `agent_end` subscribers.\n\n## Methods\n\n### Prompting\n\n```typescript\n// Text prompt\nawait agent.prompt(\"Hello\");\n\n// With images\nawait agent.prompt(\"What's in this image?\", [\n  { type: \"image\", data: base64Data, mimeType: \"image/jpeg\" }\n]);\n\n// AgentMessage directly\nawait agent.prompt({ role: \"user\", content: \"Hello\", timestamp: Date.now() });\n\n// Continue from current context (last message must be user or toolResult)\nawait agent.continue();\n```\n\n### State Management\n\n```typescript\nagent.state.systemPrompt = \"New prompt\";\nagent.state.model = getModel(\"openai\", \"gpt-4o\");\nagent.state.thinkingLevel = \"medium\";\nagent.state.tools = [myTool];\nagent.toolExecution = \"sequential\";\nagent.beforeToolCall = async ({ toolCall }) => undefined;\nagent.afterToolCall = async ({ toolCall, result }) => undefined;\nagent.state.messages = newMessages; // top-level array is copied\nagent.state.messages.push(message);\nagent.reset();\n```\n\n### Session and Thinking Budgets\n\n```typescript\nagent.sessionId = \"session-123\";\n\nagent.thinkingBudgets = {\n  minimal: 128,\n  low: 512,\n  medium: 1024,\n  high: 2048,\n};\n```\n\n### Control\n\n```typescript\nagent.abort();           // Cancel current operation\nawait agent.waitForIdle(); // Wait for completion\n```\n\n### Events\n\n```typescript\nconst unsubscribe = agent.subscribe(async (event, signal) => {\n  if (event.type === \"agent_end\") {\n    // Final barrier work for the run\n    await flushSessionState(signal);\n  }\n});\nunsubscribe();\n```\n\n## Steering and Follow-up\n\nSteering messages let you interrupt the agent while tools are running. Follow-up messages let you queue work after the agent would otherwise stop.\n\n```typescript\nagent.steeringMode = \"one-at-a-time\";\nagent.followUpMode = \"one-at-a-time\";\n\n// While agent is running tools\nagent.steer({\n  role: \"user\",\n  content: \"Stop! Do this instead.\",\n  timestamp: Date.now(),\n});\n\n// After the agent finishes its current work\nagent.followUp({\n  role: \"user\",\n  content: \"Also summarize the result.\",\n  timestamp: Date.now(),\n});\n\nconst steeringMode = agent.steeringMode;\nconst followUpMode = agent.followUpMode;\n\nagent.clearSteeringQueue();\nagent.clearFollowUpQueue();\nagent.clearAllQueues();\n```\n\nUse clearSteeringQueue, clearFollowUpQueue, or clearAllQueues to drop queued messages.\n\nWhen steering messages are detected after a turn completes:\n1. All tool calls from the current assistant message have already finished\n2. Steering messages are injected\n3. The LLM responds on the next turn\n\nFollow-up messages are checked only when there are no more tool calls and no steering messages. If any are queued, they are injected and another turn runs.\n\n## Custom Message Types\n\nExtend `AgentMessage` via declaration merging:\n\n```typescript\ndeclare module \"@aaditri-globaltech/aria-agent\" {\n  interface CustomAgentMessages {\n    notification: { role: \"notification\"; text: string; timestamp: number };\n  }\n}\n\n// Now valid\nconst msg: AgentMessage = { role: \"notification\", text: \"Info\", timestamp: Date.now() };\n```\n\nHandle custom types in `convertToLlm`:\n\n```typescript\nconst agent = new Agent({\n  convertToLlm: (messages) => messages.flatMap(m => {\n    if (m.role === \"notification\") return []; // Filter out\n    return [m];\n  }),\n});\n```\n\n## Tools\n\nDefine tools using `AgentTool`:\n\n```typescript\nimport { Type } from \"typebox\";\n\nconst readFileTool: AgentTool = {\n  name: \"read_file\",\n  label: \"Read File\",  // For UI display\n  description: \"Read a file's contents\",\n  parameters: Type.Object({\n    path: Type.String({ description: \"File path\" }),\n  }),\n  // Override execution mode for this tool (optional).\n  // \"sequential\" forces the entire batch to run one at a time.\n  // \"parallel\" allows concurrent execution with other tool calls.\n  // If omitted, the global toolExecution config applies.\n  executionMode: \"sequential\",\n  execute: async (toolCallId, params, signal, onUpdate) => {\n    const content = await fs.readFile(params.path, \"utf-8\");\n\n    // Optional: stream progress\n    onUpdate?.({ content: [{ type: \"text\", text: \"Reading...\" }], details: {} });\n\n    // Optional: add `terminate: true` here to skip the automatic follow-up LLM call\n    // when every finalized tool result in the batch does the same.\n    return {\n      content: [{ type: \"text\", text: content }],\n      details: { path: params.path, size: content.length },\n    };\n  },\n};\n\nagent.state.tools = [readFileTool];\n```\n\n### Error Handling\n\n**Throw an error** when a tool fails. Do not return error messages as content.\n\n```typescript\nexecute: async (toolCallId, params, signal, onUpdate) => {\n  if (!fs.existsSync(params.path)) {\n    throw new Error(`File not found: ${params.path}`);\n  }\n  // Return content only on success\n  return { content: [{ type: \"text\", text: \"...\" }] };\n}\n```\n\nThrown errors are caught by the agent and reported to the LLM as tool errors with `isError: true`.\n\nReturn `terminate: true` from `execute()` or `afterToolCall` to hint that the agent should stop after the current tool batch. This only takes effect when every finalized tool result in the batch is terminating. The hint is runtime-only; emitted `toolResult` transcript messages remain standard LLM tool results.\n\n## Proxy Usage\n\nFor browser apps that proxy through a backend:\n\n```typescript\nimport { Agent, streamProxy } from \"@aaditri-globaltech/aria-agent\";\n\nconst agent = new Agent({\n  streamFn: (model, context, options) =>\n    streamProxy(model, context, {\n      ...options,\n      authToken: \"...\",\n      proxyUrl: \"https://your-server.com\",\n    }),\n});\n```\n\n## Low-Level API\n\nFor direct control without the Agent class:\n\n```typescript\nimport { agentLoop, agentLoopContinue } from \"@aaditri-globaltech/aria-agent\";\n\nconst context: AgentContext = {\n  systemPrompt: \"You are helpful.\",\n  messages: [],\n  tools: [],\n};\n\nconst config: AgentLoopConfig = {\n  model: getModel(\"openai\", \"gpt-4o\"),\n  convertToLlm: (msgs) => msgs.filter(m => [\"user\", \"assistant\", \"toolResult\"].includes(m.role)),\n  toolExecution: \"parallel\",  // overridden by per-tool executionMode if set\n  beforeToolCall: async ({ toolCall, args, context }) => undefined,\n  afterToolCall: async ({ toolCall, result, isError, context }) => undefined,\n};\n\nconst userMessage = { role: \"user\", content: \"Hello\", timestamp: Date.now() };\n\nfor await (const event of agentLoop([userMessage], context, config)) {\n  console.log(event.type);\n}\n\n// Continue from existing context\nfor await (const event of agentLoopContinue(context, config)) {\n  console.log(event.type);\n}\n```\n\nThese low-level streams are observational. They preserve event order, but they do not wait for your async event handling to settle before later producer phases continue. If you need message processing to act as a barrier before tool preflight, use the `Agent` class instead of raw `agentLoop()` or `agentLoopContinue()`.\n\n## License\n\nMIT\n","readmeFilename":"README.md"}