@iqai/adk-cli 0.2.9 → 0.3.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.
Files changed (156) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/app.module.d.ts +3 -0
  3. package/dist/app.module.d.ts.map +1 -0
  4. package/dist/app.module.js +24 -0
  5. package/dist/app.module.js.map +1 -0
  6. package/dist/cli/cli.module.d.ts +3 -0
  7. package/dist/cli/cli.module.d.ts.map +1 -0
  8. package/dist/cli/cli.module.js +25 -0
  9. package/dist/cli/cli.module.js.map +1 -0
  10. package/dist/cli/new.command.d.ts +10 -0
  11. package/dist/cli/new.command.d.ts.map +1 -0
  12. package/dist/cli/new.command.js +273 -0
  13. package/dist/cli/new.command.js.map +1 -0
  14. package/dist/cli/run.command.d.ts +20 -0
  15. package/dist/cli/run.command.d.ts.map +1 -0
  16. package/dist/cli/run.command.js +342 -0
  17. package/dist/cli/run.command.js.map +1 -0
  18. package/dist/cli/serve.command.d.ts +20 -0
  19. package/dist/cli/serve.command.d.ts.map +1 -0
  20. package/dist/cli/serve.command.js +137 -0
  21. package/dist/cli/serve.command.js.map +1 -0
  22. package/dist/cli/web.command.d.ts +20 -0
  23. package/dist/cli/web.command.d.ts.map +1 -0
  24. package/dist/cli/web.command.js +146 -0
  25. package/dist/cli/web.command.js.map +1 -0
  26. package/dist/common/tokens.d.ts +5 -0
  27. package/dist/common/tokens.d.ts.map +1 -0
  28. package/dist/common/tokens.js +8 -0
  29. package/dist/common/tokens.js.map +1 -0
  30. package/dist/common/types.d.ts +91 -0
  31. package/dist/common/types.d.ts.map +1 -0
  32. package/dist/common/types.js +3 -0
  33. package/dist/common/types.js.map +1 -0
  34. package/dist/http/bootstrap.d.ts +17 -0
  35. package/dist/http/bootstrap.d.ts.map +1 -0
  36. package/dist/http/bootstrap.js +221 -0
  37. package/dist/http/bootstrap.js.map +1 -0
  38. package/dist/http/config/config.module.d.ts +6 -0
  39. package/dist/http/config/config.module.d.ts.map +1 -0
  40. package/dist/http/config/config.module.js +32 -0
  41. package/dist/http/config/config.module.js.map +1 -0
  42. package/dist/http/discovery/agents.controller.d.ts +13 -0
  43. package/dist/http/discovery/agents.controller.d.ts.map +1 -0
  44. package/dist/http/discovery/agents.controller.js +73 -0
  45. package/dist/http/discovery/agents.controller.js.map +1 -0
  46. package/dist/http/discovery/discovery.module.d.ts +3 -0
  47. package/dist/http/discovery/discovery.module.d.ts.map +1 -0
  48. package/dist/http/discovery/discovery.module.js +22 -0
  49. package/dist/http/discovery/discovery.module.js.map +1 -0
  50. package/dist/http/dto/api.dto.d.ts +70 -0
  51. package/dist/http/dto/api.dto.d.ts.map +1 -0
  52. package/dist/http/dto/api.dto.js +268 -0
  53. package/dist/http/dto/api.dto.js.map +1 -0
  54. package/dist/http/events/events.controller.d.ts +8 -0
  55. package/dist/http/events/events.controller.d.ts.map +1 -0
  56. package/dist/http/events/events.controller.js +55 -0
  57. package/dist/http/events/events.controller.js.map +1 -0
  58. package/dist/http/events/events.module.d.ts +3 -0
  59. package/dist/http/events/events.module.d.ts.map +1 -0
  60. package/dist/http/events/events.module.js +25 -0
  61. package/dist/http/events/events.module.js.map +1 -0
  62. package/dist/http/events/events.service.d.ts +8 -0
  63. package/dist/http/events/events.service.d.ts.map +1 -0
  64. package/dist/http/events/events.service.js +37 -0
  65. package/dist/http/events/events.service.js.map +1 -0
  66. package/dist/http/health/health.controller.d.ts +6 -0
  67. package/dist/http/health/health.controller.d.ts.map +1 -0
  68. package/dist/http/health/health.controller.js +37 -0
  69. package/dist/http/health/health.controller.js.map +1 -0
  70. package/dist/http/health/health.module.d.ts +3 -0
  71. package/dist/http/health/health.module.d.ts.map +1 -0
  72. package/dist/http/health/health.module.js +20 -0
  73. package/dist/http/health/health.module.js.map +1 -0
  74. package/dist/http/http.module.d.ts +6 -0
  75. package/dist/http/http.module.d.ts.map +1 -0
  76. package/dist/http/http.module.js +43 -0
  77. package/dist/http/http.module.js.map +1 -0
  78. package/dist/http/messaging/messaging.controller.d.ts +9 -0
  79. package/dist/http/messaging/messaging.controller.d.ts.map +1 -0
  80. package/dist/http/messaging/messaging.controller.js +83 -0
  81. package/dist/http/messaging/messaging.controller.js.map +1 -0
  82. package/dist/http/messaging/messaging.module.d.ts +3 -0
  83. package/dist/http/messaging/messaging.module.d.ts.map +1 -0
  84. package/dist/http/messaging/messaging.module.js +25 -0
  85. package/dist/http/messaging/messaging.module.js.map +1 -0
  86. package/dist/http/messaging/messaging.service.d.ts +11 -0
  87. package/dist/http/messaging/messaging.service.d.ts.map +1 -0
  88. package/dist/http/messaging/messaging.service.js +48 -0
  89. package/dist/http/messaging/messaging.service.js.map +1 -0
  90. package/dist/http/providers/agent-loader.service.d.ts +49 -0
  91. package/dist/http/providers/agent-loader.service.d.ts.map +1 -0
  92. package/dist/http/providers/agent-loader.service.js +416 -0
  93. package/dist/http/providers/agent-loader.service.js.map +1 -0
  94. package/dist/http/providers/agent-manager.service.d.ts +24 -0
  95. package/dist/http/providers/agent-manager.service.d.ts.map +1 -0
  96. package/dist/http/providers/agent-manager.service.js +222 -0
  97. package/dist/http/providers/agent-manager.service.js.map +1 -0
  98. package/dist/http/providers/agent-scanner.service.d.ts +9 -0
  99. package/dist/http/providers/agent-scanner.service.d.ts.map +1 -0
  100. package/dist/http/providers/agent-scanner.service.js +108 -0
  101. package/dist/http/providers/agent-scanner.service.js.map +1 -0
  102. package/dist/http/providers/providers.module.d.ts +3 -0
  103. package/dist/http/providers/providers.module.d.ts.map +1 -0
  104. package/dist/http/providers/providers.module.js +47 -0
  105. package/dist/http/providers/providers.module.js.map +1 -0
  106. package/dist/http/reload/hot-reload.service.d.ts +16 -0
  107. package/dist/http/reload/hot-reload.service.d.ts.map +1 -0
  108. package/dist/http/reload/hot-reload.service.js +79 -0
  109. package/dist/http/reload/hot-reload.service.js.map +1 -0
  110. package/dist/http/reload/reload.controller.d.ts +14 -0
  111. package/dist/http/reload/reload.controller.d.ts.map +1 -0
  112. package/dist/http/reload/reload.controller.js +50 -0
  113. package/dist/http/reload/reload.controller.js.map +1 -0
  114. package/dist/http/reload/reload.module.d.ts +3 -0
  115. package/dist/http/reload/reload.module.d.ts.map +1 -0
  116. package/dist/http/reload/reload.module.js +23 -0
  117. package/dist/http/reload/reload.module.js.map +1 -0
  118. package/dist/http/runtime-config.d.ts +22 -0
  119. package/dist/http/runtime-config.d.ts.map +1 -0
  120. package/dist/http/runtime-config.js +5 -0
  121. package/dist/http/runtime-config.js.map +1 -0
  122. package/dist/http/sessions/sessions.controller.d.ts +11 -0
  123. package/dist/http/sessions/sessions.controller.d.ts.map +1 -0
  124. package/dist/http/sessions/sessions.controller.js +116 -0
  125. package/dist/http/sessions/sessions.controller.js.map +1 -0
  126. package/dist/http/sessions/sessions.module.d.ts +3 -0
  127. package/dist/http/sessions/sessions.module.d.ts.map +1 -0
  128. package/dist/http/sessions/sessions.module.js +25 -0
  129. package/dist/http/sessions/sessions.module.js.map +1 -0
  130. package/dist/http/sessions/sessions.service.d.ts +54 -0
  131. package/dist/http/sessions/sessions.service.d.ts.map +1 -0
  132. package/dist/http/sessions/sessions.service.js +353 -0
  133. package/dist/http/sessions/sessions.service.js.map +1 -0
  134. package/dist/http/state/state.controller.d.ts +9 -0
  135. package/dist/http/state/state.controller.d.ts.map +1 -0
  136. package/dist/http/state/state.controller.js +76 -0
  137. package/dist/http/state/state.controller.js.map +1 -0
  138. package/dist/http/state/state.module.d.ts +3 -0
  139. package/dist/http/state/state.module.d.ts.map +1 -0
  140. package/dist/http/state/state.module.js +25 -0
  141. package/dist/http/state/state.module.js.map +1 -0
  142. package/dist/http/state/state.service.d.ts +9 -0
  143. package/dist/http/state/state.service.d.ts.map +1 -0
  144. package/dist/http/state/state.service.js +55 -0
  145. package/dist/http/state/state.service.js.map +1 -0
  146. package/dist/main.d.ts +3 -0
  147. package/dist/main.d.ts.map +1 -0
  148. package/dist/main.js +25 -0
  149. package/dist/main.js.map +1 -0
  150. package/package.json +18 -12
  151. package/dist/index.d.mts +0 -2
  152. package/dist/index.d.ts +0 -2
  153. package/dist/index.js +0 -1239
  154. package/dist/index.js.map +0 -1
  155. package/dist/index.mjs +0 -1223
  156. package/dist/index.mjs.map +0 -1
