@agi-cli/server 0.1.81 → 0.1.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agi-cli/server",
3
- "version": "0.1.81",
3
+ "version": "0.1.83",
4
4
  "description": "HTTP API server for AGI CLI",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -29,8 +29,8 @@
29
29
  "typecheck": "tsc --noEmit"
30
30
  },
31
31
  "dependencies": {
32
- "@agi-cli/sdk": "0.1.81",
33
- "@agi-cli/database": "0.1.81",
32
+ "@agi-cli/sdk": "0.1.83",
33
+ "@agi-cli/database": "0.1.83",
34
34
  "drizzle-orm": "^0.44.5",
35
35
  "hono": "^4.9.9",
36
36
  "zod": "^4.1.8"
package/src/index.ts CHANGED
@@ -7,9 +7,9 @@ import { registerSessionsRoutes } from './routes/sessions.ts';
7
7
  import { registerSessionMessagesRoutes } from './routes/session-messages.ts';
8
8
  import { registerSessionStreamRoute } from './routes/session-stream.ts';
9
9
  import { registerAskRoutes } from './routes/ask.ts';
10
- import { registerConfigRoutes } from './routes/config.ts';
10
+ import { registerConfigRoutes } from './routes/config/index.ts';
11
11
  import { registerFilesRoutes } from './routes/files.ts';
12
- import { registerGitRoutes } from './routes/git.ts';
12
+ import { registerGitRoutes } from './routes/git/index.ts';
13
13
  import type { AgentConfigEntry } from './runtime/agent-registry.ts';
14
14
 
15
15
  function initApp() {
@@ -346,4 +346,108 @@ export const gitPaths = {
346
346
  },
347
347
  },
348
348
  },
349
+ '/v1/git/restore': {
350
+ post: {
351
+ tags: ['git'],
352
+ operationId: 'restoreFiles',
353
+ summary: 'Restore files to HEAD',
354
+ requestBody: {
355
+ required: true,
356
+ content: {
357
+ 'application/json': {
358
+ schema: {
359
+ type: 'object',
360
+ properties: {
361
+ project: { type: 'string' },
362
+ files: {
363
+ type: 'array',
364
+ items: { type: 'string' },
365
+ },
366
+ },
367
+ required: ['files'],
368
+ },
369
+ },
370
+ },
371
+ },
372
+ responses: {
373
+ 200: {
374
+ description: 'OK',
375
+ content: {
376
+ 'application/json': {
377
+ schema: {
378
+ type: 'object',
379
+ properties: {
380
+ status: { type: 'string', enum: ['ok'] },
381
+ data: {
382
+ type: 'object',
383
+ properties: {
384
+ restored: {
385
+ type: 'array',
386
+ items: { type: 'string' },
387
+ },
388
+ },
389
+ required: ['restored'],
390
+ },
391
+ },
392
+ required: ['status', 'data'],
393
+ },
394
+ },
395
+ },
396
+ },
397
+ 500: gitErrorResponse(),
398
+ },
399
+ },
400
+ },
401
+ '/v1/git/delete': {
402
+ post: {
403
+ tags: ['git'],
404
+ operationId: 'deleteFiles',
405
+ summary: 'Delete untracked files',
406
+ requestBody: {
407
+ required: true,
408
+ content: {
409
+ 'application/json': {
410
+ schema: {
411
+ type: 'object',
412
+ properties: {
413
+ project: { type: 'string' },
414
+ files: {
415
+ type: 'array',
416
+ items: { type: 'string' },
417
+ },
418
+ },
419
+ required: ['files'],
420
+ },
421
+ },
422
+ },
423
+ },
424
+ responses: {
425
+ 200: {
426
+ description: 'OK',
427
+ content: {
428
+ 'application/json': {
429
+ schema: {
430
+ type: 'object',
431
+ properties: {
432
+ status: { type: 'string', enum: ['ok'] },
433
+ data: {
434
+ type: 'object',
435
+ properties: {
436
+ deleted: {
437
+ type: 'array',
438
+ items: { type: 'string' },
439
+ },
440
+ },
441
+ required: ['deleted'],
442
+ },
443
+ },
444
+ required: ['status', 'data'],
445
+ },
446
+ },
447
+ },
448
+ },
449
+ 500: gitErrorResponse(),
450
+ },
451
+ },
452
+ },
349
453
  } as const;
