@arki-moe/agent-ts 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 arki.moe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+ # agent.ts
2
+
3
+ Minimal Agent library, zero dependencies
4
+
5
+ ## Usage Example
6
+
7
+ ```ts
8
+ import { Agent, Role, type Tool } from "agent-ts";
9
+
10
+ const getTimeTool: Tool = {
11
+ name: "get_time",
12
+ description: "Get the current time in ISO format",
13
+ parameters: { type: "object", properties: {} },
14
+ execute: () => new Date().toISOString(),
15
+ };
16
+
17
+ const agent = new Agent("openai", {
18
+ apiKey: "sk-...",
19
+ model: "gpt-5-nano",
20
+ system: "You are a helpful assistant. Reply concisely.", // optional: system role
21
+ });
22
+ agent.registerTool(getTimeTool);
23
+
24
+ // run: Executes tool chain automatically, returns new messages, context is maintained automatically
25
+ const msgs = await agent.run({ role: Role.User, content: "What time is it?" });
26
+ console.log(msgs);
27
+
28
+ // step: Single-step inference, returns new messages from the model
29
+ const msgs2 = await agent.step({ role: Role.User, content: "Hello" });
30
+ console.log(msgs2);
31
+
32
+ // context is a public property that can be read directly
33
+ console.log(agent.context);
34
+ ```
35
+
36
+ ## API
37
+
38
+ - `Agent(adapterName, config)` - Create Agent, config contains `apiKey`, `model`, `system` (optional), etc.
39
+ - `agent.context` - Public property, complete conversation history
40
+ - `agent.registerTool(tool)` - Register tool
41
+ - `agent.step(message)` - Call model once, returns new `Message[]`
42
+ - `agent.run(message)` - Execute tool chain automatically, returns all new `Message[]`
@@ -0,0 +1,2 @@
1
+ import { type Message, type Tool } from "../types";
2
+ export declare function openaiAdapter(config: Record<string, unknown>, context: Message[], tools: Tool[]): Promise<Message[]>;
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.openaiAdapter = openaiAdapter;
4
+ const types_1 = require("../types");
5
+ const ROLE_TO_OPENAI = {
6
+ [types_1.Role.System]: "system",
7
+ [types_1.Role.User]: "user",
8
+ [types_1.Role.Ai]: "assistant",
9
+ };
10
+ function toOpenAIMessages(context) {
11
+ return context.reduce((out, m) => {
12
+ if (m.role === types_1.Role.System || m.role === types_1.Role.User || m.role === types_1.Role.Ai)
13
+ return [...out, { role: ROLE_TO_OPENAI[m.role], content: m.content }];
14
+ if (m.role === types_1.Role.ToolResult)
15
+ return [...out, { role: "tool", content: m.content, tool_call_id: m.callId }];
16
+ if (m.role === types_1.Role.ToolCall) {
17
+ const tc = { id: m.callId, type: "function", function: { name: m.toolName, arguments: m.argsText ?? "{}" } };
18
+ const last = out[out.length - 1];
19
+ if (last?.tool_calls) {
20
+ last.tool_calls.push(tc);
21
+ return out;
22
+ }
23
+ return [...out, { role: "assistant", tool_calls: [tc] }];
24
+ }
25
+ return out;
26
+ }, []);
27
+ }
28
+ async function openaiAdapter(config, context, tools) {
29
+ const baseUrl = config.baseUrl ?? "https://api.openai.com";
30
+ const apiKey = config.apiKey ?? "";
31
+ const model = config.model ?? "gpt-5-nano";
32
+ if (!apiKey)
33
+ throw new Error("OpenAI adapter requires apiKey in config");
34
+ const contextMessages = toOpenAIMessages(context);
35
+ const systemContent = config.system;
36
+ const messages = systemContent
37
+ ? [{ role: "system", content: systemContent }, ...contextMessages]
38
+ : contextMessages;
39
+ const body = {
40
+ model,
41
+ messages,
42
+ tools: tools.length ? tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.parameters ?? {} } })) : undefined,
43
+ tool_choice: tools.length ? "auto" : undefined,
44
+ };
45
+ const res = await fetch(`${baseUrl.replace(/\/$/, "")}/v1/chat/completions`, {
46
+ method: "POST",
47
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
48
+ body: JSON.stringify(body),
49
+ });
50
+ const text = await res.text();
51
+ if (!res.ok) {
52
+ let errMsg = `OpenAI API HTTP ${res.status}`;
53
+ try {
54
+ const parsed = JSON.parse(text);
55
+ if (parsed?.error?.message)
56
+ errMsg = parsed.error.message;
57
+ }
58
+ catch {
59
+ if (text)
60
+ errMsg += `: ${text.slice(0, 200)}`;
61
+ }
62
+ throw new Error(errMsg);
63
+ }
64
+ let data;
65
+ try {
66
+ data = JSON.parse(text);
67
+ }
68
+ catch {
69
+ throw new Error(`OpenAI API returned invalid JSON: ${text.slice(0, 200)}`);
70
+ }
71
+ if (data.error)
72
+ throw new Error(`OpenAI API error: ${data.error.message}`);
73
+ const msg = data.choices?.[0]?.message;
74
+ if (!msg)
75
+ throw new Error("OpenAI API returned empty response");
76
+ if (msg.tool_calls?.length) {
77
+ return msg.tool_calls.map((tc) => ({
78
+ role: types_1.Role.ToolCall,
79
+ toolName: tc.function.name,
80
+ callId: tc.id,
81
+ argsText: tc.function.arguments ?? "{}",
82
+ }));
83
+ }
84
+ return [{ role: types_1.Role.Ai, content: msg.content ?? "" }];
85
+ }
@@ -0,0 +1,14 @@
1
+ import type { Context, Message, Tool } from "./types";
2
+ export { openaiAdapter } from "./adapter/openai";
3
+ export type { Adapter, Context, Message, Tool } from "./types";
4
+ export { Role } from "./types";
5
+ export declare class Agent {
6
+ context: Context;
7
+ private adapter;
8
+ private config;
9
+ private tools;
10
+ constructor(adapterName: string, config: Record<string, unknown>);
11
+ registerTool(tool: Tool): void;
12
+ step(message: Message): Promise<Message[]>;
13
+ run(message: Message): Promise<Message[]>;
14
+ }
package/dist/index.js ADDED
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Agent = exports.Role = exports.openaiAdapter = void 0;
4
+ const openai_1 = require("./adapter/openai");
5
+ const types_1 = require("./types");
6
+ var openai_2 = require("./adapter/openai");
7
+ Object.defineProperty(exports, "openaiAdapter", { enumerable: true, get: function () { return openai_2.openaiAdapter; } });
8
+ var types_2 = require("./types");
9
+ Object.defineProperty(exports, "Role", { enumerable: true, get: function () { return types_2.Role; } });
10
+ const adapters = {
11
+ openai: openai_1.openaiAdapter,
12
+ };
13
+ class Agent {
14
+ constructor(adapterName, config) {
15
+ this.context = [];
16
+ this.tools = [];
17
+ this.adapter = adapters[adapterName] ?? (() => { throw new Error(`Adapter "${adapterName}" not found`); })();
18
+ this.config = config;
19
+ }
20
+ registerTool(tool) {
21
+ this.tools.push(tool);
22
+ }
23
+ async step(message) {
24
+ this.context.push(message);
25
+ const msgs = await this.adapter(this.config, this.context, this.tools);
26
+ this.context.push(...msgs);
27
+ return msgs;
28
+ }
29
+ async run(message) {
30
+ this.context.push(message);
31
+ const all = [];
32
+ for (;;) {
33
+ const msgs = await this.adapter(this.config, this.context, this.tools);
34
+ this.context.push(...msgs);
35
+ all.push(...msgs);
36
+ const last = msgs[msgs.length - 1];
37
+ if (last.role === types_1.Role.Ai)
38
+ return all;
39
+ for (const m of msgs) {
40
+ if (m.role !== types_1.Role.ToolCall)
41
+ continue;
42
+ const tool = this.tools.find((t) => t.name === m.toolName);
43
+ if (!tool)
44
+ throw new Error(`Tool "${m.toolName}" is not registered`);
45
+ let content;
46
+ let isError = false;
47
+ try {
48
+ const args = JSON.parse(m.argsText || "{}");
49
+ const out = await Promise.resolve(tool.execute(args));
50
+ content = typeof out === "string" ? out : JSON.stringify(out);
51
+ }
52
+ catch (err) {
53
+ isError = true;
54
+ content = err instanceof Error ? err.message : String(err);
55
+ }
56
+ const result = { role: types_1.Role.ToolResult, callId: m.callId, content, isError };
57
+ this.context.push(result);
58
+ all.push(result);
59
+ }
60
+ }
61
+ }
62
+ }
63
+ exports.Agent = Agent;
@@ -0,0 +1,35 @@
1
+ export declare enum Role {
2
+ System = "system",
3
+ User = "user",
4
+ Ai = "ai",
5
+ ToolCall = "tool_call",
6
+ ToolResult = "tool_result"
7
+ }
8
+ export type Message = {
9
+ role: Role.System;
10
+ content: string;
11
+ } | {
12
+ role: Role.User;
13
+ content: string;
14
+ } | {
15
+ role: Role.Ai;
16
+ content: string;
17
+ } | {
18
+ role: Role.ToolCall;
19
+ toolName: string;
20
+ callId: string;
21
+ argsText: string;
22
+ } | {
23
+ role: Role.ToolResult;
24
+ callId: string;
25
+ content: string;
26
+ isError?: boolean;
27
+ };
28
+ export type Context = Message[];
29
+ export type Tool = {
30
+ name: string;
31
+ description: string;
32
+ parameters: unknown;
33
+ execute: (args: unknown) => Promise<unknown> | unknown;
34
+ };
35
+ export type Adapter = (config: Record<string, unknown>, context: Message[], tools: Tool[]) => Promise<Message[]>;
package/dist/types.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Role = void 0;
4
+ var Role;
5
+ (function (Role) {
6
+ Role["System"] = "system";
7
+ Role["User"] = "user";
8
+ Role["Ai"] = "ai";
9
+ Role["ToolCall"] = "tool_call";
10
+ Role["ToolResult"] = "tool_result";
11
+ })(Role || (exports.Role = Role = {}));
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@arki-moe/agent-ts",
3
+ "version": "1.0.0",
4
+ "description": "Minimal Agent library, zero dependencies",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js",
11
+ "require": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsc",
20
+ "check": "tsc --noEmit -p tsconfig.check.json",
21
+ "test": "vitest run",
22
+ "prepublishOnly": "pnpm run build"
23
+ },
24
+ "keywords": [
25
+ "agent",
26
+ "llm",
27
+ "openai",
28
+ "ai",
29
+ "chat"
30
+ ],
31
+ "author": "haruamamiya",
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/arki-moe/agent-ts.git"
36
+ },
37
+ "packageManager": "pnpm@10.23.0",
38
+ "devDependencies": {
39
+ "@types/node": "^25.3.0",
40
+ "typescript": "^5.9.3",
41
+ "vitest": "^4.0.18"
42
+ }
43
+ }