package/dist/index.mjs DELETED
@@ -1,1223 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
-
4
- // src/index.ts
5
- import chalk6 from "chalk";
6
- import { program } from "commander";
7
-
8
- // package.json
9
- var package_default = {
10
- name: "@iqai/adk-cli",
11
- version: "0.2.9",
12
- description: "CLI tool for creating, running, and testing ADK agents",
13
- main: "dist/index.js",
14
- types: "dist/index.d.ts",
15
- bin: {
16
- adk: "./dist/index.mjs"
17
- },
18
- scripts: {
19
- build: "tsup",
20
- dev: "tsup --watch",
21
- test: "vitest run",
22
- "test:watch": "vitest"
23
- },
24
- repository: {
25
- type: "git",
26
- url: "https://github.com/IQAIcom/adk-ts.git",
27
- directory: "packages/adk-cli"
28
- },
29
- keywords: [
30
- "ai",
31
- "llm",
32
- "agent",
33
- "cli",
34
- "adk",
35
- "typescript"
36
- ],
37
- author: "IQAI",
38
- license: "MIT",
39
- dependencies: {
40
- "@clack/prompts": "^0.11.0",
41
- "@hono/node-server": "^1.18.1",
42
- "@iqai/adk": "workspace:*",
43
- chalk: "^5.4.1",
44
- commander: "^12.1.0",
45
- dedent: "^1.6.0",
46
- giget: "^2.0.0",
47
- hono: "^4.6.13",
48
- marked: "^14.1.3",
49
- "marked-terminal": "^7.2.1",
50
- esbuild: "^0.23.0"
51
- },
52
- devDependencies: {
53
- "@iqai/tsconfig": "workspace:*",
54
- "@types/marked-terminal": "^6.1.1",
55
- "@types/node": "^20.17.30",
56
- tsup: "^8.4.0",
57
- typescript: "^5.3.2",
58
- vitest: "^3.1.3"
59
- },
60
- packageManager: "pnpm@9.0.0",
61
- engines: {
62
- node: ">=22.0"
63
- },
64
- files: [
65
- "dist",
66
- "!**/*.test.*",
67
- "!**/*.json",
68
- "CHANGELOG.md",
69
- "LICENSE",
70
- "README.md"
71
- ],
72
- publishConfig: {
73
- access: "public"
74
- }
75
- };
76
-
77
- // src/commands/new.ts
78
- import { existsSync } from "fs";
79
- import { join } from "path";
80
- import { confirm, intro, outro, select, spinner, text } from "@clack/prompts";
81
- import chalk from "chalk";
82
- import dedent from "dedent";
83
- import { downloadTemplate } from "giget";
84
- var templates = [
85
- {
86
- value: "simple-agent",
87
- label: "\u{1F916} Simple Agent",
88
- hint: "Basic agent with chat capabilities",
89
- source: "github:IQAIcom/adk-ts/apps/starter-templates/simple-agent"
90
- },
91
- {
92
- value: "discord-bot",
93
- label: "\u{1F3AE} Discord Bot",
94
- hint: "Agent integrated with Discord",
95
- source: "github:IQAIcom/adk-ts/apps/starter-templates/discord-bot"
96
- },
97
- {
98
- value: "telegram-bot",
99
- label: "\u{1F4F1} Telegram Bot",
100
- hint: "Agent integrated with Telegram",
101
- source: "github:IQAIcom/adk-ts/apps/starter-templates/telegram-bot"
102
- },
103
- {
104
- value: "hono-server",
105
- label: "\u{1F680} Hono Server",
106
- hint: "Web server with agent endpoints",
107
- source: "github:IQAIcom/adk-ts/apps/starter-templates/hono-server"
108
- },
109
- {
110
- value: "shade-agent",
111
- label: "\u{1F313} Near Shade Agent",
112
- hint: "Starter that uses Near Shade Agent",
113
- source: "github:IQAIcom/adk-ts/apps/starter-templates/shade-agent"
114
- },
115
- {
116
- value: "mcp-starter",
117
- label: "\u{1F50C} MCP Integration",
118
- hint: "Model Context Protocol server",
119
- source: "github:IQAIcom/adk-ts/apps/starter-templates/mcp-starter"
120
- }
121
- ];
122
- var packageManagers = [
123
- { name: "npm", command: "npm", args: ["install"], label: "\u{1F4E6} npm" },
124
- { name: "pnpm", command: "pnpm", args: ["install"], label: "\u26A1 pnpm" },
125
- { name: "yarn", command: "yarn", args: ["install"], label: "\u{1F9F6} yarn" },
126
- { name: "bun", command: "bun", args: ["install"], label: "\u{1F35E} bun" }
127
- ];
128
- async function detectAvailablePackageManagers() {
129
- const { spawn } = await import("child_process");
130
- const available = [];
131
- for (const pm of packageManagers) {
132
- try {
133
- await new Promise((resolve2, reject) => {
134
- const child = spawn(pm.command, ["--version"], {
135
- stdio: "pipe"
136
- });
137
- child.on("close", (code) => {
138
- if (code === 0) {
139
- available.push(pm);
140
- }
141
- resolve2();
142
- });
143
- child.on("error", () => resolve2());
144
- });
145
- } catch {
146
- }
147
- }
148
- return available.length > 0 ? available : [packageManagers[0]];
149
- }
150
- async function createProject(projectName, options) {
151
- console.clear();
152
- intro(chalk.magentaBright("\u{1F9E0} Create new ADK-TS project"));
153
- let finalProjectName = projectName;
154
- if (!finalProjectName) {
155
- const response = await text({
156
- message: "What is your project name?",
157
- placeholder: "my-adk-project",
158
- validate: (value) => {
159
- if (!value) return "Project name is required";
160
- if (value.includes(" ")) return "Project name cannot contain spaces";
161
- if (existsSync(value)) return `Directory "${value}" already exists`;
162
- return void 0;
163
- }
164
- });
165
- if (typeof response === "symbol") {
166
- outro("Operation cancelled");
167
- process.exit(0);
168
- }
169
- finalProjectName = response;
170
- }
171
- let selectedTemplate = options?.template;
172
- if (!selectedTemplate || !templates.find((t) => t.value === selectedTemplate)) {
173
- const framework = await select({
174
- message: "Which template would you like to use?",
175
- options: templates.map((t) => ({
176
- value: t.value,
177
- label: t.label,
178
- hint: t.hint
179
- }))
180
- });
181
- if (typeof framework === "symbol") {
182
- outro("Operation cancelled");
183
- process.exit(0);
184
- }
185
- selectedTemplate = framework;
186
- }
187
- const template = templates.find((t) => t.value === selectedTemplate);
188
- if (!template) {
189
- outro("Invalid template selected");
190
- process.exit(1);
191
- }
192
- if (existsSync(finalProjectName)) {
193
- outro(chalk.red(`Directory "${finalProjectName}" already exists`));
194
- process.exit(1);
195
- }
196
- const s = spinner();
197
- s.start("Downloading template...");
198
- try {
199
- await downloadTemplate(template.source, {
200
- dir: finalProjectName,
201
- registry: "gh"
202
- });
203
- s.stop("Template downloaded!");
204
- } catch (error) {
205
- s.stop("Failed to download template");
206
- outro(chalk.red(`Error: ${error}`));
207
- process.exit(1);
208
- }
209
- const availablePackageManagers = await detectAvailablePackageManagers();
210
- let selectedPackageManager;
211
- if (availablePackageManagers.length === 1) {
212
- selectedPackageManager = availablePackageManagers[0];
213
- } else {
214
- const packageManagerChoice = await select({
215
- message: "Which package manager would you like to use?",
216
- options: availablePackageManagers.map((pm) => ({
217
- value: pm.name,
218
- label: pm.label
219
- }))
220
- });
221
- if (typeof packageManagerChoice === "symbol") {
222
- outro("Operation cancelled");
223
- process.exit(0);
224
- }
225
- selectedPackageManager = availablePackageManagers.find(
226
- (pm) => pm.name === packageManagerChoice
227
- );
228
- }
229
- const shouldInstall = await confirm({
230
- message: "Install dependencies?",
231
- initialValue: true
232
- });
233
- if (typeof shouldInstall === "symbol") {
234
- outro("Operation cancelled");
235
- process.exit(0);
236
- }
237
- if (shouldInstall) {
238
- const s2 = spinner();
239
- s2.start(`Installing dependencies with ${selectedPackageManager.name}...`);
240
- const { spawn } = await import("child_process");
241
- const projectPath = join(process.cwd(), finalProjectName);
242
- try {
243
- await new Promise((resolve2, reject) => {
244
- const child = spawn(
245
- selectedPackageManager.command,
246
- selectedPackageManager.args,
247
- {
248
- cwd: projectPath,
249
- stdio: "pipe"
250
- }
251
- );
252
- child.on("close", (code) => {
253
- if (code === 0) {
254
- resolve2();
255
- } else {
256
- reject(new Error(`Package installation failed with code ${code}`));
257
- }
258
- });
259
- child.on("error", reject);
260
- });
261
- s2.stop("Dependencies installed!");
262
- } catch (error) {
263
- s2.stop("Failed to install dependencies");
264
- console.log(
265
- chalk.yellow("\nYou can install dependencies manually by running:")
266
- );
267
- console.log(
268
- chalk.cyan(
269
- `cd ${finalProjectName} && ${selectedPackageManager.command} ${selectedPackageManager.args.join(" ")}`
270
- )
271
- );
272
- }
273
- }
274
- outro(
275
- chalk.green(dedent`
276
- 🎉 Project created successfully!
277
-
278
- Next steps:
279
- ${chalk.cyan(`cd ${finalProjectName}`)}
280
- ${shouldInstall ? "" : chalk.cyan(`${selectedPackageManager.command} ${selectedPackageManager.args.join(" ")}`)}
281
- ${chalk.cyan("npm run dev")} or ${chalk.cyan("yarn dev")} or ${chalk.cyan("pnpm dev")}
282
-
283
- Happy coding! 🚀
284
- `)
285
- );
286
- }
287
-
288
- // src/commands/run.ts
289
- import * as p from "@clack/prompts";
290
- import { log, spinner as spinner2 } from "@clack/prompts";
291
- import chalk4 from "chalk";
292
- import { marked } from "marked";
293
- import { markedTerminal } from "marked-terminal";
294
-
295
- // src/commands/serve.ts
296
- import { existsSync as existsSync3 } from "fs";
297
- import { resolve } from "path";
298
- import chalk3 from "chalk";
299
-
300
- // src/server/index.ts
301
- import { serve } from "@hono/node-server";
302
- import { InMemorySessionService } from "@iqai/adk";
303
- import { Hono } from "hono";
304
-
305
- // src/server/logger.ts
306
- import chalk2 from "chalk";
307
- var Logger = class {
308
- name;
309
- quiet;
310
- debugEnabled;
311
- constructor({ name, quiet = false }) {
312
- this.name = name;
313
- this.quiet = quiet;
314
- this.debugEnabled = process.env.NODE_ENV === "development" || process.env.ADK_DEBUG === "true";
315
- }
316
- time() {
317
- return (/* @__PURE__ */ new Date()).toLocaleTimeString();
318
- }
319
- prefix(icon, message) {
320
- return `${this.time()} ${icon} [${this.name}] ${message}`;
321
- }
322
- debug(message, ...args) {
323
- if (!this.debugEnabled || this.quiet) return;
324
- console.debug(chalk2.blue(this.prefix("\u{1F41B}", message)), ...args);
325
- }
326
- info(message, ...args) {
327
- if (this.quiet) return;
328
- console.info(chalk2.cyan(this.prefix("\u2139\uFE0F", message)), ...args);
329
- }
330
- warn(message, ...args) {
331
- if (this.quiet) return;
332
- console.warn(chalk2.yellow(this.prefix("\u{1F6A7}", message)), ...args);
333
- }
334
- error(message, ...args) {
335
- if (this.quiet) return;
336
- console.error(chalk2.red(this.prefix("\u274C", message)), ...args);
337
- }
338
- };
339
-
340
- // src/server/routes.ts
341
- import { cors } from "hono/cors";
342
- function setupRoutes(app, agentManager, sessionManager, agentsDir) {
343
- app.use("/*", cors());
344
- app.get("/health", (c) => c.json({ status: "ok" }));
345
- app.get("/api/agents", (c) => {
346
- const agentsList = Array.from(
347
- agentManager.getAgents().values()
348
- ).map((agent) => ({
349
- path: agent.absolutePath,
350
- name: agent.name,
351
- directory: agent.absolutePath,
352
- relativePath: agent.relativePath
353
- }));
354
- return c.json({ agents: agentsList });
355
- });
356
- app.post("/api/agents/refresh", (c) => {
357
- agentManager.scanAgents(agentsDir);
358
- const agentsList = Array.from(
359
- agentManager.getAgents().values()
360
- ).map((agent) => ({
361
- path: agent.absolutePath,
362
- name: agent.name,
363
- directory: agent.absolutePath,
364
- relativePath: agent.relativePath
365
- }));
366
- return c.json({ agents: agentsList });
367
- });
368
- app.get("/api/agents/:id/messages", async (c) => {
369
- const agentPath = decodeURIComponent(c.req.param("id"));
370
- const loadedAgent = agentManager.getLoadedAgents().get(agentPath);
371
- if (!loadedAgent) {
372
- return c.json({ messages: [] });
373
- }
374
- const messages = await sessionManager.getSessionMessages(loadedAgent);
375
- const response = { messages };
376
- return c.json(response);
377
- });
378
- app.post("/api/agents/:id/message", async (c) => {
379
- const agentPath = decodeURIComponent(c.req.param("id"));
380
- const { message, attachments } = await c.req.json();
381
- const response = await agentManager.sendMessageToAgent(
382
- agentPath,
383
- message,
384
- attachments
385
- );
386
- const messageResponse = { response };
387
- return c.json(messageResponse);
388
- });
389
- }
390
-
391
- // src/server/services.ts
392
- import {
393
- existsSync as existsSync2,
394
- mkdirSync,
395
- readFileSync,
396
- readdirSync,
397
- statSync,
398
- unlinkSync
399
- } from "fs";
400
- import { dirname, join as join2, relative } from "path";
401
- import { pathToFileURL } from "url";
402
- import { AgentBuilder } from "@iqai/adk";
403
- var AgentScanner = class {
404
- constructor(quiet = false) {
405
- this.quiet = quiet;
406
- this.logger = new Logger({ name: "session-manager", quiet: this.quiet });
407
- }
408
- logger;
409
- async getSessionMessages(loadedAgent) {
410
- }
411
- scanAgents(agentsDir, loadedAgents) {
412
- const agents = /* @__PURE__ */ new Map();
413
- const scanDir = !agentsDir || !existsSync2(agentsDir) ? process.cwd() : agentsDir;
414
- const shouldSkipDirectory = (dirName) => {
415
- const skipDirs = [
416
- "node_modules",
417
- ".git",
418
- ".next",
419
- "dist",
420
- "build",
421
- ".turbo",
422
- "coverage",
423
- ".vscode",
424
- ".idea"
425
- ];
426
- return skipDirs.includes(dirName);
427
- };
428
- const scanDirectory = (dir) => {
429
- const items = readdirSync(dir);
430
- for (const item of items) {
431
- const fullPath = join2(dir, item);
432
- const stat = statSync(fullPath);
433
- if (stat.isDirectory()) {
434
- if (!shouldSkipDirectory(item)) {
435
- scanDirectory(fullPath);
436
- }
437
- } else if (item === "agent.ts" || item === "agent.js") {
438
- const relativePath = relative(scanDir, dir);
439
- const loadedAgent = loadedAgents.get(relativePath);
440
- let agentName = relativePath.split("/").pop() || "unknown";
441
- if (loadedAgent?.agent?.name) {
442
- agentName = loadedAgent.agent.name;
443
- } else {
444
- try {
445
- const agentFilePath = join2(dir, item);
446
- agentName = this.extractAgentNameFromFile(agentFilePath) || agentName;
447
- } catch {
448
- }
449
- }
450
- agents.set(relativePath, {
451
- relativePath,
452
- name: agentName,
453
- absolutePath: dir,
454
- instance: loadedAgent?.agent
455
- });
456
- }
457
- }
458
- };
459
- scanDirectory(scanDir);
460
- this.logger.info(`Agent scan complete. Found ${agents.size} agents. \u2728`);
461
- return agents;
462
- }
463
- extractAgentNameFromFile(filePath) {
464
- try {
465
- const content = readFileSync(filePath, "utf-8");
466
- const nameMatch = content.match(/name\s*:\s*["']([^"']+)["']/);
467
- if (nameMatch?.[1]) {
468
- return nameMatch[1];
469
- }
470
- return null;
471
- } catch {
472
- return null;
473
- }
474
- }
475
- };
476
- var AgentLoader = class {
477
- constructor(quiet = false) {
478
- this.quiet = quiet;
479
- this.logger = new Logger({ name: "agent-loader", quiet: this.quiet });
480
- }
481
- logger;
482
- /**
483
- * Import a TypeScript file by compiling it on-demand
484
- */
485
- async importTypeScriptFile(filePath) {
486
- const startDir = dirname(filePath);
487
- let projectRoot = startDir;
488
- while (projectRoot !== "/" && projectRoot !== dirname(projectRoot)) {
489
- if (existsSync2(join2(projectRoot, "package.json")) || existsSync2(join2(projectRoot, ".env"))) {
490
- break;
491
- }
492
- projectRoot = dirname(projectRoot);
493
- }
494
- if (projectRoot === "/") {
495
- projectRoot = startDir;
496
- }
497
- try {
498
- const { build } = await import("esbuild");
499
- const cacheDir = join2(projectRoot, ".adk-cache");
500
- if (!existsSync2(cacheDir)) {
501
- mkdirSync(cacheDir, { recursive: true });
502
- }
503
- const outFile = join2(cacheDir, `agent-${Date.now()}.mjs`);
504
- const plugin = {
505
- name: "externalize-bare-imports",
506
- setup(build2) {
507
- build2.onResolve({ filter: /.*/ }, (args) => {
508
- if (args.path.startsWith(".") || args.path.startsWith("/") || args.path.startsWith("..")) {
509
- return;
510
- }
511
- return { path: args.path, external: true };
512
- });
513
- }
514
- };
515
- const tsconfigPath = join2(projectRoot, "tsconfig.json");
516
- await build({
517
- entryPoints: [filePath],
518
- outfile: outFile,
519
- bundle: true,
520
- format: "esm",
521
- platform: "node",
522
- target: ["node22"],
523
- sourcemap: false,
524
- logLevel: "silent",
525
- plugins: [plugin],
526
- absWorkingDir: projectRoot,
527
- // Use tsconfig if present for path aliases
528
- ...existsSync2(tsconfigPath) ? { tsconfig: tsconfigPath } : {}
529
- });
530
- const mod = await import(`${pathToFileURL(outFile).href}?t=${Date.now()}`);
531
- let agentExport = mod?.agent;
532
- if (!agentExport && mod?.default) {
533
- agentExport = mod.default.agent ?? mod.default;
534
- }
535
- try {
536
- unlinkSync(outFile);
537
- } catch {
538
- }
539
- if (agentExport) {
540
- const isPrimitive = (v) => v == null || ["string", "number", "boolean"].includes(typeof v);
541
- if (isPrimitive(agentExport)) {
542
- this.logger.info(
543
- `Ignoring primitive 'agent' export in ${filePath}; scanning module for factory...`
544
- );
545
- } else {
546
- this.logger.info(`TS agent imported via esbuild: ${filePath} \u2705`);
547
- return { agent: agentExport };
548
- }
549
- }
550
- return mod;
551
- } catch (e) {
552
- throw new Error(
553
- `Failed to import TS agent via esbuild: ${e instanceof Error ? e.message : String(e)}`
554
- );
555
- }
556
- }
557
- loadEnvironmentVariables(agentFilePath) {
558
- let projectRoot = dirname(agentFilePath);
559
- while (projectRoot !== "/" && projectRoot !== dirname(projectRoot)) {
560
- if (existsSync2(join2(projectRoot, "package.json")) || existsSync2(join2(projectRoot, ".env"))) {
561
- break;
562
- }
563
- projectRoot = dirname(projectRoot);
564
- }
565
- const envFiles = [
566
- ".env.local",
567
- ".env.development.local",
568
- ".env.production.local",
569
- ".env.development",
570
- ".env.production",
571
- ".env"
572
- ];
573
- for (const envFile of envFiles) {
574
- const envPath = join2(projectRoot, envFile);
575
- if (existsSync2(envPath)) {
576
- try {
577
- const envContent = readFileSync(envPath, "utf8");
578
- const envLines = envContent.split("\n");
579
- for (const line of envLines) {
580
- const trimmedLine = line.trim();
581
- if (trimmedLine && !trimmedLine.startsWith("#")) {
582
- const [key, ...valueParts] = trimmedLine.split("=");
583
- if (key && valueParts.length > 0) {
584
- const value = valueParts.join("=").replace(/^"(.*)"$/, "$1");
585
- if (!process.env[key.trim()]) {
586
- process.env[key.trim()] = value.trim();
587
- }
588
- }
589
- }
590
- }
591
- } catch (error) {
592
- this.logger.warn(
593
- `Warning: Could not load ${envFile} file: ${error instanceof Error ? error.message : String(error)}`
594
- );
595
- }
596
- }
597
- }
598
- }
599
- // Minimal resolution logic for agent exports: supports
600
- // 1) export const agent = new LlmAgent(...)
601
- // 2) export function agent() { return new LlmAgent(...) }
602
- // 3) export async function agent() { return new LlmAgent(...) }
603
- // 4) default export (object or function) returning or containing .agent
604
- async resolveAgentExport(mod) {
605
- let candidate = mod?.agent ?? mod?.default?.agent ?? mod?.default ?? mod;
606
- const isLikelyAgentInstance = (obj) => obj && typeof obj === "object" && typeof obj.name === "string";
607
- const isPrimitive = (v) => v == null || ["string", "number", "boolean"].includes(typeof v);
608
- const invokeMaybe = async (fn) => {
609
- let out = fn();
610
- if (out && typeof out === "object" && "then" in out) {
611
- out = await out;
612
- }
613
- return out;
614
- };
615
- if (!isLikelyAgentInstance(candidate) && isPrimitive(candidate) || !isLikelyAgentInstance(candidate) && candidate && candidate === mod) {
616
- candidate = mod;
617
- for (const [key, value] of Object.entries(mod)) {
618
- if (key === "default") continue;
619
- const keyLower = key.toLowerCase();
620
- if (isPrimitive(value)) continue;
621
- if (isLikelyAgentInstance(value)) {
622
- candidate = value;
623
- break;
624
- }
625
- if (value && typeof value === "object" && value.agent && isLikelyAgentInstance(value.agent)) {
626
- candidate = value.agent;
627
- break;
628
- }
629
- if (typeof value === "function" && (/(agent|build|create)/i.test(keyLower) || value.name && /(agent|build|create)/i.test(value.name.toLowerCase()))) {
630
- try {
631
- const maybe = await invokeMaybe(value);
632
- if (isLikelyAgentInstance(maybe)) {
633
- candidate = maybe;
634
- break;
635
- }
636
- if (maybe && typeof maybe === "object" && maybe.agent && isLikelyAgentInstance(maybe.agent)) {
637
- candidate = maybe.agent;
638
- break;
639
- }
640
- } catch (e) {
641
- }
642
- }
643
- }
644
- }
645
- if (typeof candidate === "function") {
646
- try {
647
- candidate = await invokeMaybe(candidate);
648
- } catch (e) {
649
- throw new Error(
650
- `Failed executing exported agent function: ${e instanceof Error ? e.message : String(e)}`
651
- );
652
- }
653
- }
654
- if (candidate && typeof candidate === "object" && candidate.agent && isLikelyAgentInstance(candidate.agent)) {
655
- candidate = candidate.agent;
656
- }
657
- if (candidate?.agent && isLikelyAgentInstance(candidate.agent)) {
658
- candidate = candidate.agent;
659
- }
660
- if (!candidate || !isLikelyAgentInstance(candidate)) {
661
- throw new Error(
662
- "No agent export resolved (expected variable, function, or function returning an agent)"
663
- );
664
- }
665
- return { agent: candidate };
666
- }
667
- };
668
- var AgentManager = class {
669
- constructor(sessionService, quiet = false) {
670
- this.sessionService = sessionService;
671
- this.quiet = quiet;
672
- this.scanner = new AgentScanner(quiet);
673
- this.loader = new AgentLoader(quiet);
674
- this.logger = new Logger({ name: "agent-manager", quiet: this.quiet });
675
- }
676
- agents = /* @__PURE__ */ new Map();
677
- loadedAgents = /* @__PURE__ */ new Map();
678
- scanner;
679
- loader;
680
- logger;
681
- getAgents() {
682
- return this.agents;
683
- }
684
- getLoadedAgents() {
685
- return this.loadedAgents;
686
- }
687
- scanAgents(agentsDir) {
688
- this.agents = this.scanner.scanAgents(agentsDir, this.loadedAgents);
689
- }
690
- async startAgent(agentPath) {
691
- const agent = this.agents.get(agentPath);
692
- if (!agent) {
693
- throw new Error(`Agent not found: ${agentPath}`);
694
- }
695
- if (this.loadedAgents.has(agentPath)) {
696
- return;
697
- }
698
- try {
699
- let agentFilePath = join2(agent.absolutePath, "agent.js");
700
- if (!existsSync2(agentFilePath)) {
701
- agentFilePath = join2(agent.absolutePath, "agent.ts");
702
- }
703
- if (!existsSync2(agentFilePath)) {
704
- throw new Error(
705
- `No agent.js or agent.ts file found in ${agent.absolutePath}`
706
- );
707
- }
708
- this.loader.loadEnvironmentVariables(agentFilePath);
709
- const agentFileUrl = pathToFileURL(agentFilePath).href;
710
- const agentModule = agentFilePath.endsWith(".ts") ? await this.loader.importTypeScriptFile(agentFilePath) : await import(agentFileUrl);
711
- const resolved = await this.loader.resolveAgentExport(agentModule);
712
- const exportedAgent = resolved.agent;
713
- if (!exportedAgent?.name) {
714
- throw new Error(
715
- `Invalid agent export in ${agentFilePath}. Expected an LlmAgent instance with a name property.`
716
- );
717
- }
718
- const agentBuilder = AgentBuilder.create(exportedAgent.name).withAgent(exportedAgent).withSessionService(this.sessionService, {
719
- userId: `user_${agentPath}`,
720
- appName: "adk-server"
721
- });
722
- const { runner, session } = await agentBuilder.build();
723
- const loadedAgent = {
724
- agent: exportedAgent,
725
- runner,
726
- sessionId: session.id,
727
- userId: `user_${agentPath}`,
728
- appName: "adk-server"
729
- };
730
- this.loadedAgents.set(agentPath, loadedAgent);
731
- agent.instance = exportedAgent;
732
- agent.name = exportedAgent.name;
733
- } catch (error) {
734
- const agentName = agent?.name ?? agentPath;
735
- this.logger.error(
736
- `Failed to load agent "${agentName}": ${error instanceof Error ? error.message : String(error)}`
737
- );
738
- throw new Error(
739
- `Failed to load agent: ${error instanceof Error ? error.message : String(error)}`
740
- );
741
- }
742
- }
743
- async stopAgent(agentPath) {
744
- this.loadedAgents.delete(agentPath);
745
- const agent = this.agents.get(agentPath);
746
- if (agent) {
747
- agent.instance = void 0;
748
- }
749
- }
750
- async sendMessageToAgent(agentPath, message, attachments) {
751
- if (!this.loadedAgents.has(agentPath)) {
752
- await this.startAgent(agentPath);
753
- }
754
- const loadedAgent = this.loadedAgents.get(agentPath);
755
- if (!loadedAgent) {
756
- throw new Error("Agent failed to start");
757
- }
758
- try {
759
- if (attachments && attachments.length > 0) {
760
- const request = {
761
- parts: [
762
- { text: message },
763
- ...attachments.map((file) => ({
764
- inlineData: {
765
- mimeType: file.mimeType,
766
- data: file.data
767
- }
768
- }))
769
- ]
770
- };
771
- const response2 = await loadedAgent.runner.ask(request);
772
- return response2;
773
- }
774
- const response = await loadedAgent.runner.ask(message);
775
- return response;
776
- } catch (error) {
777
- const errorMessage = error instanceof Error ? error.message : String(error);
778
- this.logger.error(
779
- `Error sending message to agent ${agentPath}: ${errorMessage}`
780
- );
781
- throw new Error(`Failed to send message to agent: ${errorMessage}`);
782
- }
783
- }
784
- stopAllAgents() {
785
- for (const [agentPath] of this.loadedAgents.entries()) {
786
- this.stopAgent(agentPath);
787
- }
788
- }
789
- };
790
- var SessionManager = class {
791
- constructor(sessionService, quiet = false) {
792
- this.sessionService = sessionService;
793
- this.quiet = quiet;
794
- this.logger = new Logger({ name: "session-manager", quiet: this.quiet });
795
- }
796
- logger;
797
- async getSessionMessages(loadedAgent) {
798
- try {
799
- const session = await this.sessionService.getSession(
800
- loadedAgent.appName,
801
- loadedAgent.userId,
802
- loadedAgent.sessionId
803
- );
804
- if (!session || !session.events) {
805
- return [];
806
- }
807
- const messages = session.events.map((event, index) => ({
808
- id: index + 1,
809
- type: event.author === "user" ? "user" : "assistant",
810
- content: event.content?.parts?.map(
811
- (part) => typeof part === "object" && "text" in part ? part.text : ""
812
- ).join("") || "",
813
- timestamp: new Date(event.timestamp || Date.now()).toISOString()
814
- }));
815
- return messages;
816
- } catch (error) {
817
- this.logger.error(
818
- "Error fetching messages:",
819
- error instanceof Error ? error.message : String(error)
820
- );
821
- return [];
822
- }
823
- }
824
- };
825
-
826
- // src/server/index.ts
827
- var ADKServer = class {
828
- agentManager;
829
- sessionManager;
830
- sessionService;
831
- app;
832
- server;
833
- config;
834
- logger;
835
- constructor(agentsDir, port = 8042, host = "localhost", quiet = false) {
836
- this.config = { agentsDir, port, host, quiet };
837
- this.logger = new Logger({ name: "adk-server", quiet });
838
- this.sessionService = new InMemorySessionService();
839
- this.agentManager = new AgentManager(this.sessionService, quiet);
840
- this.sessionManager = new SessionManager(this.sessionService, quiet);
841
- this.app = new Hono();
842
- setupRoutes(this.app, this.agentManager, this.sessionManager, agentsDir);
843
- this.logger.info(`Starting agent scan in ${agentsDir} \u2728`);
844
- this.agentManager.scanAgents(agentsDir);
845
- }
846
- async start() {
847
- return new Promise((resolve2) => {
848
- this.server = serve({
849
- fetch: this.app.fetch,
850
- port: this.config.port,
851
- hostname: this.config.host
852
- });
853
- setTimeout(() => {
854
- this.logger.info(
855
- `Server listening on http://${this.config.host}:${this.config.port} \u{1F680}`
856
- );
857
- resolve2();
858
- }, 100);
859
- });
860
- }
861
- async stop() {
862
- return new Promise((resolve2) => {
863
- this.logger.info("Stopping server and all agents... \u{1F6D1}");
864
- this.agentManager.stopAllAgents();
865
- if (this.server) {
866
- this.server.close();
867
- }
868
- this.logger.info("Server stopped");
869
- resolve2();
870
- });
871
- }
872
- getPort() {
873
- return this.config.port;
874
- }
875
- };
876
-
877
- // src/commands/serve.ts
878
- async function serveCommand(options = {}) {
879
- const port = options.port || 8042;
880
- const host = options.host || "localhost";
881
- const agentsDir = resolve(options.dir || ".");
882
- if (!existsSync3(agentsDir)) {
883
- console.error(chalk3.red(`\u274C Directory not found: ${agentsDir}`));
884
- process.exit(1);
885
- }
886
- if (!options.quiet) {
887
- console.log(chalk3.blue(`\u{1F680} ADK Server starting on http://${host}:${port}`));
888
- }
889
- const server = new ADKServer(agentsDir, port, host, options.quiet);
890
- try {
891
- await server.start();
892
- if (!options.quiet) {
893
- console.log(chalk3.green("\u2705 Server ready"));
894
- }
895
- const cleanup = async () => {
896
- if (!options.quiet) {
897
- console.log(chalk3.yellow("\n\u{1F6D1} Stopping server..."));
898
- }
899
- await server.stop();
900
- process.exit(0);
901
- };
902
- process.on("SIGINT", cleanup);
903
- process.on("SIGTERM", cleanup);
904
- return server;
905
- } catch (error) {
906
- console.error(chalk3.red("\u274C Failed to start ADK server:"), error);
907
- process.exit(1);
908
- }
909
- }
910
-
911
- // src/commands/run.ts
912
- marked.use(markedTerminal());
913
- async function renderMarkdown(text3) {
914
- try {
915
- const result = await marked(text3);
916
- return typeof result === "string" ? result : text3;
917
- } catch (error) {
918
- return text3;
919
- }
920
- }
921
- var AgentChatClient = class {
922
- apiUrl;
923
- selectedAgent = null;
924
- constructor(apiUrl) {
925
- this.apiUrl = apiUrl;
926
- }
927
- async connect() {
928
- try {
929
- const response = await fetch(`${this.apiUrl}/health`);
930
- if (!response.ok) {
931
- throw new Error("Connection failed");
932
- }
933
- } catch (error) {
934
- throw new Error("\u274C Connection failed");
935
- }
936
- }
937
- async fetchAgents() {
938
- try {
939
- const response = await fetch(`${this.apiUrl}/api/agents`);
940
- if (!response.ok) {
941
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
942
- }
943
- const data = await response.json();
944
- if (Array.isArray(data)) {
945
- return data;
946
- }
947
- if (data && Array.isArray(data.agents)) {
948
- return data.agents;
949
- }
950
- throw new Error(`Unexpected response format: ${JSON.stringify(data)}`);
951
- } catch (error) {
952
- throw new Error(
953
- `Failed to fetch agents: ${error instanceof Error ? error.message : String(error)}`
954
- );
955
- }
956
- }
957
- async selectAgent() {
958
- const agents = await this.fetchAgents();
959
- if (agents.length === 0) {
960
- throw new Error("No agents found in the current directory");
961
- }
962
- if (agents.length === 1) {
963
- return agents[0];
964
- }
965
- const selectedAgent = await p.select({
966
- message: "Choose an agent to chat with:",
967
- options: agents.map((agent) => ({
968
- label: agent.name,
969
- value: agent,
970
- hint: agent.relativePath
971
- }))
972
- });
973
- if (p.isCancel(selectedAgent)) {
974
- p.cancel("Operation cancelled");
975
- process.exit(0);
976
- }
977
- return selectedAgent;
978
- }
979
- // No-op: agents are auto-loaded on message; keeping method removed
980
- async sendMessage(message) {
981
- if (!this.selectedAgent) {
982
- throw new Error("No agent selected");
983
- }
984
- const s = spinner2();
985
- s.start("\u{1F916} Thinking...");
986
- try {
987
- const response = await fetch(
988
- `${this.apiUrl}/api/agents/${encodeURIComponent(this.selectedAgent.relativePath)}/message`,
989
- {
990
- method: "POST",
991
- headers: {
992
- "Content-Type": "application/json"
993
- },
994
- body: JSON.stringify({ message })
995
- }
996
- );
997
- if (!response.ok) {
998
- const errorText = await response.text();
999
- s.stop("\u274C Failed to send message");
1000
- throw new Error(`Failed to send message: ${errorText}`);
1001
- }
1002
- const result = await response.json();
1003
- s.stop("\u{1F916} Assistant:");
1004
- if (result.response) {
1005
- const formattedResponse = await renderMarkdown(result.response);
1006
- log.message(formattedResponse.trim());
1007
- }
1008
- } catch (error) {
1009
- log.error("Failed to send message");
1010
- }
1011
- }
1012
- async startChat() {
1013
- if (!this.selectedAgent) {
1014
- throw new Error("Agent not selected");
1015
- }
1016
- while (true) {
1017
- try {
1018
- const message = await p.text({
1019
- message: "\u{1F4AC} Message:",
1020
- placeholder: "Type your message here..."
1021
- });
1022
- if (p.isCancel(message)) {
1023
- break;
1024
- }
1025
- if (message.trim()) {
1026
- await this.sendMessage(message.trim());
1027
- }
1028
- } catch (error) {
1029
- console.error(chalk4.red("Error in chat:"), error);
1030
- break;
1031
- }
1032
- }
1033
- }
1034
- disconnect() {
1035
- }
1036
- setSelectedAgent(agent) {
1037
- this.selectedAgent = agent;
1038
- }
1039
- };
1040
- async function runAgent(agentPath, options = {}) {
1041
- const envVerbose = process.env.ADK_VERBOSE;
1042
- const isVerbose = options.verbose ?? (envVerbose === "1" || envVerbose === "true");
1043
- if (options.server) {
1044
- const apiPort = 8042;
1045
- const host = options.host || "localhost";
1046
- console.log(chalk4.blue("\u{1F680} Starting ADK Server..."));
1047
- const serveOptions = {
1048
- port: apiPort,
1049
- dir: process.cwd(),
1050
- host,
1051
- quiet: !isVerbose
1052
- };
1053
- try {
1054
- const server = await serveCommand(serveOptions);
1055
- console.log(chalk4.cyan("Press Ctrl+C to stop the server"));
1056
- process.on("SIGINT", async () => {
1057
- console.log(chalk4.yellow("\n\u{1F6D1} Stopping server..."));
1058
- await server.stop();
1059
- process.exit(0);
1060
- });
1061
- return new Promise(() => {
1062
- });
1063
- } catch (error) {
1064
- console.error(chalk4.red("\u274C Failed to start server"));
1065
- process.exit(1);
1066
- }
1067
- }
1068
- const apiUrl = `http://${options.host || "localhost"}:8042`;
1069
- p.intro("\u{1F916} ADK Agent Chat");
1070
- try {
1071
- const healthResponse = await fetch(`${apiUrl}/health`).catch(() => null);
1072
- if (!healthResponse || !healthResponse.ok) {
1073
- const serverSpinner = spinner2();
1074
- serverSpinner.start("\u{1F680} Starting server...");
1075
- const serveOptions = {
1076
- port: 8042,
1077
- // Use new default port
1078
- dir: process.cwd(),
1079
- host: options.host || "localhost",
1080
- quiet: !isVerbose
1081
- };
1082
- await serveCommand(serveOptions);
1083
- await new Promise((resolve2) => setTimeout(resolve2, 1e3));
1084
- serverSpinner.stop("\u2705 Server ready");
1085
- }
1086
- const client = new AgentChatClient(apiUrl);
1087
- await client.connect();
1088
- const agentSpinner = spinner2();
1089
- agentSpinner.start("\u{1F50D} Scanning for agents...");
1090
- const agents = await client.fetchAgents();
1091
- let selectedAgent;
1092
- if (agents.length === 0) {
1093
- agentSpinner.stop("\u274C No agents found");
1094
- p.cancel("No agents found in the current directory");
1095
- process.exit(1);
1096
- } else if (agents.length === 1) {
1097
- selectedAgent = agents[0];
1098
- agentSpinner.stop(`\u{1F916} Found agent: ${selectedAgent.name}`);
1099
- } else {
1100
- agentSpinner.stop(`\u{1F916} Found ${agents.length} agents`);
1101
- const choice = await p.select({
1102
- message: "Choose an agent to chat with:",
1103
- options: agents.map((agent) => ({
1104
- label: agent.name,
1105
- value: agent,
1106
- hint: agent.relativePath
1107
- }))
1108
- });
1109
- if (p.isCancel(choice)) {
1110
- p.cancel("Operation cancelled");
1111
- process.exit(0);
1112
- }
1113
- selectedAgent = choice;
1114
- }
1115
- client.setSelectedAgent(selectedAgent);
1116
- await client.startChat();
1117
- client.disconnect();
1118
- p.outro("Chat ended");
1119
- } catch (error) {
1120
- p.cancel(
1121
- `Error: ${error instanceof Error ? error.message : String(error)}`
1122
- );
1123
- process.exit(1);
1124
- }
1125
- }
1126
-
1127
- // src/commands/web.ts
1128
- import chalk5 from "chalk";
1129
- async function webCommand(options = {}) {
1130
- const apiPort = options.port || 8042;
1131
- const webPort = options.webPort || 3e3;
1132
- const host = options.host || "localhost";
1133
- const useLocal = options.local || false;
1134
- const webUrl = options.webUrl || "https://adk-web.iqai.com";
1135
- console.log(chalk5.blue("\u{1F310} Starting ADK Web Interface..."));
1136
- const serveOptions = {
1137
- port: apiPort,
1138
- dir: options.dir,
1139
- host,
1140
- quiet: true
1141
- };
1142
- await serveCommand(serveOptions);
1143
- let webAppUrl;
1144
- if (useLocal) {
1145
- if (apiPort === 8042) {
1146
- webAppUrl = `http://${host}:${webPort}`;
1147
- } else {
1148
- webAppUrl = `http://${host}:${webPort}?port=${apiPort}`;
1149
- }
1150
- } else {
1151
- if (apiPort === 8042) {
1152
- webAppUrl = webUrl;
1153
- } else {
1154
- webAppUrl = `${webUrl}?port=${apiPort}`;
1155
- }
1156
- }
1157
- console.log(chalk5.cyan(`\u{1F517} Open this URL in your browser: ${webAppUrl}`));
1158
- console.log(chalk5.gray(` API Server: http://${host}:${apiPort}`));
1159
- console.log(chalk5.cyan("Press Ctrl+C to stop the API server"));
1160
- }
1161
-
1162
- // src/index.ts
1163
- program.name("adk").description(package_default.description).version(package_default.version);
1164
- program.command("new").description("Create a new ADK project").argument("[project-name]", "Name of the project to create").option(
1165
- "-t, --template <template>",
1166
- "Template to use (simple-agent, discord-bot, telegram-bot, hono-server, mcp-starter)"
1167
- ).action(async (projectName, options) => {
1168
- try {
1169
- await createProject(projectName, options);
1170
- } catch (error) {
1171
- console.error(chalk6.red("Error creating project:"), error);
1172
- process.exit(1);
1173
- }
1174
- });
1175
- program.command("run").description("Start an interactive chat with an agent").argument(
1176
- "[agent-path]",
1177
- "Path to specific agent (optional - will show selector if multiple agents found)"
1178
- ).option("-s, --server", "Start ADK server only (without chat interface)").option(
1179
- "-h, --host <host>",
1180
- "Host for server (when using --server)",
1181
- "localhost"
1182
- ).action(async (agentPath, options) => {
1183
- try {
1184
- await runAgent(agentPath, options);
1185
- } catch (error) {
1186
- console.error(chalk6.red("Error running agent:"), error);
1187
- process.exit(1);
1188
- }
1189
- });
1190
- program.command("web").description("Start a web interface for testing agents").option("-p, --port <port>", "Port for API server", "8042").option("--web-port <port>", "Port for web app (when using --local)", "3000").option("-h, --host <host>", "Host for servers", "localhost").option(
1191
- "-d, --dir <directory>",
1192
- "Directory to scan for agents (default: current directory)",
1193
- "."
1194
- ).option(
1195
- "--local",
1196
- "Run local web app instead of opening production URL",
1197
- false
1198
- ).option(
1199
- "--web-url <url>",
1200
- "URL of the web application (used when not --local)",
1201
- "https://adk-web.iqai.com"
1202
- ).action(async (options) => {
1203
- try {
1204
- await webCommand(options);
1205
- } catch (error) {
1206
- console.error(chalk6.red("Error starting web UI:"), error);
1207
- process.exit(1);
1208
- }
1209
- });
1210
- program.command("serve").description("Start an API server for agent management").option("-p, --port <port>", "Port for the server", "8042").option("-h, --host <host>", "Host for the server", "localhost").option(
1211
- "-d, --dir <directory>",
1212
- "Directory to scan for agents (default: current directory)",
1213
- "."
1214
- ).action(async (options) => {
1215
- try {
1216
- await serveCommand(options);
1217
- } catch (error) {
1218
- console.error(chalk6.red("Error starting server:"), error);
1219
- process.exit(1);
1220
- }
1221
- });
1222
- program.parse();
1223
- //# sourceMappingURL=index.mjs.map