@@ -0,0 +1,44 @@
1
+ import type { Hono } from 'hono';
2
+ import { loadConfig } from '@agi-cli/sdk';
3
+ import type { EmbeddedAppConfig } from '../../index.ts';
4
+ import { logger } from '../../runtime/logger.ts';
5
+ import { serializeError } from '../../runtime/api-error.ts';
6
+ import { discoverAllAgents, getDefault } from './utils.ts';
7
+
8
+ export function registerAgentsRoute(app: Hono) {
9
+ app.get('/v1/config/agents', async (c) => {
10
+ try {
11
+ const embeddedConfig = c.get('embeddedConfig') as
12
+ | EmbeddedAppConfig
13
+ | undefined;
14
+
15
+ if (embeddedConfig) {
16
+ const agents = embeddedConfig.agents
17
+ ? Object.keys(embeddedConfig.agents)
18
+ : ['general', 'build', 'plan'];
19
+ return c.json({
20
+ agents,
21
+ default: getDefault(
22
+ embeddedConfig.agent,
23
+ embeddedConfig.defaults?.agent,
24
+ 'general',
25
+ ),
26
+ });
27
+ }
28
+
29
+ const projectRoot = c.req.query('project') || process.cwd();
30
+ const cfg = await loadConfig(projectRoot);
31
+
32
+ const allAgents = await discoverAllAgents(cfg.projectRoot);
33
+
34
+ return c.json({
35
+ agents: allAgents,
36
+ default: cfg.defaults.agent,
37
+ });
38
+ } catch (error) {
39
+ logger.error('Failed to get agents', error);
40
+ const errorResponse = serializeError(error);
41
+ return c.json(errorResponse, errorResponse.error.status || 500);
42
+ }
43
+ });
44
+ }
@@ -0,0 +1,21 @@
1
+ import type { Hono } from 'hono';
2
+ import { basename } from 'node:path';
3
+ import { logger } from '../../runtime/logger.ts';
4
+ import { serializeError } from '../../runtime/api-error.ts';
5
+
6
+ export function registerCwdRoute(app: Hono) {
7
+ app.get('/v1/config/cwd', (c) => {
8
+ try {
9
+ const cwd = process.cwd();
10
+ const dirName = basename(cwd);
11
+ return c.json({
12
+ cwd,
13
+ dirName,
14
+ });
15
+ } catch (error) {
16
+ logger.error('Failed to get current working directory', error);
17
+ const errorResponse = serializeError(error);
18
+ return c.json(errorResponse, errorResponse.error.status || 500);
19
+ }
20
+ });
21
+ }
@@ -0,0 +1,14 @@
1
+ import type { Hono } from 'hono';
2
+ import { registerCwdRoute } from './cwd.ts';
3
+ import { registerMainConfigRoute } from './main.ts';
4
+ import { registerAgentsRoute } from './agents.ts';
5
+ import { registerProvidersRoute } from './providers.ts';
6
+ import { registerModelsRoutes } from './models.ts';
7
+
8
+ export function registerConfigRoutes(app: Hono) {
9
+ registerCwdRoute(app);
10
+ registerMainConfigRoute(app);
11
+ registerAgentsRoute(app);
12
+ registerProvidersRoute(app);
13
+ registerModelsRoutes(app);
14
+ }
@@ -0,0 +1,68 @@
1
+ import type { Hono } from 'hono';
2
+ import { loadConfig } from '@agi-cli/sdk';
3
+ import type { EmbeddedAppConfig } from '../../index.ts';
4
+ import { logger } from '../../runtime/logger.ts';
5
+ import { serializeError } from '../../runtime/api-error.ts';
6
+ import {
7
+ discoverAllAgents,
8
+ getAuthorizedProviders,
9
+ getDefault,
10
+ } from './utils.ts';
11
+
12
+ export function registerMainConfigRoute(app: Hono) {
13
+ app.get('/v1/config', async (c) => {
14
+ try {
15
+ const projectRoot = c.req.query('project') || process.cwd();
16
+ const embeddedConfig = c.get('embeddedConfig') as
17
+ | EmbeddedAppConfig
18
+ | undefined;
19
+
20
+ const cfg = await loadConfig(projectRoot);
21
+
22
+ let allAgents: string[];
23
+
24
+ if (embeddedConfig?.agents) {
25
+ const embeddedAgents = Object.keys(embeddedConfig.agents);
26
+ const fileAgents = await discoverAllAgents(cfg.projectRoot);
27
+ allAgents = Array.from(
28
+ new Set([...embeddedAgents, ...fileAgents]),
29
+ ).sort();
30
+ } else {
31
+ allAgents = await discoverAllAgents(cfg.projectRoot);
32
+ }
33
+
34
+ const authorizedProviders = await getAuthorizedProviders(
35
+ embeddedConfig,
36
+ cfg,
37
+ );
38
+
39
+ const defaults = {
40
+ agent: getDefault(
41
+ embeddedConfig?.agent,
42
+ embeddedConfig?.defaults?.agent,
43
+ cfg.defaults.agent,
44
+ ),
45
+ provider: getDefault(
46
+ embeddedConfig?.provider,
47
+ embeddedConfig?.defaults?.provider,
48
+ cfg.defaults.provider,
49
+ ),
50
+ model: getDefault(
51
+ embeddedConfig?.model,
52
+ embeddedConfig?.defaults?.model,
53
+ cfg.defaults.model,
54
+ ),
55
+ };
56
+
57
+ return c.json({
58
+ agents: allAgents,
59
+ providers: authorizedProviders,
60
+ defaults,
61
+ });
62
+ } catch (error) {
63
+ logger.error('Failed to load config', error);
64
+ const errorResponse = serializeError(error);
65
+ return c.json(errorResponse, errorResponse.error.status || 500);
66
+ }
67
+ });
68
+ }
@@ -0,0 +1,109 @@
1
+ import type { Hono } from 'hono';
2
+ import { loadConfig, catalog, type ProviderId } from '@agi-cli/sdk';
3
+ import type { EmbeddedAppConfig } from '../../index.ts';
4
+ import { logger } from '../../runtime/logger.ts';
5
+ import { serializeError } from '../../runtime/api-error.ts';
6
+ import {
7
+ isProviderAuthorizedHybrid,
8
+ getAuthorizedProviders,
9
+ getDefault,
10
+ } from './utils.ts';
11
+
12
+ export function registerModelsRoutes(app: Hono) {
13
+ app.get('/v1/config/providers/:provider/models', async (c) => {
14
+ try {
15
+ const embeddedConfig = c.get('embeddedConfig') as
16
+ | EmbeddedAppConfig
17
+ | undefined;
18
+ const provider = c.req.param('provider') as ProviderId;
19
+
20
+ const projectRoot = c.req.query('project') || process.cwd();
21
+ const cfg = await loadConfig(projectRoot);
22
+
23
+ const authorized = await isProviderAuthorizedHybrid(
24
+ embeddedConfig,
25
+ cfg,
26
+ provider,
27
+ );
28
+
29
+ if (!authorized) {
30
+ logger.warn('Provider not authorized', { provider });
31
+ return c.json({ error: 'Provider not authorized' }, 403);
32
+ }
33
+
34
+ const providerCatalog = catalog[provider];
35
+ if (!providerCatalog) {
36
+ logger.warn('Provider not found in catalog', { provider });
37
+ return c.json({ error: 'Provider not found' }, 404);
38
+ }
39
+
40
+ return c.json({
41
+ models: providerCatalog.models.map((m) => ({
42
+ id: m.id,
43
+ label: m.label || m.id,
44
+ toolCall: m.toolCall,
45
+ reasoning: m.reasoning,
46
+ })),
47
+ default: getDefault(
48
+ embeddedConfig?.model,
49
+ embeddedConfig?.defaults?.model,
50
+ cfg.defaults.model,
51
+ ),
52
+ });
53
+ } catch (error) {
54
+ logger.error('Failed to get provider models', error);
55
+ const errorResponse = serializeError(error);
56
+ return c.json(errorResponse, errorResponse.error.status || 500);
57
+ }
58
+ });
59
+
60
+ app.get('/v1/config/models', async (c) => {
61
+ try {
62
+ const embeddedConfig = c.get('embeddedConfig') as
63
+ | EmbeddedAppConfig
64
+ | undefined;
65
+
66
+ const projectRoot = c.req.query('project') || process.cwd();
67
+ const cfg = await loadConfig(projectRoot);
68
+
69
+ const authorizedProviders = await getAuthorizedProviders(
70
+ embeddedConfig,
71
+ cfg,
72
+ );
73
+
74
+ const modelsMap: Record<
75
+ string,
76
+ {
77
+ label: string;
78
+ models: Array<{
79
+ id: string;
80
+ label: string;
81
+ toolCall?: boolean;
82
+ reasoning?: boolean;
83
+ }>;
84
+ }
85
+ > = {};
86
+
87
+ for (const provider of authorizedProviders) {
88
+ const providerCatalog = catalog[provider];
89
+ if (providerCatalog) {
90
+ modelsMap[provider] = {
91
+ label: providerCatalog.label || provider,
92
+ models: providerCatalog.models.map((m) => ({
93
+ id: m.id,
94
+ label: m.label || m.id,
95
+ toolCall: m.toolCall,
96
+ reasoning: m.reasoning,
97
+ })),
98
+ };
99
+ }
100
+ }
101
+
102
+ return c.json(modelsMap);
103
+ } catch (error) {
104
+ logger.error('Failed to get all models', error);
105
+ const errorResponse = serializeError(error);
106
+ return c.json(errorResponse, errorResponse.error.status || 500);
107
+ }
108
+ });
109
+ }
@@ -0,0 +1,46 @@
1
+ import type { Hono } from 'hono';
2
+ import { loadConfig } from '@agi-cli/sdk';
3
+ import type { ProviderId } from '@agi-cli/sdk';
4
+ import type { EmbeddedAppConfig } from '../../index.ts';
5
+ import { logger } from '../../runtime/logger.ts';
6
+ import { serializeError } from '../../runtime/api-error.ts';
7
+ import { getAuthorizedProviders, getDefault } from './utils.ts';
8
+
9
+ export function registerProvidersRoute(app: Hono) {
10
+ app.get('/v1/config/providers', async (c) => {
11
+ try {
12
+ const embeddedConfig = c.get('embeddedConfig') as
13
+ | EmbeddedAppConfig
14
+ | undefined;
15
+
16
+ if (embeddedConfig) {
17
+ const providers = embeddedConfig.auth
18
+ ? (Object.keys(embeddedConfig.auth) as ProviderId[])
19
+ : [embeddedConfig.provider];
20
+
21
+ return c.json({
22
+ providers,
23
+ default: getDefault(
24
+ embeddedConfig.provider,
25
+ embeddedConfig.defaults?.provider,
26
+ undefined,
27
+ ),
28
+ });
29
+ }
30
+
31
+ const projectRoot = c.req.query('project') || process.cwd();
32
+ const cfg = await loadConfig(projectRoot);
33
+
34
+ const authorizedProviders = await getAuthorizedProviders(undefined, cfg);
35
+
36
+ return c.json({
37
+ providers: authorizedProviders,
38
+ default: cfg.defaults.provider,
39
+ });
40
+ } catch (error) {
41
+ logger.error('Failed to get providers', error);
42
+ const errorResponse = serializeError(error);
43
+ return c.json(errorResponse, errorResponse.error.status || 500);
44
+ }
45
+ });
46
+ }
@@ -0,0 +1,107 @@
1
+ import {
2
+ catalog,
3
+ type ProviderId,
4
+ isProviderAuthorized,
5
+ getGlobalAgentsDir,
6
+ } from '@agi-cli/sdk';
7
+ import { readdir } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ import type { EmbeddedAppConfig } from '../../index.ts';
10
+ import type { AGIConfig } from '@agi-cli/sdk';
11
+ import { logger } from '../../runtime/logger.ts';
12
+ import { loadAgentsConfig } from '../../runtime/agent-registry.ts';
13
+
14
+ export async function isProviderAuthorizedHybrid(
15
+ embeddedConfig: EmbeddedAppConfig | undefined,
16
+ fileConfig: AGIConfig,
17
+ provider: ProviderId,
18
+ ): Promise<boolean> {
19
+ const hasEmbeddedAuth =
20
+ embeddedConfig?.provider === provider ||
21
+ (embeddedConfig?.auth && provider in embeddedConfig.auth);
22
+
23
+ if (hasEmbeddedAuth) {
24
+ return true;
25
+ }
26
+
27
+ return await isProviderAuthorized(fileConfig, provider);
28
+ }
29
+
30
+ export async function getAuthorizedProviders(
31
+ embeddedConfig: EmbeddedAppConfig | undefined,
32
+ fileConfig: AGIConfig,
33
+ ): Promise<ProviderId[]> {
34
+ const allProviders = Object.keys(catalog) as ProviderId[];
35
+ const authorizedProviders: ProviderId[] = [];
36
+
37
+ for (const provider of allProviders) {
38
+ const authorized = await isProviderAuthorizedHybrid(
39
+ embeddedConfig,
40
+ fileConfig,
41
+ provider,
42
+ );
43
+ if (authorized) {
44
+ authorizedProviders.push(provider);
45
+ }
46
+ }
47
+
48
+ return authorizedProviders;
49
+ }
50
+
51
+ export function getDefault<T>(
52
+ embeddedValue: T | undefined,
53
+ embeddedDefaultValue: T | undefined,
54
+ fileValue: T,
55
+ ): T {
56
+ return embeddedValue ?? embeddedDefaultValue ?? fileValue;
57
+ }
58
+
59
+ export async function discoverAllAgents(
60
+ projectRoot: string,
61
+ ): Promise<string[]> {
62
+ const builtInAgents = ['general', 'build', 'plan'];
63
+ const agentSet = new Set<string>(builtInAgents);
64
+
65
+ try {
66
+ const agentsJson = await loadAgentsConfig(projectRoot);
67
+ for (const agentName of Object.keys(agentsJson)) {
68
+ if (agentName.trim()) {
69
+ agentSet.add(agentName);
70
+ }
71
+ }
72
+ } catch (err) {
73
+ logger.debug('Failed to load agents.json', err);
74
+ }
75
+
76
+ try {
77
+ const localAgentsPath = join(projectRoot, '.agi', 'agents');
78
+ const localFiles = await readdir(localAgentsPath).catch(() => []);
79
+ for (const file of localFiles) {
80
+ if (file.endsWith('.txt') || file.endsWith('.md')) {
81
+ const agentName = file.replace(/\.(txt|md)$/, '');
82
+ if (agentName.trim()) {
83
+ agentSet.add(agentName);
84
+ }
85
+ }
86
+ }
87
+ } catch (err) {
88
+ logger.debug('Failed to read local agents directory', err);
89
+ }
90
+
91
+ try {
92
+ const globalAgentsPath = getGlobalAgentsDir();
93
+ const globalFiles = await readdir(globalAgentsPath).catch(() => []);
94
+ for (const file of globalFiles) {
95
+ if (file.endsWith('.txt') || file.endsWith('.md')) {
96
+ const agentName = file.replace(/\.(txt|md)$/, '');
97
+ if (agentName.trim()) {
98
+ agentSet.add(agentName);
99
+ }
100
+ }
101
+ }
102
+ } catch (err) {
103
+ logger.debug('Failed to read global agents directory', err);
104
+ }
105
+
106
+ return Array.from(agentSet).sort();
107
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Hono } from 'hono';
2
- import { readdir } from 'node:fs/promises';
2
+ import { readdir, readFile } from 'node:fs/promises';
3
3
  import { join, relative } from 'node:path';
4
4
  import { exec } from 'node:child_process';
5
5
  import { promisify } from 'node:util';
@@ -38,6 +38,51 @@ function shouldExclude(name: string): boolean {
38
38
  return false;
39
39
  }
40
40
 
41
+ async function parseGitignore(projectRoot: string): Promise<Set<string>> {
42
+ const patterns = new Set<string>();
43
+ try {
44
+ const gitignorePath = join(projectRoot, '.gitignore');
45
+ const content = await readFile(gitignorePath, 'utf-8');
46
+ for (const line of content.split('\n')) {
47
+ const trimmed = line.trim();
48
+ if (trimmed && !trimmed.startsWith('#')) {
49
+ patterns.add(trimmed);
50
+ }
51
+ }
52
+ } catch (_err) {}
53
+ return patterns;
54
+ }
55
+
56
+ function matchesGitignorePattern(
57
+ relativePath: string,
58
+ patterns: Set<string>,
59
+ ): boolean {
60
+ for (const pattern of patterns) {
61
+ const cleanPattern = pattern.replace(/^\//, '').replace(/\/$/, '');
62
+ const pathParts = relativePath.split('/');
63
+
64
+ if (pattern.endsWith('/')) {
65
+ if (pathParts[0] === cleanPattern) return true;
66
+ if (relativePath.startsWith(`${cleanPattern}/`)) return true;
67
+ }
68
+
69
+ if (pattern.includes('*')) {
70
+ const regex = new RegExp(
71
+ `^${cleanPattern.replace(/\*/g, '.*').replace(/\?/g, '.')}$`,
72
+ );
73
+ if (regex.test(relativePath)) return true;
74
+ for (const part of pathParts) {
75
+ if (regex.test(part)) return true;
76
+ }
77
+ } else {
78
+ if (relativePath === cleanPattern) return true;
79
+ if (pathParts.includes(cleanPattern)) return true;
80
+ if (relativePath.startsWith(`${cleanPattern}/`)) return true;
81
+ }
82
+ }
83
+ return false;
84
+ }
85
+
41
86
  async function traverseDirectory(
42
87
  dir: string,
43
88
  projectRoot: string,
@@ -45,6 +90,7 @@ async function traverseDirectory(
45
90
  currentDepth = 0,
46
91
  limit: number,
47
92
  collected: string[] = [],
93
+ gitignorePatterns?: Set<string>,
48
94
  ): Promise<{ files: string[]; truncated: boolean }> {
49
95
  if (currentDepth >= maxDepth || collected.length >= limit) {
50
96
  return { files: collected, truncated: collected.length >= limit };
@@ -65,6 +111,13 @@ async function traverseDirectory(
65
111
  const fullPath = join(dir, entry.name);
66
112
  const relativePath = relative(projectRoot, fullPath);
67
113
 
114
+ if (
115
+ gitignorePatterns &&
116
+ matchesGitignorePattern(relativePath, gitignorePatterns)
117
+ ) {
118
+ continue;
119
+ }
120
+
68
121
  if (entry.isDirectory()) {
69
122
  const result = await traverseDirectory(
70
123
  fullPath,
@@ -73,6 +126,7 @@ async function traverseDirectory(
73
126
  currentDepth + 1,
74
127
  limit,
75
128
  collected,
129
+ gitignorePatterns,
76
130
  );
77
131
  if (result.truncated) {
78
132
  return result;
@@ -112,7 +166,7 @@ async function getChangedFiles(
112
166
  }
113
167
  }
114
168
  return changedFiles;
115
- } catch (err) {
169
+ } catch (_err) {
116
170
  return new Set();
117
171
  }
118
172
  }
@@ -124,12 +178,16 @@ export function registerFilesRoutes(app: Hono) {
124
178
  const maxDepth = Number.parseInt(c.req.query('maxDepth') || '10', 10);
125
179
  const limit = Number.parseInt(c.req.query('limit') || '1000', 10);
126
180
 
181
+ const gitignorePatterns = await parseGitignore(projectRoot);
182
+
127
183
  const result = await traverseDirectory(
128
184
  projectRoot,
129
185
  projectRoot,
130
186
  maxDepth,
131
187
  0,
132
188
  limit,
189
+ [],
190
+ gitignorePatterns,
133
191
  );
134
192
 
135
193
  const changedFiles = await getChangedFiles(projectRoot);