Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

AgentStack SDK

npm versionLicense: MIT

Languages:English (canonical) · Русский (this file)

English README (GitHub / npm / AI default):README.en.mdканон API и интеграции.

Этот файл (README.md) — расширенный русский narrative (история, примеры). Не дублируйте устаревшие API: сверяйтесь с EN.

Сверка стиля: docs/DOC_STYLE_GAP_ru.md · Doc hub:docs/DOC_HUB_ru.md

Универсальный TypeScript/JavaScript SDK для экосистемы AgentStack. Модульный API: auth, projects, payments, DNA, protocol, Neural Architecture.

Quick Start (TypeScript/JavaScript):

npm install @agentstack/sdk
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});constprojects=awaitsdk.platform.api.getProjects();constcatalog=sdk.getModuleCatalog();// AI: discover modules, hints, examples

AI entry:AGENTS.md · docs/AI_APPLICATION_FACTORY.md
Integrator scope (no ecosystem admin):docs/INTEGRATOR_SCOPE.md
All integration flows (npm, submodule, monorepo, …):docs/SDK_INTEGRATION_FLOWS.md

Links:Changelog | Contributing


How to add the SDK to your project

FlowWhenInstall
A — npm (default)Production apps, most integratorsnpm install @agentstack/sdk
B — git submodulePin SDK commit in git, vendored CIdocs/SUBMODULE_CONSUMER.mdvendor/agentstack-sdk
D — monorepo siblingYou work inside AgentStack"@agentstack/sdk": "file:../agentstack-unified-sdk/packages/core"
E — local file: / npm linkDeveloping SDK + app togetherPUBLISHING.md
G — PythonPython backendspip install agentstack-sdk

Full decision tree, CI, and env checklist: docs/SDK_INTEGRATION_FLOWS.md.

Submodule in one minute

git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
node vendor/agentstack-sdk/scripts/bootstrap-submodule-consumer.mjs --target . --tag v0.4.13

Then npm install in your app and set projectId — see docs/PROJECT_CONTEXT.md.


Современный, универсальный SDK для экосистемы AgentStack с интеграцией Neural Architecture и Admin SDK. Удобный и понятный API для разработчиков и AI агентов.

🎯 Цели проекта

  • Единообразие: Один SDK для всех API запросов
  • Простота: Интуитивный API для разработчиков
  • Надежность: Встроенные механизмы retry, кэширования, error handling
  • Производительность: Оптимизированные запросы с Neural Cache
  • Масштабируемость: Легкое добавление новых сервисов
  • Мультиязычность: Поддержка TypeScript, Python, и других языков
  • Neural Integration: Полная интеграция с Neural Architecture
  • Project-scoped APIs: RBAC, DNA, economy — без экосистемной /api/admin/* (см. INTEGRATOR_SCOPE)

🏗️ Архитектура

agentstack-sdk/
├── packages/
│ ├── core/ # @agentstack/sdk
│ │ ├── src/
│ │ │ ├── client/ # HTTP и WebSocket клиенты
│ │ │ │ ├── AgentHTTP.ts # HTTP клиент
│ │ │ │ └── AgentWebSocket.ts # WebSocket клиент
│ │ │ ├── modules/ # Модули SDK
│ │ │ │ ├── AgentAuth.ts # Аутентификация
│ │ │ │ ├── AgentAPI.ts # Основные API
│ │ │ │ ├── AgentAdmin.ts # Админ функции
│ │ │ │ ├── AgentNeural.ts # Neural Architecture
│ │ │ │ ├── AgentDocs.ts # Документация
│ │ │ │ ├── AgentPayments.ts # Платежи
│ │ │ │ ├── AgentAnalytics.ts # Аналитика
│ │ │ │ ├── AgentWebhooks.ts # Webhooks
│ │ │ │ └── AgentScheduler.ts # Планировщик
│ │ │ ├── types/ # TypeScript типы
│ │ │ ├── utils/ # Утилиты
│ │ │ │ ├── AgentCache.ts # Кэширование
│ │ │ │ ├── AgentRetry.ts # Retry логика
│ │ │ │ └── AgentLogger.ts # Логирование
│ │ │ └── index.ts
│ │ └── package.json
│ ├── react/ # @agentstack/react
│ │ ├── src/
│ │ │ ├── hooks/ # React хуки
│ │ │ │ ├── useAgentAuth.ts
│ │ │ │ ├── useAgentAdmin.ts
│ │ │ │ ├── useAgentPayments.ts
│ │ │ │ └── useAgentNeural.ts
│ │ │ ├── components/ # React компоненты
│ │ │ │ ├── AgentProvider.tsx
│ │ │ │ ├── AgentAuthGuard.tsx
│ │ │ │ └── AgentAdminPanel.tsx
│ │ │ └── index.ts
│ │ └── package.json
│ └── python/ # agentstack-sdk
│ ├── src/
│ │ ├── client/ # HTTP клиент
│ │ ├── modules/ # Модули Python SDK
│ │ │ ├── agent_auth.py
│ │ │ ├── agent_api.py
│ │ │ ├── agent_admin.py
│ │ │ ├── agent_neural.py
│ │ │ └── agent_payments.py
│ │ └── __init__.py
│ └── setup.py
├── docs/ # Документация
├── examples/ # Примеры использования
├── tests/ # Тесты
└── tools/ # Инструменты разработки

🚀 Ключевые особенности

Core SDK

  • Умный HTTP клиент с автоматическим retry и кэшированием
  • Автоматическая аутентификация с refresh токенами
  • Type-safe API с полной типизацией TypeScript
  • Модульная архитектура с понятными названиями модулей
  • Neural Cache Integration - интеллектуальное кэширование
  • Admin SDK - специализированные методы для администрирования
  • Error Handling с автоматическим retry и fallback
  • Request/Response Interceptors для логирования и мониторинга

🎯 Модули SDK

  • AgentAuth - аутентификация и авторизация
  • AgentAPI - основные API операции
  • AgentAdmin - административные функции
  • AgentNeural - Neural Architecture интеграция
  • AgentDocs - документация и справка
  • AgentPayments - платежная система
  • AgentAnalytics - аналитика и метрики
  • AgentWebhooks - webhook'и
  • AgentScheduler - планировщик задач

Admin SDK (NEW!)

  • User Management - полное управление пользователями
  • System Statistics - метрики и аналитика системы
  • Bulk Operations - массовые операции с пользователями
  • Security Management - управление безопасностью
  • Dashboard Metrics - метрики для дашборда

Neural Architecture Integration

  • Neural Cache - интеллектуальное кэширование с предсказаниями
  • Neural Events - система событий для межмодульной коммуникации
  • Pattern Analysis - анализ паттернов использования
  • Auto Optimization - автоматическая оптимизация запросов

React Integration

  • React Hooks для всех сервисов
  • Context Provider для глобального состояния
  • Admin Components - готовые компоненты для админки
  • Real-time Updates с WebSocket поддержкой

📦 Установка

See docs/SDK_INTEGRATION_FLOWS.md for npm vs submodule vs monorepo vs npm link.

Quick paths:

# A — npm (default)
npm install @agentstack/sdk
npm install @agentstack/react @tanstack/react-query # optional UI# B — git submodule (see SUBMODULE_CONSUMER.md)
git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
# G — Python
pip install agentstack-sdk

🚀 Быстрый старт

TypeScript/JavaScript

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});// Использование модулей SDK (tenant / integrator)awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password'});constprojects=awaitsdk.platform.api.getProjects();constpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB'});// Использование Neural Cacheawaitsdk.neural.cache.set('key','value');constvalue=awaitsdk.neural.cache.get('key');// Использование документацииconsthelp=awaitsdk.docs.getHelp('auth');

Python

fromagentstackimportAgentStackSDKsdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key'
)
# Tenant APIs (no ecosystem admin — see docs/INTEGRATOR_SCOPE.md)projects=awaitsdk.api.get("/projects")
# Использование Neural Cacheawaitsdk.neural.cache.set('key', 'value')
value=awaitsdk.neural.cache.get('key')

React

import{SDKProvider,useSDK}from'@agentstack/react';functionApp(){return(<SDKProviderconfig={{apiBase: 'https://agentstack.tech/api',apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),}}><ProjectList/></SDKProvider>);}functionProjectList(){constsdk=useSDK();// useSDKQuery / sdk.platform.api — see docs/REACT_QUERY_INTEGRATION.md}

Ecosystem admin hooks (useAdminUsers, …) require sdkAudience: 'platform_operator' in the AgentStack monorepo only — see docs/INTEGRATOR_SCOPE.md.

🔧 API Reference

Core Services

Auth Service

// Предпочитайте sdk.platform.auth (sdk.auth — тот же модуль)consttokens=awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password',project_id: 1,});constnewTokens=awaitsdk.platform.auth.refresh(tokens.refresh_token);constprofile=awaitsdk.platform.auth.getProfile();

Projects Service

// REST (preferred for apps and AI agents)constprojects=awaitsdk.platform.api.getProjects();constproject=awaitsdk.platform.api.getProject(projectId);// 8DNA project row (advanced)constrow=awaitsdk.platform.dna.get('data_projects_8dna',{id: projectId,project_id: 0,});

Payments Service

// Создание платежаconstpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB',description: 'Test payment'});// Получение статусаconststatus=awaitsdk.payments.getPaymentStatus(payment.id);// История платежейconsttransactions=awaitsdk.payments.getTransactions({limit: 20,offset: 0});

Platform operator only (not in npm integrator docs)

Ecosystem admin (sdk.admin, /api/admin/*) is not available to tenant apps. Default SDKConfig.sdkAudience is integrator. AgentStack monorepo ops shells use sdkAudience: 'platform_operator'. Details: docs/INTEGRATOR_SCOPE.md.

AgentDocs - Документация и справка

// Получение справки по темеconsthelp=awaitsdk.docs.getHelp('auth');// Поиск по документацииconstresults=awaitsdk.docs.search('payment integration');// Получение примеров кодаconstexamples=awaitsdk.docs.getCodeExamples({language: 'typescript',category: 'payments'});// Получение FAQconstfaq=awaitsdk.docs.getFAQ('payments');

Neural Architecture Integration

Neural Cache

// Кэширование данныхawaitsdk.neural.cache.set('user:123:profile',userProfile,300);constprofile=awaitsdk.neural.cache.get('user:123:profile');// Кэширование с тегамиawaitsdk.neural.cache.setWithTags('project:456',projectData,['projects','active'],600);// Инвалидация кэшаawaitsdk.neural.cache.invalidateByPattern('user:123:*');awaitsdk.neural.cache.invalidateByTag('projects');

Neural Events

awaitsdk.neural.emitEvent('payment_created',{payment_id: '123',amount: 1000,currency: 'RUB',});awaitsdk.neural.emitEvent('payment_created',{payment_id: 'pay_1'});sdk.on('neural:cache:hit',(key)=>console.debug('cache hit',key));

Pattern Analysis

constpatterns=awaitsdk.neural.patterns.analyze('user_behavior',{user_id: 123,project_id: 1,period: '30d',});constpredictions=awaitsdk.neural.patterns.predict('payment_success',{user_id: 123,project_id: 1,input_data: {amount: 1000,currency: 'RUB'},});

🎨 React Hooks

Admin Hooks (только оператор платформы)

Хуки useAdminUsers, useAdminStats, useAdminDashboardне для tenant npm-приложений. Нужен sdkAudience: 'platform_operator' в monorepo AgentStack.

Пример: examples/typescript/operator-admin-usage.ts · docs/INTEGRATOR_SCOPE_ru.md

Core Hooks (интегратор)

import{useAuth,useProjects,usePayments}from'@agentstack/react';functionApp(){const{ user, login, logout }=useAuth();const{ projects, createProject }=useProjects();const{ payments, createPayment }=usePayments();return(<div>{user ? (<div><h1>Welcome, {user.email}!</h1><buttononClick={logout}>Logout</button><h2>Projects</h2>{projects.map(project=>(<divkey={project.id}>{project.name}</div>))}</div>) : (<buttononClick={()=>login('user@example.com','password')}>
Login
</button>)}</div>);}

🔧 Конфигурация

TypeScript/JavaScript

constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'your_api_key',// Neural Architectureneural: {cache: {enabled: true,ttl: 300,maxSize: 1000},events: {enabled: true,bufferSize: 10000}},// Retry configurationretry: {attempts: 3,delay: 1000,backoff: 'exponential'},// Cache configurationcache: {enabled: true,ttl: 300},// Logginglogging: {level: 'info',enabled: true}});

Python

sdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key',
# Neural Architectureneural={
'cache': {
'enabled': True,
'ttl': 300,
'max_size': 1000
},
'events': {
'enabled': True,
'buffer_size': 10000
}
},
# Retry configurationretry={
'attempts': 3,
'delay': 1000,
'backoff': 'exponential'
},
# Cache configurationcache={
'enabled': True,
'ttl': 300
},
# Logginglogging={
'level': 'info',
'enabled': True
}
)

🧪 Тестирование

Unit Tests

import{AgentStackSDK}from'@agentstack/sdk';describe('Integrator SDK',()=>{letsdk: AgentStackSDK;beforeEach(()=>{sdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'test_key',});});it('should list projects via platform.api',async()=>{constprojects=awaitsdk.platform.api.getProjects();expect(Array.isArray(projects)).toBe(true);});it('should not expose admin in module catalog',()=>{constids=sdk.getModuleCatalog().modules.map((m)=>m.id);expect(ids).not.toContain('admin');});});

Integration Tests

describe('SDK Integration',()=>{it('should handle authentication flow',async()=>{consttokens=awaitsdk.platform.auth.login({email: 'test@example.com',password: 'password',project_id: 1,});expect(tokens.access_token).toBeDefined();expect(tokens.refresh_token).toBeDefined();constprofile=awaitsdk.platform.auth.getProfile();expect(profile.email).toBe('test@example.com');});});

📚 Примеры использования

Project dashboard (integrator)

classProjectDashboard{constructor(privatesdk: AgentStackSDK){}asyncgetDashboardData(projectId: number){constproject=awaitthis.sdk.platform.api.getProject(projectId);constcatalog=this.sdk.getModuleCatalog();return{ project, catalog };}}

Neural Cache Usage

// Пример использования Neural CacheclassUserService{privatesdk: AgentStackSDK;constructor(sdk: AgentStackSDK){this.sdk=sdk;}asyncgetMemberProfile(projectId: number,userId: number){constkey=`user:${userId}:profile`;constcached=awaitthis.sdk.neural.cache.get(key);if(cached)returncached;const{ users }=awaitthis.sdk.platform.api.getProjectUsers(projectId,{limit: 100});constmember=users.find((u)=>u.id===userId);if(member)awaitthis.sdk.neural.cache.set(key,member,300);returnmember;}asyncupdateMyProfile(updates: {display_name?: string}){awaitthis.sdk.platform.auth.updateProfileData(updates);awaitthis.sdk.neural.cache.invalidateByPattern('user:*');}}

🔒 Безопасность

  • Не коммитьте API keys; используйте AGENTSTACK_API_KEY / VITE_AGENTSTACK_API_KEY.
  • Tenant-приложения: безsdk.admindocs/INTEGRATOR_SCOPE.md.
  • Ключи проекта — через панель проекта / sdk.platform.api, не устаревший sdk.auth.createApiKey (deprecated).
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: process.env.AGENTSTACK_API_BASE??resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),timeout: 30000,});

📊 Мониторинг и метрики

SDK Metrics

// Получение метрик SDKconstmetrics=awaitsdk.getMetrics();console.log('Requests:',metrics.requests);console.log('Cache Hit Rate:',metrics.cacheHitRate);console.log('Average Latency:',metrics.averageLatency);

Neural Architecture Metrics

// Получение метрик Neural ArchitectureconstneuralMetrics=awaitsdk.neural.getMetrics();console.log('Neural Cache Hit Rate:',neuralMetrics.cache.hitRate);console.log('Neural Events Throughput:',neuralMetrics.events.throughput);console.log('Pattern Analysis Accuracy:',neuralMetrics.patterns.accuracy);

Production API base

Production REST base is https://agentstack.tech/api. Prefer the helper (Node, scripts, examples):

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});
EnvironmentConfiguration
Production (default)Omit AGENTSTACK_API_BASEhttps://agentstack.tech/api
Local CoreAGENTSTACK_API_BASE=http://localhost:8000/api
Vite SPAVITE_API_BASE_URL=https://agentstack.tech/api (no /api suffix in some setups — HTTPClient normalizes)
# Node / CI
AGENTSTACK_API_BASE=https://agentstack.tech/api
AGENTSTACK_API_KEY=your_api_key

The SDK is a client library — deploy your app as you normally would (static host, serverless, container). No separate “SDK Docker image” is required.

🤝 Contributing

Мы приветствуем вклад в развитие SDK! Пожалуйста, ознакомьтесь с нашими руководящими принципами:

  1. Следуйте TypeScript best practices
  2. Добавляйте тесты для нового функционала
  3. Обновляйте документацию
  4. Используйте Neural Architecture компоненты
  5. Поддерживайте обратную совместимость

📞 Поддержка


npm:@agentstack/sdk · AI entry:AGENTS.md · Integrator scope:docs/INTEGRATOR_SCOPE.md

About

SDK for fast AI build apps

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

AgentStack SDK

npm versionLicense: MIT

Languages:English (canonical) · Русский (this file)

English README (GitHub / npm / AI default):README.en.mdканон API и интеграции.

Этот файл (README.md) — расширенный русский narrative (история, примеры). Не дублируйте устаревшие API: сверяйтесь с EN.

Сверка стиля: docs/DOC_STYLE_GAP_ru.md · Doc hub:docs/DOC_HUB_ru.md

Универсальный TypeScript/JavaScript SDK для экосистемы AgentStack. Модульный API: auth, projects, payments, DNA, protocol, Neural Architecture.

Quick Start (TypeScript/JavaScript):

npm install @agentstack/sdk
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});constprojects=awaitsdk.platform.api.getProjects();constcatalog=sdk.getModuleCatalog();// AI: discover modules, hints, examples

AI entry:AGENTS.md · docs/AI_APPLICATION_FACTORY.md
Integrator scope (no ecosystem admin):docs/INTEGRATOR_SCOPE.md
All integration flows (npm, submodule, monorepo, …):docs/SDK_INTEGRATION_FLOWS.md

Links:Changelog | Contributing


How to add the SDK to your project

FlowWhenInstall
A — npm (default)Production apps, most integratorsnpm install @agentstack/sdk
B — git submodulePin SDK commit in git, vendored CIdocs/SUBMODULE_CONSUMER.mdvendor/agentstack-sdk
D — monorepo siblingYou work inside AgentStack"@agentstack/sdk": "file:../agentstack-unified-sdk/packages/core"
E — local file: / npm linkDeveloping SDK + app togetherPUBLISHING.md
G — PythonPython backendspip install agentstack-sdk

Full decision tree, CI, and env checklist: docs/SDK_INTEGRATION_FLOWS.md.

Submodule in one minute

git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
node vendor/agentstack-sdk/scripts/bootstrap-submodule-consumer.mjs --target . --tag v0.4.13

Then npm install in your app and set projectId — see docs/PROJECT_CONTEXT.md.


Современный, универсальный SDK для экосистемы AgentStack с интеграцией Neural Architecture и Admin SDK. Удобный и понятный API для разработчиков и AI агентов.

🎯 Цели проекта

  • Единообразие: Один SDK для всех API запросов
  • Простота: Интуитивный API для разработчиков
  • Надежность: Встроенные механизмы retry, кэширования, error handling
  • Производительность: Оптимизированные запросы с Neural Cache
  • Масштабируемость: Легкое добавление новых сервисов
  • Мультиязычность: Поддержка TypeScript, Python, и других языков
  • Neural Integration: Полная интеграция с Neural Architecture
  • Project-scoped APIs: RBAC, DNA, economy — без экосистемной /api/admin/* (см. INTEGRATOR_SCOPE)

🏗️ Архитектура

agentstack-sdk/
├── packages/
│ ├── core/ # @agentstack/sdk
│ │ ├── src/
│ │ │ ├── client/ # HTTP и WebSocket клиенты
│ │ │ │ ├── AgentHTTP.ts # HTTP клиент
│ │ │ │ └── AgentWebSocket.ts # WebSocket клиент
│ │ │ ├── modules/ # Модули SDK
│ │ │ │ ├── AgentAuth.ts # Аутентификация
│ │ │ │ ├── AgentAPI.ts # Основные API
│ │ │ │ ├── AgentAdmin.ts # Админ функции
│ │ │ │ ├── AgentNeural.ts # Neural Architecture
│ │ │ │ ├── AgentDocs.ts # Документация
│ │ │ │ ├── AgentPayments.ts # Платежи
│ │ │ │ ├── AgentAnalytics.ts # Аналитика
│ │ │ │ ├── AgentWebhooks.ts # Webhooks
│ │ │ │ └── AgentScheduler.ts # Планировщик
│ │ │ ├── types/ # TypeScript типы
│ │ │ ├── utils/ # Утилиты
│ │ │ │ ├── AgentCache.ts # Кэширование
│ │ │ │ ├── AgentRetry.ts # Retry логика
│ │ │ │ └── AgentLogger.ts # Логирование
│ │ │ └── index.ts
│ │ └── package.json
│ ├── react/ # @agentstack/react
│ │ ├── src/
│ │ │ ├── hooks/ # React хуки
│ │ │ │ ├── useAgentAuth.ts
│ │ │ │ ├── useAgentAdmin.ts
│ │ │ │ ├── useAgentPayments.ts
│ │ │ │ └── useAgentNeural.ts
│ │ │ ├── components/ # React компоненты
│ │ │ │ ├── AgentProvider.tsx
│ │ │ │ ├── AgentAuthGuard.tsx
│ │ │ │ └── AgentAdminPanel.tsx
│ │ │ └── index.ts
│ │ └── package.json
│ └── python/ # agentstack-sdk
│ ├── src/
│ │ ├── client/ # HTTP клиент
│ │ ├── modules/ # Модули Python SDK
│ │ │ ├── agent_auth.py
│ │ │ ├── agent_api.py
│ │ │ ├── agent_admin.py
│ │ │ ├── agent_neural.py
│ │ │ └── agent_payments.py
│ │ └── __init__.py
│ └── setup.py
├── docs/ # Документация
├── examples/ # Примеры использования
├── tests/ # Тесты
└── tools/ # Инструменты разработки

🚀 Ключевые особенности

Core SDK

  • Умный HTTP клиент с автоматическим retry и кэшированием
  • Автоматическая аутентификация с refresh токенами
  • Type-safe API с полной типизацией TypeScript
  • Модульная архитектура с понятными названиями модулей
  • Neural Cache Integration - интеллектуальное кэширование
  • Admin SDK - специализированные методы для администрирования
  • Error Handling с автоматическим retry и fallback
  • Request/Response Interceptors для логирования и мониторинга

🎯 Модули SDK

  • AgentAuth - аутентификация и авторизация
  • AgentAPI - основные API операции
  • AgentAdmin - административные функции
  • AgentNeural - Neural Architecture интеграция
  • AgentDocs - документация и справка
  • AgentPayments - платежная система
  • AgentAnalytics - аналитика и метрики
  • AgentWebhooks - webhook'и
  • AgentScheduler - планировщик задач

Admin SDK (NEW!)

  • User Management - полное управление пользователями
  • System Statistics - метрики и аналитика системы
  • Bulk Operations - массовые операции с пользователями
  • Security Management - управление безопасностью
  • Dashboard Metrics - метрики для дашборда

Neural Architecture Integration

  • Neural Cache - интеллектуальное кэширование с предсказаниями
  • Neural Events - система событий для межмодульной коммуникации
  • Pattern Analysis - анализ паттернов использования
  • Auto Optimization - автоматическая оптимизация запросов

React Integration

  • React Hooks для всех сервисов
  • Context Provider для глобального состояния
  • Admin Components - готовые компоненты для админки
  • Real-time Updates с WebSocket поддержкой

📦 Установка

See docs/SDK_INTEGRATION_FLOWS.md for npm vs submodule vs monorepo vs npm link.

Quick paths:

# A — npm (default)
npm install @agentstack/sdk
npm install @agentstack/react @tanstack/react-query # optional UI# B — git submodule (see SUBMODULE_CONSUMER.md)
git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
# G — Python
pip install agentstack-sdk

🚀 Быстрый старт

TypeScript/JavaScript

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});// Использование модулей SDK (tenant / integrator)awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password'});constprojects=awaitsdk.platform.api.getProjects();constpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB'});// Использование Neural Cacheawaitsdk.neural.cache.set('key','value');constvalue=awaitsdk.neural.cache.get('key');// Использование документацииconsthelp=awaitsdk.docs.getHelp('auth');

Python

fromagentstackimportAgentStackSDKsdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key'
)
# Tenant APIs (no ecosystem admin — see docs/INTEGRATOR_SCOPE.md)projects=awaitsdk.api.get("/projects")
# Использование Neural Cacheawaitsdk.neural.cache.set('key', 'value')
value=awaitsdk.neural.cache.get('key')

React

import{SDKProvider,useSDK}from'@agentstack/react';functionApp(){return(<SDKProviderconfig={{apiBase: 'https://agentstack.tech/api',apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),}}><ProjectList/></SDKProvider>);}functionProjectList(){constsdk=useSDK();// useSDKQuery / sdk.platform.api — see docs/REACT_QUERY_INTEGRATION.md}

Ecosystem admin hooks (useAdminUsers, …) require sdkAudience: 'platform_operator' in the AgentStack monorepo only — see docs/INTEGRATOR_SCOPE.md.

🔧 API Reference

Core Services

Auth Service

// Предпочитайте sdk.platform.auth (sdk.auth — тот же модуль)consttokens=awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password',project_id: 1,});constnewTokens=awaitsdk.platform.auth.refresh(tokens.refresh_token);constprofile=awaitsdk.platform.auth.getProfile();

Projects Service

// REST (preferred for apps and AI agents)constprojects=awaitsdk.platform.api.getProjects();constproject=awaitsdk.platform.api.getProject(projectId);// 8DNA project row (advanced)constrow=awaitsdk.platform.dna.get('data_projects_8dna',{id: projectId,project_id: 0,});

Payments Service

// Создание платежаconstpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB',description: 'Test payment'});// Получение статусаconststatus=awaitsdk.payments.getPaymentStatus(payment.id);// История платежейconsttransactions=awaitsdk.payments.getTransactions({limit: 20,offset: 0});

Platform operator only (not in npm integrator docs)

Ecosystem admin (sdk.admin, /api/admin/*) is not available to tenant apps. Default SDKConfig.sdkAudience is integrator. AgentStack monorepo ops shells use sdkAudience: 'platform_operator'. Details: docs/INTEGRATOR_SCOPE.md.

AgentDocs - Документация и справка

// Получение справки по темеconsthelp=awaitsdk.docs.getHelp('auth');// Поиск по документацииconstresults=awaitsdk.docs.search('payment integration');// Получение примеров кодаconstexamples=awaitsdk.docs.getCodeExamples({language: 'typescript',category: 'payments'});// Получение FAQconstfaq=awaitsdk.docs.getFAQ('payments');

Neural Architecture Integration

Neural Cache

// Кэширование данныхawaitsdk.neural.cache.set('user:123:profile',userProfile,300);constprofile=awaitsdk.neural.cache.get('user:123:profile');// Кэширование с тегамиawaitsdk.neural.cache.setWithTags('project:456',projectData,['projects','active'],600);// Инвалидация кэшаawaitsdk.neural.cache.invalidateByPattern('user:123:*');awaitsdk.neural.cache.invalidateByTag('projects');

Neural Events

awaitsdk.neural.emitEvent('payment_created',{payment_id: '123',amount: 1000,currency: 'RUB',});awaitsdk.neural.emitEvent('payment_created',{payment_id: 'pay_1'});sdk.on('neural:cache:hit',(key)=>console.debug('cache hit',key));

Pattern Analysis

constpatterns=awaitsdk.neural.patterns.analyze('user_behavior',{user_id: 123,project_id: 1,period: '30d',});constpredictions=awaitsdk.neural.patterns.predict('payment_success',{user_id: 123,project_id: 1,input_data: {amount: 1000,currency: 'RUB'},});

🎨 React Hooks

Admin Hooks (только оператор платформы)

Хуки useAdminUsers, useAdminStats, useAdminDashboardне для tenant npm-приложений. Нужен sdkAudience: 'platform_operator' в monorepo AgentStack.

Пример: examples/typescript/operator-admin-usage.ts · docs/INTEGRATOR_SCOPE_ru.md

Core Hooks (интегратор)

import{useAuth,useProjects,usePayments}from'@agentstack/react';functionApp(){const{ user, login, logout }=useAuth();const{ projects, createProject }=useProjects();const{ payments, createPayment }=usePayments();return(<div>{user ? (<div><h1>Welcome, {user.email}!</h1><buttononClick={logout}>Logout</button><h2>Projects</h2>{projects.map(project=>(<divkey={project.id}>{project.name}</div>))}</div>) : (<buttononClick={()=>login('user@example.com','password')}>
Login
</button>)}</div>);}

🔧 Конфигурация

TypeScript/JavaScript

constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'your_api_key',// Neural Architectureneural: {cache: {enabled: true,ttl: 300,maxSize: 1000},events: {enabled: true,bufferSize: 10000}},// Retry configurationretry: {attempts: 3,delay: 1000,backoff: 'exponential'},// Cache configurationcache: {enabled: true,ttl: 300},// Logginglogging: {level: 'info',enabled: true}});

Python

sdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key',
# Neural Architectureneural={
'cache': {
'enabled': True,
'ttl': 300,
'max_size': 1000
},
'events': {
'enabled': True,
'buffer_size': 10000
}
},
# Retry configurationretry={
'attempts': 3,
'delay': 1000,
'backoff': 'exponential'
},
# Cache configurationcache={
'enabled': True,
'ttl': 300
},
# Logginglogging={
'level': 'info',
'enabled': True
}
)

🧪 Тестирование

Unit Tests

import{AgentStackSDK}from'@agentstack/sdk';describe('Integrator SDK',()=>{letsdk: AgentStackSDK;beforeEach(()=>{sdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'test_key',});});it('should list projects via platform.api',async()=>{constprojects=awaitsdk.platform.api.getProjects();expect(Array.isArray(projects)).toBe(true);});it('should not expose admin in module catalog',()=>{constids=sdk.getModuleCatalog().modules.map((m)=>m.id);expect(ids).not.toContain('admin');});});

Integration Tests

describe('SDK Integration',()=>{it('should handle authentication flow',async()=>{consttokens=awaitsdk.platform.auth.login({email: 'test@example.com',password: 'password',project_id: 1,});expect(tokens.access_token).toBeDefined();expect(tokens.refresh_token).toBeDefined();constprofile=awaitsdk.platform.auth.getProfile();expect(profile.email).toBe('test@example.com');});});

📚 Примеры использования

Project dashboard (integrator)

classProjectDashboard{constructor(privatesdk: AgentStackSDK){}asyncgetDashboardData(projectId: number){constproject=awaitthis.sdk.platform.api.getProject(projectId);constcatalog=this.sdk.getModuleCatalog();return{ project, catalog };}}

Neural Cache Usage

// Пример использования Neural CacheclassUserService{privatesdk: AgentStackSDK;constructor(sdk: AgentStackSDK){this.sdk=sdk;}asyncgetMemberProfile(projectId: number,userId: number){constkey=`user:${userId}:profile`;constcached=awaitthis.sdk.neural.cache.get(key);if(cached)returncached;const{ users }=awaitthis.sdk.platform.api.getProjectUsers(projectId,{limit: 100});constmember=users.find((u)=>u.id===userId);if(member)awaitthis.sdk.neural.cache.set(key,member,300);returnmember;}asyncupdateMyProfile(updates: {display_name?: string}){awaitthis.sdk.platform.auth.updateProfileData(updates);awaitthis.sdk.neural.cache.invalidateByPattern('user:*');}}

🔒 Безопасность

  • Не коммитьте API keys; используйте AGENTSTACK_API_KEY / VITE_AGENTSTACK_API_KEY.
  • Tenant-приложения: безsdk.admindocs/INTEGRATOR_SCOPE.md.
  • Ключи проекта — через панель проекта / sdk.platform.api, не устаревший sdk.auth.createApiKey (deprecated).
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: process.env.AGENTSTACK_API_BASE??resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),timeout: 30000,});

📊 Мониторинг и метрики

SDK Metrics

// Получение метрик SDKconstmetrics=awaitsdk.getMetrics();console.log('Requests:',metrics.requests);console.log('Cache Hit Rate:',metrics.cacheHitRate);console.log('Average Latency:',metrics.averageLatency);

Neural Architecture Metrics

// Получение метрик Neural ArchitectureconstneuralMetrics=awaitsdk.neural.getMetrics();console.log('Neural Cache Hit Rate:',neuralMetrics.cache.hitRate);console.log('Neural Events Throughput:',neuralMetrics.events.throughput);console.log('Pattern Analysis Accuracy:',neuralMetrics.patterns.accuracy);

Production API base

Production REST base is https://agentstack.tech/api. Prefer the helper (Node, scripts, examples):

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});
EnvironmentConfiguration
Production (default)Omit AGENTSTACK_API_BASEhttps://agentstack.tech/api
Local CoreAGENTSTACK_API_BASE=http://localhost:8000/api
Vite SPAVITE_API_BASE_URL=https://agentstack.tech/api (no /api suffix in some setups — HTTPClient normalizes)
# Node / CI
AGENTSTACK_API_BASE=https://agentstack.tech/api
AGENTSTACK_API_KEY=your_api_key

The SDK is a client library — deploy your app as you normally would (static host, serverless, container). No separate “SDK Docker image” is required.

🤝 Contributing

Мы приветствуем вклад в развитие SDK! Пожалуйста, ознакомьтесь с нашими руководящими принципами:

  1. Следуйте TypeScript best practices
  2. Добавляйте тесты для нового функционала
  3. Обновляйте документацию
  4. Используйте Neural Architecture компоненты
  5. Поддерживайте обратную совместимость

📞 Поддержка


npm:@agentstack/sdk · AI entry:AGENTS.md · Integrator scope:docs/INTEGRATOR_SCOPE.md

About

SDK for fast AI build apps

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

AgentStack SDK

npm versionLicense: MIT

Languages:English (canonical) · Русский (this file)

English README (GitHub / npm / AI default):README.en.mdканон API и интеграции.

Этот файл (README.md) — расширенный русский narrative (история, примеры). Не дублируйте устаревшие API: сверяйтесь с EN.

Сверка стиля: docs/DOC_STYLE_GAP_ru.md · Doc hub:docs/DOC_HUB_ru.md

Универсальный TypeScript/JavaScript SDK для экосистемы AgentStack. Модульный API: auth, projects, payments, DNA, protocol, Neural Architecture.

Quick Start (TypeScript/JavaScript):

npm install @agentstack/sdk
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});constprojects=awaitsdk.platform.api.getProjects();constcatalog=sdk.getModuleCatalog();// AI: discover modules, hints, examples

AI entry:AGENTS.md · docs/AI_APPLICATION_FACTORY.md
Integrator scope (no ecosystem admin):docs/INTEGRATOR_SCOPE.md
All integration flows (npm, submodule, monorepo, …):docs/SDK_INTEGRATION_FLOWS.md

Links:Changelog | Contributing


How to add the SDK to your project

FlowWhenInstall
A — npm (default)Production apps, most integratorsnpm install @agentstack/sdk
B — git submodulePin SDK commit in git, vendored CIdocs/SUBMODULE_CONSUMER.mdvendor/agentstack-sdk
D — monorepo siblingYou work inside AgentStack"@agentstack/sdk": "file:../agentstack-unified-sdk/packages/core"
E — local file: / npm linkDeveloping SDK + app togetherPUBLISHING.md
G — PythonPython backendspip install agentstack-sdk

Full decision tree, CI, and env checklist: docs/SDK_INTEGRATION_FLOWS.md.

Submodule in one minute

git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
node vendor/agentstack-sdk/scripts/bootstrap-submodule-consumer.mjs --target . --tag v0.4.13

Then npm install in your app and set projectId — see docs/PROJECT_CONTEXT.md.


Современный, универсальный SDK для экосистемы AgentStack с интеграцией Neural Architecture и Admin SDK. Удобный и понятный API для разработчиков и AI агентов.

🎯 Цели проекта

  • Единообразие: Один SDK для всех API запросов
  • Простота: Интуитивный API для разработчиков
  • Надежность: Встроенные механизмы retry, кэширования, error handling
  • Производительность: Оптимизированные запросы с Neural Cache
  • Масштабируемость: Легкое добавление новых сервисов
  • Мультиязычность: Поддержка TypeScript, Python, и других языков
  • Neural Integration: Полная интеграция с Neural Architecture
  • Project-scoped APIs: RBAC, DNA, economy — без экосистемной /api/admin/* (см. INTEGRATOR_SCOPE)

🏗️ Архитектура

agentstack-sdk/
├── packages/
│ ├── core/ # @agentstack/sdk
│ │ ├── src/
│ │ │ ├── client/ # HTTP и WebSocket клиенты
│ │ │ │ ├── AgentHTTP.ts # HTTP клиент
│ │ │ │ └── AgentWebSocket.ts # WebSocket клиент
│ │ │ ├── modules/ # Модули SDK
│ │ │ │ ├── AgentAuth.ts # Аутентификация
│ │ │ │ ├── AgentAPI.ts # Основные API
│ │ │ │ ├── AgentAdmin.ts # Админ функции
│ │ │ │ ├── AgentNeural.ts # Neural Architecture
│ │ │ │ ├── AgentDocs.ts # Документация
│ │ │ │ ├── AgentPayments.ts # Платежи
│ │ │ │ ├── AgentAnalytics.ts # Аналитика
│ │ │ │ ├── AgentWebhooks.ts # Webhooks
│ │ │ │ └── AgentScheduler.ts # Планировщик
│ │ │ ├── types/ # TypeScript типы
│ │ │ ├── utils/ # Утилиты
│ │ │ │ ├── AgentCache.ts # Кэширование
│ │ │ │ ├── AgentRetry.ts # Retry логика
│ │ │ │ └── AgentLogger.ts # Логирование
│ │ │ └── index.ts
│ │ └── package.json
│ ├── react/ # @agentstack/react
│ │ ├── src/
│ │ │ ├── hooks/ # React хуки
│ │ │ │ ├── useAgentAuth.ts
│ │ │ │ ├── useAgentAdmin.ts
│ │ │ │ ├── useAgentPayments.ts
│ │ │ │ └── useAgentNeural.ts
│ │ │ ├── components/ # React компоненты
│ │ │ │ ├── AgentProvider.tsx
│ │ │ │ ├── AgentAuthGuard.tsx
│ │ │ │ └── AgentAdminPanel.tsx
│ │ │ └── index.ts
│ │ └── package.json
│ └── python/ # agentstack-sdk
│ ├── src/
│ │ ├── client/ # HTTP клиент
│ │ ├── modules/ # Модули Python SDK
│ │ │ ├── agent_auth.py
│ │ │ ├── agent_api.py
│ │ │ ├── agent_admin.py
│ │ │ ├── agent_neural.py
│ │ │ └── agent_payments.py
│ │ └── __init__.py
│ └── setup.py
├── docs/ # Документация
├── examples/ # Примеры использования
├── tests/ # Тесты
└── tools/ # Инструменты разработки

🚀 Ключевые особенности

Core SDK

  • Умный HTTP клиент с автоматическим retry и кэшированием
  • Автоматическая аутентификация с refresh токенами
  • Type-safe API с полной типизацией TypeScript
  • Модульная архитектура с понятными названиями модулей
  • Neural Cache Integration - интеллектуальное кэширование
  • Admin SDK - специализированные методы для администрирования
  • Error Handling с автоматическим retry и fallback
  • Request/Response Interceptors для логирования и мониторинга

🎯 Модули SDK

  • AgentAuth - аутентификация и авторизация
  • AgentAPI - основные API операции
  • AgentAdmin - административные функции
  • AgentNeural - Neural Architecture интеграция
  • AgentDocs - документация и справка
  • AgentPayments - платежная система
  • AgentAnalytics - аналитика и метрики
  • AgentWebhooks - webhook'и
  • AgentScheduler - планировщик задач

Admin SDK (NEW!)

  • User Management - полное управление пользователями
  • System Statistics - метрики и аналитика системы
  • Bulk Operations - массовые операции с пользователями
  • Security Management - управление безопасностью
  • Dashboard Metrics - метрики для дашборда

Neural Architecture Integration

  • Neural Cache - интеллектуальное кэширование с предсказаниями
  • Neural Events - система событий для межмодульной коммуникации
  • Pattern Analysis - анализ паттернов использования
  • Auto Optimization - автоматическая оптимизация запросов

React Integration

  • React Hooks для всех сервисов
  • Context Provider для глобального состояния
  • Admin Components - готовые компоненты для админки
  • Real-time Updates с WebSocket поддержкой

📦 Установка

See docs/SDK_INTEGRATION_FLOWS.md for npm vs submodule vs monorepo vs npm link.

Quick paths:

# A — npm (default)
npm install @agentstack/sdk
npm install @agentstack/react @tanstack/react-query # optional UI# B — git submodule (see SUBMODULE_CONSUMER.md)
git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
# G — Python
pip install agentstack-sdk

🚀 Быстрый старт

TypeScript/JavaScript

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});// Использование модулей SDK (tenant / integrator)awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password'});constprojects=awaitsdk.platform.api.getProjects();constpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB'});// Использование Neural Cacheawaitsdk.neural.cache.set('key','value');constvalue=awaitsdk.neural.cache.get('key');// Использование документацииconsthelp=awaitsdk.docs.getHelp('auth');

Python

fromagentstackimportAgentStackSDKsdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key'
)
# Tenant APIs (no ecosystem admin — see docs/INTEGRATOR_SCOPE.md)projects=awaitsdk.api.get("/projects")
# Использование Neural Cacheawaitsdk.neural.cache.set('key', 'value')
value=awaitsdk.neural.cache.get('key')

React

import{SDKProvider,useSDK}from'@agentstack/react';functionApp(){return(<SDKProviderconfig={{apiBase: 'https://agentstack.tech/api',apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),}}><ProjectList/></SDKProvider>);}functionProjectList(){constsdk=useSDK();// useSDKQuery / sdk.platform.api — see docs/REACT_QUERY_INTEGRATION.md}

Ecosystem admin hooks (useAdminUsers, …) require sdkAudience: 'platform_operator' in the AgentStack monorepo only — see docs/INTEGRATOR_SCOPE.md.

🔧 API Reference

Core Services

Auth Service

// Предпочитайте sdk.platform.auth (sdk.auth — тот же модуль)consttokens=awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password',project_id: 1,});constnewTokens=awaitsdk.platform.auth.refresh(tokens.refresh_token);constprofile=awaitsdk.platform.auth.getProfile();

Projects Service

// REST (preferred for apps and AI agents)constprojects=awaitsdk.platform.api.getProjects();constproject=awaitsdk.platform.api.getProject(projectId);// 8DNA project row (advanced)constrow=awaitsdk.platform.dna.get('data_projects_8dna',{id: projectId,project_id: 0,});

Payments Service

// Создание платежаconstpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB',description: 'Test payment'});// Получение статусаconststatus=awaitsdk.payments.getPaymentStatus(payment.id);// История платежейconsttransactions=awaitsdk.payments.getTransactions({limit: 20,offset: 0});

Platform operator only (not in npm integrator docs)

Ecosystem admin (sdk.admin, /api/admin/*) is not available to tenant apps. Default SDKConfig.sdkAudience is integrator. AgentStack monorepo ops shells use sdkAudience: 'platform_operator'. Details: docs/INTEGRATOR_SCOPE.md.

AgentDocs - Документация и справка

// Получение справки по темеconsthelp=awaitsdk.docs.getHelp('auth');// Поиск по документацииconstresults=awaitsdk.docs.search('payment integration');// Получение примеров кодаconstexamples=awaitsdk.docs.getCodeExamples({language: 'typescript',category: 'payments'});// Получение FAQconstfaq=awaitsdk.docs.getFAQ('payments');

Neural Architecture Integration

Neural Cache

// Кэширование данныхawaitsdk.neural.cache.set('user:123:profile',userProfile,300);constprofile=awaitsdk.neural.cache.get('user:123:profile');// Кэширование с тегамиawaitsdk.neural.cache.setWithTags('project:456',projectData,['projects','active'],600);// Инвалидация кэшаawaitsdk.neural.cache.invalidateByPattern('user:123:*');awaitsdk.neural.cache.invalidateByTag('projects');

Neural Events

awaitsdk.neural.emitEvent('payment_created',{payment_id: '123',amount: 1000,currency: 'RUB',});awaitsdk.neural.emitEvent('payment_created',{payment_id: 'pay_1'});sdk.on('neural:cache:hit',(key)=>console.debug('cache hit',key));

Pattern Analysis

constpatterns=awaitsdk.neural.patterns.analyze('user_behavior',{user_id: 123,project_id: 1,period: '30d',});constpredictions=awaitsdk.neural.patterns.predict('payment_success',{user_id: 123,project_id: 1,input_data: {amount: 1000,currency: 'RUB'},});

🎨 React Hooks

Admin Hooks (только оператор платформы)

Хуки useAdminUsers, useAdminStats, useAdminDashboardне для tenant npm-приложений. Нужен sdkAudience: 'platform_operator' в monorepo AgentStack.

Пример: examples/typescript/operator-admin-usage.ts · docs/INTEGRATOR_SCOPE_ru.md

Core Hooks (интегратор)

import{useAuth,useProjects,usePayments}from'@agentstack/react';functionApp(){const{ user, login, logout }=useAuth();const{ projects, createProject }=useProjects();const{ payments, createPayment }=usePayments();return(<div>{user ? (<div><h1>Welcome, {user.email}!</h1><buttononClick={logout}>Logout</button><h2>Projects</h2>{projects.map(project=>(<divkey={project.id}>{project.name}</div>))}</div>) : (<buttononClick={()=>login('user@example.com','password')}>
Login
</button>)}</div>);}

🔧 Конфигурация

TypeScript/JavaScript

constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'your_api_key',// Neural Architectureneural: {cache: {enabled: true,ttl: 300,maxSize: 1000},events: {enabled: true,bufferSize: 10000}},// Retry configurationretry: {attempts: 3,delay: 1000,backoff: 'exponential'},// Cache configurationcache: {enabled: true,ttl: 300},// Logginglogging: {level: 'info',enabled: true}});

Python

sdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key',
# Neural Architectureneural={
'cache': {
'enabled': True,
'ttl': 300,
'max_size': 1000
},
'events': {
'enabled': True,
'buffer_size': 10000
}
},
# Retry configurationretry={
'attempts': 3,
'delay': 1000,
'backoff': 'exponential'
},
# Cache configurationcache={
'enabled': True,
'ttl': 300
},
# Logginglogging={
'level': 'info',
'enabled': True
}
)

🧪 Тестирование

Unit Tests

import{AgentStackSDK}from'@agentstack/sdk';describe('Integrator SDK',()=>{letsdk: AgentStackSDK;beforeEach(()=>{sdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'test_key',});});it('should list projects via platform.api',async()=>{constprojects=awaitsdk.platform.api.getProjects();expect(Array.isArray(projects)).toBe(true);});it('should not expose admin in module catalog',()=>{constids=sdk.getModuleCatalog().modules.map((m)=>m.id);expect(ids).not.toContain('admin');});});

Integration Tests

describe('SDK Integration',()=>{it('should handle authentication flow',async()=>{consttokens=awaitsdk.platform.auth.login({email: 'test@example.com',password: 'password',project_id: 1,});expect(tokens.access_token).toBeDefined();expect(tokens.refresh_token).toBeDefined();constprofile=awaitsdk.platform.auth.getProfile();expect(profile.email).toBe('test@example.com');});});

📚 Примеры использования

Project dashboard (integrator)

classProjectDashboard{constructor(privatesdk: AgentStackSDK){}asyncgetDashboardData(projectId: number){constproject=awaitthis.sdk.platform.api.getProject(projectId);constcatalog=this.sdk.getModuleCatalog();return{ project, catalog };}}

Neural Cache Usage

// Пример использования Neural CacheclassUserService{privatesdk: AgentStackSDK;constructor(sdk: AgentStackSDK){this.sdk=sdk;}asyncgetMemberProfile(projectId: number,userId: number){constkey=`user:${userId}:profile`;constcached=awaitthis.sdk.neural.cache.get(key);if(cached)returncached;const{ users }=awaitthis.sdk.platform.api.getProjectUsers(projectId,{limit: 100});constmember=users.find((u)=>u.id===userId);if(member)awaitthis.sdk.neural.cache.set(key,member,300);returnmember;}asyncupdateMyProfile(updates: {display_name?: string}){awaitthis.sdk.platform.auth.updateProfileData(updates);awaitthis.sdk.neural.cache.invalidateByPattern('user:*');}}

🔒 Безопасность

  • Не коммитьте API keys; используйте AGENTSTACK_API_KEY / VITE_AGENTSTACK_API_KEY.
  • Tenant-приложения: безsdk.admindocs/INTEGRATOR_SCOPE.md.
  • Ключи проекта — через панель проекта / sdk.platform.api, не устаревший sdk.auth.createApiKey (deprecated).
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: process.env.AGENTSTACK_API_BASE??resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),timeout: 30000,});

📊 Мониторинг и метрики

SDK Metrics

// Получение метрик SDKconstmetrics=awaitsdk.getMetrics();console.log('Requests:',metrics.requests);console.log('Cache Hit Rate:',metrics.cacheHitRate);console.log('Average Latency:',metrics.averageLatency);

Neural Architecture Metrics

// Получение метрик Neural ArchitectureconstneuralMetrics=awaitsdk.neural.getMetrics();console.log('Neural Cache Hit Rate:',neuralMetrics.cache.hitRate);console.log('Neural Events Throughput:',neuralMetrics.events.throughput);console.log('Pattern Analysis Accuracy:',neuralMetrics.patterns.accuracy);

Production API base

Production REST base is https://agentstack.tech/api. Prefer the helper (Node, scripts, examples):

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});
EnvironmentConfiguration
Production (default)Omit AGENTSTACK_API_BASEhttps://agentstack.tech/api
Local CoreAGENTSTACK_API_BASE=http://localhost:8000/api
Vite SPAVITE_API_BASE_URL=https://agentstack.tech/api (no /api suffix in some setups — HTTPClient normalizes)
# Node / CI
AGENTSTACK_API_BASE=https://agentstack.tech/api
AGENTSTACK_API_KEY=your_api_key

The SDK is a client library — deploy your app as you normally would (static host, serverless, container). No separate “SDK Docker image” is required.

🤝 Contributing

Мы приветствуем вклад в развитие SDK! Пожалуйста, ознакомьтесь с нашими руководящими принципами:

  1. Следуйте TypeScript best practices
  2. Добавляйте тесты для нового функционала
  3. Обновляйте документацию
  4. Используйте Neural Architecture компоненты
  5. Поддерживайте обратную совместимость

📞 Поддержка


npm:@agentstack/sdk · AI entry:AGENTS.md · Integrator scope:docs/INTEGRATOR_SCOPE.md

About

SDK for fast AI build apps

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

AgentStack SDK

npm versionLicense: MIT

Languages:English (canonical) · Русский (this file)

English README (GitHub / npm / AI default):README.en.mdканон API и интеграции.

Этот файл (README.md) — расширенный русский narrative (история, примеры). Не дублируйте устаревшие API: сверяйтесь с EN.

Сверка стиля: docs/DOC_STYLE_GAP_ru.md · Doc hub:docs/DOC_HUB_ru.md

Универсальный TypeScript/JavaScript SDK для экосистемы AgentStack. Модульный API: auth, projects, payments, DNA, protocol, Neural Architecture.

Quick Start (TypeScript/JavaScript):

npm install @agentstack/sdk
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});constprojects=awaitsdk.platform.api.getProjects();constcatalog=sdk.getModuleCatalog();// AI: discover modules, hints, examples

AI entry:AGENTS.md · docs/AI_APPLICATION_FACTORY.md
Integrator scope (no ecosystem admin):docs/INTEGRATOR_SCOPE.md
All integration flows (npm, submodule, monorepo, …):docs/SDK_INTEGRATION_FLOWS.md

Links:Changelog | Contributing


How to add the SDK to your project

FlowWhenInstall
A — npm (default)Production apps, most integratorsnpm install @agentstack/sdk
B — git submodulePin SDK commit in git, vendored CIdocs/SUBMODULE_CONSUMER.mdvendor/agentstack-sdk
D — monorepo siblingYou work inside AgentStack"@agentstack/sdk": "file:../agentstack-unified-sdk/packages/core"
E — local file: / npm linkDeveloping SDK + app togetherPUBLISHING.md
G — PythonPython backendspip install agentstack-sdk

Full decision tree, CI, and env checklist: docs/SDK_INTEGRATION_FLOWS.md.

Submodule in one minute

git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
node vendor/agentstack-sdk/scripts/bootstrap-submodule-consumer.mjs --target . --tag v0.4.13

Then npm install in your app and set projectId — see docs/PROJECT_CONTEXT.md.


Современный, универсальный SDK для экосистемы AgentStack с интеграцией Neural Architecture и Admin SDK. Удобный и понятный API для разработчиков и AI агентов.

🎯 Цели проекта

  • Единообразие: Один SDK для всех API запросов
  • Простота: Интуитивный API для разработчиков
  • Надежность: Встроенные механизмы retry, кэширования, error handling
  • Производительность: Оптимизированные запросы с Neural Cache
  • Масштабируемость: Легкое добавление новых сервисов
  • Мультиязычность: Поддержка TypeScript, Python, и других языков
  • Neural Integration: Полная интеграция с Neural Architecture
  • Project-scoped APIs: RBAC, DNA, economy — без экосистемной /api/admin/* (см. INTEGRATOR_SCOPE)

🏗️ Архитектура

agentstack-sdk/
├── packages/
│ ├── core/ # @agentstack/sdk
│ │ ├── src/
│ │ │ ├── client/ # HTTP и WebSocket клиенты
│ │ │ │ ├── AgentHTTP.ts # HTTP клиент
│ │ │ │ └── AgentWebSocket.ts # WebSocket клиент
│ │ │ ├── modules/ # Модули SDK
│ │ │ │ ├── AgentAuth.ts # Аутентификация
│ │ │ │ ├── AgentAPI.ts # Основные API
│ │ │ │ ├── AgentAdmin.ts # Админ функции
│ │ │ │ ├── AgentNeural.ts # Neural Architecture
│ │ │ │ ├── AgentDocs.ts # Документация
│ │ │ │ ├── AgentPayments.ts # Платежи
│ │ │ │ ├── AgentAnalytics.ts # Аналитика
│ │ │ │ ├── AgentWebhooks.ts # Webhooks
│ │ │ │ └── AgentScheduler.ts # Планировщик
│ │ │ ├── types/ # TypeScript типы
│ │ │ ├── utils/ # Утилиты
│ │ │ │ ├── AgentCache.ts # Кэширование
│ │ │ │ ├── AgentRetry.ts # Retry логика
│ │ │ │ └── AgentLogger.ts # Логирование
│ │ │ └── index.ts
│ │ └── package.json
│ ├── react/ # @agentstack/react
│ │ ├── src/
│ │ │ ├── hooks/ # React хуки
│ │ │ │ ├── useAgentAuth.ts
│ │ │ │ ├── useAgentAdmin.ts
│ │ │ │ ├── useAgentPayments.ts
│ │ │ │ └── useAgentNeural.ts
│ │ │ ├── components/ # React компоненты
│ │ │ │ ├── AgentProvider.tsx
│ │ │ │ ├── AgentAuthGuard.tsx
│ │ │ │ └── AgentAdminPanel.tsx
│ │ │ └── index.ts
│ │ └── package.json
│ └── python/ # agentstack-sdk
│ ├── src/
│ │ ├── client/ # HTTP клиент
│ │ ├── modules/ # Модули Python SDK
│ │ │ ├── agent_auth.py
│ │ │ ├── agent_api.py
│ │ │ ├── agent_admin.py
│ │ │ ├── agent_neural.py
│ │ │ └── agent_payments.py
│ │ └── __init__.py
│ └── setup.py
├── docs/ # Документация
├── examples/ # Примеры использования
├── tests/ # Тесты
└── tools/ # Инструменты разработки

🚀 Ключевые особенности

Core SDK

  • Умный HTTP клиент с автоматическим retry и кэшированием
  • Автоматическая аутентификация с refresh токенами
  • Type-safe API с полной типизацией TypeScript
  • Модульная архитектура с понятными названиями модулей
  • Neural Cache Integration - интеллектуальное кэширование
  • Admin SDK - специализированные методы для администрирования
  • Error Handling с автоматическим retry и fallback
  • Request/Response Interceptors для логирования и мониторинга

🎯 Модули SDK

  • AgentAuth - аутентификация и авторизация
  • AgentAPI - основные API операции
  • AgentAdmin - административные функции
  • AgentNeural - Neural Architecture интеграция
  • AgentDocs - документация и справка
  • AgentPayments - платежная система
  • AgentAnalytics - аналитика и метрики
  • AgentWebhooks - webhook'и
  • AgentScheduler - планировщик задач

Admin SDK (NEW!)

  • User Management - полное управление пользователями
  • System Statistics - метрики и аналитика системы
  • Bulk Operations - массовые операции с пользователями
  • Security Management - управление безопасностью
  • Dashboard Metrics - метрики для дашборда

Neural Architecture Integration

  • Neural Cache - интеллектуальное кэширование с предсказаниями
  • Neural Events - система событий для межмодульной коммуникации
  • Pattern Analysis - анализ паттернов использования
  • Auto Optimization - автоматическая оптимизация запросов

React Integration

  • React Hooks для всех сервисов
  • Context Provider для глобального состояния
  • Admin Components - готовые компоненты для админки
  • Real-time Updates с WebSocket поддержкой

📦 Установка

See docs/SDK_INTEGRATION_FLOWS.md for npm vs submodule vs monorepo vs npm link.

Quick paths:

# A — npm (default)
npm install @agentstack/sdk
npm install @agentstack/react @tanstack/react-query # optional UI# B — git submodule (see SUBMODULE_CONSUMER.md)
git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
# G — Python
pip install agentstack-sdk

🚀 Быстрый старт

TypeScript/JavaScript

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});// Использование модулей SDK (tenant / integrator)awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password'});constprojects=awaitsdk.platform.api.getProjects();constpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB'});// Использование Neural Cacheawaitsdk.neural.cache.set('key','value');constvalue=awaitsdk.neural.cache.get('key');// Использование документацииconsthelp=awaitsdk.docs.getHelp('auth');

Python

fromagentstackimportAgentStackSDKsdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key'
)
# Tenant APIs (no ecosystem admin — see docs/INTEGRATOR_SCOPE.md)projects=awaitsdk.api.get("/projects")
# Использование Neural Cacheawaitsdk.neural.cache.set('key', 'value')
value=awaitsdk.neural.cache.get('key')

React

import{SDKProvider,useSDK}from'@agentstack/react';functionApp(){return(<SDKProviderconfig={{apiBase: 'https://agentstack.tech/api',apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),}}><ProjectList/></SDKProvider>);}functionProjectList(){constsdk=useSDK();// useSDKQuery / sdk.platform.api — see docs/REACT_QUERY_INTEGRATION.md}

Ecosystem admin hooks (useAdminUsers, …) require sdkAudience: 'platform_operator' in the AgentStack monorepo only — see docs/INTEGRATOR_SCOPE.md.

🔧 API Reference

Core Services

Auth Service

// Предпочитайте sdk.platform.auth (sdk.auth — тот же модуль)consttokens=awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password',project_id: 1,});constnewTokens=awaitsdk.platform.auth.refresh(tokens.refresh_token);constprofile=awaitsdk.platform.auth.getProfile();

Projects Service

// REST (preferred for apps and AI agents)constprojects=awaitsdk.platform.api.getProjects();constproject=awaitsdk.platform.api.getProject(projectId);// 8DNA project row (advanced)constrow=awaitsdk.platform.dna.get('data_projects_8dna',{id: projectId,project_id: 0,});

Payments Service

// Создание платежаconstpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB',description: 'Test payment'});// Получение статусаconststatus=awaitsdk.payments.getPaymentStatus(payment.id);// История платежейconsttransactions=awaitsdk.payments.getTransactions({limit: 20,offset: 0});

Platform operator only (not in npm integrator docs)

Ecosystem admin (sdk.admin, /api/admin/*) is not available to tenant apps. Default SDKConfig.sdkAudience is integrator. AgentStack monorepo ops shells use sdkAudience: 'platform_operator'. Details: docs/INTEGRATOR_SCOPE.md.

AgentDocs - Документация и справка

// Получение справки по темеconsthelp=awaitsdk.docs.getHelp('auth');// Поиск по документацииconstresults=awaitsdk.docs.search('payment integration');// Получение примеров кодаconstexamples=awaitsdk.docs.getCodeExamples({language: 'typescript',category: 'payments'});// Получение FAQconstfaq=awaitsdk.docs.getFAQ('payments');

Neural Architecture Integration

Neural Cache

// Кэширование данныхawaitsdk.neural.cache.set('user:123:profile',userProfile,300);constprofile=awaitsdk.neural.cache.get('user:123:profile');// Кэширование с тегамиawaitsdk.neural.cache.setWithTags('project:456',projectData,['projects','active'],600);// Инвалидация кэшаawaitsdk.neural.cache.invalidateByPattern('user:123:*');awaitsdk.neural.cache.invalidateByTag('projects');

Neural Events

awaitsdk.neural.emitEvent('payment_created',{payment_id: '123',amount: 1000,currency: 'RUB',});awaitsdk.neural.emitEvent('payment_created',{payment_id: 'pay_1'});sdk.on('neural:cache:hit',(key)=>console.debug('cache hit',key));

Pattern Analysis

constpatterns=awaitsdk.neural.patterns.analyze('user_behavior',{user_id: 123,project_id: 1,period: '30d',});constpredictions=awaitsdk.neural.patterns.predict('payment_success',{user_id: 123,project_id: 1,input_data: {amount: 1000,currency: 'RUB'},});

🎨 React Hooks

Admin Hooks (только оператор платформы)

Хуки useAdminUsers, useAdminStats, useAdminDashboardне для tenant npm-приложений. Нужен sdkAudience: 'platform_operator' в monorepo AgentStack.

Пример: examples/typescript/operator-admin-usage.ts · docs/INTEGRATOR_SCOPE_ru.md

Core Hooks (интегратор)

import{useAuth,useProjects,usePayments}from'@agentstack/react';functionApp(){const{ user, login, logout }=useAuth();const{ projects, createProject }=useProjects();const{ payments, createPayment }=usePayments();return(<div>{user ? (<div><h1>Welcome, {user.email}!</h1><buttononClick={logout}>Logout</button><h2>Projects</h2>{projects.map(project=>(<divkey={project.id}>{project.name}</div>))}</div>) : (<buttononClick={()=>login('user@example.com','password')}>
Login
</button>)}</div>);}

🔧 Конфигурация

TypeScript/JavaScript

constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'your_api_key',// Neural Architectureneural: {cache: {enabled: true,ttl: 300,maxSize: 1000},events: {enabled: true,bufferSize: 10000}},// Retry configurationretry: {attempts: 3,delay: 1000,backoff: 'exponential'},// Cache configurationcache: {enabled: true,ttl: 300},// Logginglogging: {level: 'info',enabled: true}});

Python

sdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key',
# Neural Architectureneural={
'cache': {
'enabled': True,
'ttl': 300,
'max_size': 1000
},
'events': {
'enabled': True,
'buffer_size': 10000
}
},
# Retry configurationretry={
'attempts': 3,
'delay': 1000,
'backoff': 'exponential'
},
# Cache configurationcache={
'enabled': True,
'ttl': 300
},
# Logginglogging={
'level': 'info',
'enabled': True
}
)

🧪 Тестирование

Unit Tests

import{AgentStackSDK}from'@agentstack/sdk';describe('Integrator SDK',()=>{letsdk: AgentStackSDK;beforeEach(()=>{sdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'test_key',});});it('should list projects via platform.api',async()=>{constprojects=awaitsdk.platform.api.getProjects();expect(Array.isArray(projects)).toBe(true);});it('should not expose admin in module catalog',()=>{constids=sdk.getModuleCatalog().modules.map((m)=>m.id);expect(ids).not.toContain('admin');});});

Integration Tests

describe('SDK Integration',()=>{it('should handle authentication flow',async()=>{consttokens=awaitsdk.platform.auth.login({email: 'test@example.com',password: 'password',project_id: 1,});expect(tokens.access_token).toBeDefined();expect(tokens.refresh_token).toBeDefined();constprofile=awaitsdk.platform.auth.getProfile();expect(profile.email).toBe('test@example.com');});});

📚 Примеры использования

Project dashboard (integrator)

classProjectDashboard{constructor(privatesdk: AgentStackSDK){}asyncgetDashboardData(projectId: number){constproject=awaitthis.sdk.platform.api.getProject(projectId);constcatalog=this.sdk.getModuleCatalog();return{ project, catalog };}}

Neural Cache Usage

// Пример использования Neural CacheclassUserService{privatesdk: AgentStackSDK;constructor(sdk: AgentStackSDK){this.sdk=sdk;}asyncgetMemberProfile(projectId: number,userId: number){constkey=`user:${userId}:profile`;constcached=awaitthis.sdk.neural.cache.get(key);if(cached)returncached;const{ users }=awaitthis.sdk.platform.api.getProjectUsers(projectId,{limit: 100});constmember=users.find((u)=>u.id===userId);if(member)awaitthis.sdk.neural.cache.set(key,member,300);returnmember;}asyncupdateMyProfile(updates: {display_name?: string}){awaitthis.sdk.platform.auth.updateProfileData(updates);awaitthis.sdk.neural.cache.invalidateByPattern('user:*');}}

🔒 Безопасность

  • Не коммитьте API keys; используйте AGENTSTACK_API_KEY / VITE_AGENTSTACK_API_KEY.
  • Tenant-приложения: безsdk.admindocs/INTEGRATOR_SCOPE.md.
  • Ключи проекта — через панель проекта / sdk.platform.api, не устаревший sdk.auth.createApiKey (deprecated).
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: process.env.AGENTSTACK_API_BASE??resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),timeout: 30000,});

📊 Мониторинг и метрики

SDK Metrics

// Получение метрик SDKconstmetrics=awaitsdk.getMetrics();console.log('Requests:',metrics.requests);console.log('Cache Hit Rate:',metrics.cacheHitRate);console.log('Average Latency:',metrics.averageLatency);

Neural Architecture Metrics

// Получение метрик Neural ArchitectureconstneuralMetrics=awaitsdk.neural.getMetrics();console.log('Neural Cache Hit Rate:',neuralMetrics.cache.hitRate);console.log('Neural Events Throughput:',neuralMetrics.events.throughput);console.log('Pattern Analysis Accuracy:',neuralMetrics.patterns.accuracy);

Production API base

Production REST base is https://agentstack.tech/api. Prefer the helper (Node, scripts, examples):

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});
EnvironmentConfiguration
Production (default)Omit AGENTSTACK_API_BASEhttps://agentstack.tech/api
Local CoreAGENTSTACK_API_BASE=http://localhost:8000/api
Vite SPAVITE_API_BASE_URL=https://agentstack.tech/api (no /api suffix in some setups — HTTPClient normalizes)
# Node / CI
AGENTSTACK_API_BASE=https://agentstack.tech/api
AGENTSTACK_API_KEY=your_api_key

The SDK is a client library — deploy your app as you normally would (static host, serverless, container). No separate “SDK Docker image” is required.

🤝 Contributing

Мы приветствуем вклад в развитие SDK! Пожалуйста, ознакомьтесь с нашими руководящими принципами:

  1. Следуйте TypeScript best practices
  2. Добавляйте тесты для нового функционала
  3. Обновляйте документацию
  4. Используйте Neural Architecture компоненты
  5. Поддерживайте обратную совместимость

📞 Поддержка


npm:@agentstack/sdk · AI entry:AGENTS.md · Integrator scope:docs/INTEGRATOR_SCOPE.md

About

SDK for fast AI build apps

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

AgentStack SDK

npm versionLicense: MIT

Languages:English (canonical) · Русский (this file)

English README (GitHub / npm / AI default):README.en.mdканон API и интеграции.

Этот файл (README.md) — расширенный русский narrative (история, примеры). Не дублируйте устаревшие API: сверяйтесь с EN.

Сверка стиля: docs/DOC_STYLE_GAP_ru.md · Doc hub:docs/DOC_HUB_ru.md

Универсальный TypeScript/JavaScript SDK для экосистемы AgentStack. Модульный API: auth, projects, payments, DNA, protocol, Neural Architecture.

Quick Start (TypeScript/JavaScript):

npm install @agentstack/sdk
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});constprojects=awaitsdk.platform.api.getProjects();constcatalog=sdk.getModuleCatalog();// AI: discover modules, hints, examples

AI entry:AGENTS.md · docs/AI_APPLICATION_FACTORY.md
Integrator scope (no ecosystem admin):docs/INTEGRATOR_SCOPE.md
All integration flows (npm, submodule, monorepo, …):docs/SDK_INTEGRATION_FLOWS.md

Links:Changelog | Contributing


How to add the SDK to your project

FlowWhenInstall
A — npm (default)Production apps, most integratorsnpm install @agentstack/sdk
B — git submodulePin SDK commit in git, vendored CIdocs/SUBMODULE_CONSUMER.mdvendor/agentstack-sdk
D — monorepo siblingYou work inside AgentStack"@agentstack/sdk": "file:../agentstack-unified-sdk/packages/core"
E — local file: / npm linkDeveloping SDK + app togetherPUBLISHING.md
G — PythonPython backendspip install agentstack-sdk

Full decision tree, CI, and env checklist: docs/SDK_INTEGRATION_FLOWS.md.

Submodule in one minute

git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
node vendor/agentstack-sdk/scripts/bootstrap-submodule-consumer.mjs --target . --tag v0.4.13

Then npm install in your app and set projectId — see docs/PROJECT_CONTEXT.md.


Современный, универсальный SDK для экосистемы AgentStack с интеграцией Neural Architecture и Admin SDK. Удобный и понятный API для разработчиков и AI агентов.

🎯 Цели проекта

  • Единообразие: Один SDK для всех API запросов
  • Простота: Интуитивный API для разработчиков
  • Надежность: Встроенные механизмы retry, кэширования, error handling
  • Производительность: Оптимизированные запросы с Neural Cache
  • Масштабируемость: Легкое добавление новых сервисов
  • Мультиязычность: Поддержка TypeScript, Python, и других языков
  • Neural Integration: Полная интеграция с Neural Architecture
  • Project-scoped APIs: RBAC, DNA, economy — без экосистемной /api/admin/* (см. INTEGRATOR_SCOPE)

🏗️ Архитектура

agentstack-sdk/
├── packages/
│ ├── core/ # @agentstack/sdk
│ │ ├── src/
│ │ │ ├── client/ # HTTP и WebSocket клиенты
│ │ │ │ ├── AgentHTTP.ts # HTTP клиент
│ │ │ │ └── AgentWebSocket.ts # WebSocket клиент
│ │ │ ├── modules/ # Модули SDK
│ │ │ │ ├── AgentAuth.ts # Аутентификация
│ │ │ │ ├── AgentAPI.ts # Основные API
│ │ │ │ ├── AgentAdmin.ts # Админ функции
│ │ │ │ ├── AgentNeural.ts # Neural Architecture
│ │ │ │ ├── AgentDocs.ts # Документация
│ │ │ │ ├── AgentPayments.ts # Платежи
│ │ │ │ ├── AgentAnalytics.ts # Аналитика
│ │ │ │ ├── AgentWebhooks.ts # Webhooks
│ │ │ │ └── AgentScheduler.ts # Планировщик
│ │ │ ├── types/ # TypeScript типы
│ │ │ ├── utils/ # Утилиты
│ │ │ │ ├── AgentCache.ts # Кэширование
│ │ │ │ ├── AgentRetry.ts # Retry логика
│ │ │ │ └── AgentLogger.ts # Логирование
│ │ │ └── index.ts
│ │ └── package.json
│ ├── react/ # @agentstack/react
│ │ ├── src/
│ │ │ ├── hooks/ # React хуки
│ │ │ │ ├── useAgentAuth.ts
│ │ │ │ ├── useAgentAdmin.ts
│ │ │ │ ├── useAgentPayments.ts
│ │ │ │ └── useAgentNeural.ts
│ │ │ ├── components/ # React компоненты
│ │ │ │ ├── AgentProvider.tsx
│ │ │ │ ├── AgentAuthGuard.tsx
│ │ │ │ └── AgentAdminPanel.tsx
│ │ │ └── index.ts
│ │ └── package.json
│ └── python/ # agentstack-sdk
│ ├── src/
│ │ ├── client/ # HTTP клиент
│ │ ├── modules/ # Модули Python SDK
│ │ │ ├── agent_auth.py
│ │ │ ├── agent_api.py
│ │ │ ├── agent_admin.py
│ │ │ ├── agent_neural.py
│ │ │ └── agent_payments.py
│ │ └── __init__.py
│ └── setup.py
├── docs/ # Документация
├── examples/ # Примеры использования
├── tests/ # Тесты
└── tools/ # Инструменты разработки

🚀 Ключевые особенности

Core SDK

  • Умный HTTP клиент с автоматическим retry и кэшированием
  • Автоматическая аутентификация с refresh токенами
  • Type-safe API с полной типизацией TypeScript
  • Модульная архитектура с понятными названиями модулей
  • Neural Cache Integration - интеллектуальное кэширование
  • Admin SDK - специализированные методы для администрирования
  • Error Handling с автоматическим retry и fallback
  • Request/Response Interceptors для логирования и мониторинга

🎯 Модули SDK

  • AgentAuth - аутентификация и авторизация
  • AgentAPI - основные API операции
  • AgentAdmin - административные функции
  • AgentNeural - Neural Architecture интеграция
  • AgentDocs - документация и справка
  • AgentPayments - платежная система
  • AgentAnalytics - аналитика и метрики
  • AgentWebhooks - webhook'и
  • AgentScheduler - планировщик задач

Admin SDK (NEW!)

  • User Management - полное управление пользователями
  • System Statistics - метрики и аналитика системы
  • Bulk Operations - массовые операции с пользователями
  • Security Management - управление безопасностью
  • Dashboard Metrics - метрики для дашборда

Neural Architecture Integration

  • Neural Cache - интеллектуальное кэширование с предсказаниями
  • Neural Events - система событий для межмодульной коммуникации
  • Pattern Analysis - анализ паттернов использования
  • Auto Optimization - автоматическая оптимизация запросов

React Integration

  • React Hooks для всех сервисов
  • Context Provider для глобального состояния
  • Admin Components - готовые компоненты для админки
  • Real-time Updates с WebSocket поддержкой

📦 Установка

See docs/SDK_INTEGRATION_FLOWS.md for npm vs submodule vs monorepo vs npm link.

Quick paths:

# A — npm (default)
npm install @agentstack/sdk
npm install @agentstack/react @tanstack/react-query # optional UI# B — git submodule (see SUBMODULE_CONSUMER.md)
git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
# G — Python
pip install agentstack-sdk

🚀 Быстрый старт

TypeScript/JavaScript

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});// Использование модулей SDK (tenant / integrator)awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password'});constprojects=awaitsdk.platform.api.getProjects();constpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB'});// Использование Neural Cacheawaitsdk.neural.cache.set('key','value');constvalue=awaitsdk.neural.cache.get('key');// Использование документацииconsthelp=awaitsdk.docs.getHelp('auth');

Python

fromagentstackimportAgentStackSDKsdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key'
)
# Tenant APIs (no ecosystem admin — see docs/INTEGRATOR_SCOPE.md)projects=awaitsdk.api.get("/projects")
# Использование Neural Cacheawaitsdk.neural.cache.set('key', 'value')
value=awaitsdk.neural.cache.get('key')

React

import{SDKProvider,useSDK}from'@agentstack/react';functionApp(){return(<SDKProviderconfig={{apiBase: 'https://agentstack.tech/api',apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),}}><ProjectList/></SDKProvider>);}functionProjectList(){constsdk=useSDK();// useSDKQuery / sdk.platform.api — see docs/REACT_QUERY_INTEGRATION.md}

Ecosystem admin hooks (useAdminUsers, …) require sdkAudience: 'platform_operator' in the AgentStack monorepo only — see docs/INTEGRATOR_SCOPE.md.

🔧 API Reference

Core Services

Auth Service

// Предпочитайте sdk.platform.auth (sdk.auth — тот же модуль)consttokens=awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password',project_id: 1,});constnewTokens=awaitsdk.platform.auth.refresh(tokens.refresh_token);constprofile=awaitsdk.platform.auth.getProfile();

Projects Service

// REST (preferred for apps and AI agents)constprojects=awaitsdk.platform.api.getProjects();constproject=awaitsdk.platform.api.getProject(projectId);// 8DNA project row (advanced)constrow=awaitsdk.platform.dna.get('data_projects_8dna',{id: projectId,project_id: 0,});

Payments Service

// Создание платежаconstpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB',description: 'Test payment'});// Получение статусаconststatus=awaitsdk.payments.getPaymentStatus(payment.id);// История платежейconsttransactions=awaitsdk.payments.getTransactions({limit: 20,offset: 0});

Platform operator only (not in npm integrator docs)

Ecosystem admin (sdk.admin, /api/admin/*) is not available to tenant apps. Default SDKConfig.sdkAudience is integrator. AgentStack monorepo ops shells use sdkAudience: 'platform_operator'. Details: docs/INTEGRATOR_SCOPE.md.

AgentDocs - Документация и справка

// Получение справки по темеconsthelp=awaitsdk.docs.getHelp('auth');// Поиск по документацииconstresults=awaitsdk.docs.search('payment integration');// Получение примеров кодаconstexamples=awaitsdk.docs.getCodeExamples({language: 'typescript',category: 'payments'});// Получение FAQconstfaq=awaitsdk.docs.getFAQ('payments');

Neural Architecture Integration

Neural Cache

// Кэширование данныхawaitsdk.neural.cache.set('user:123:profile',userProfile,300);constprofile=awaitsdk.neural.cache.get('user:123:profile');// Кэширование с тегамиawaitsdk.neural.cache.setWithTags('project:456',projectData,['projects','active'],600);// Инвалидация кэшаawaitsdk.neural.cache.invalidateByPattern('user:123:*');awaitsdk.neural.cache.invalidateByTag('projects');

Neural Events

awaitsdk.neural.emitEvent('payment_created',{payment_id: '123',amount: 1000,currency: 'RUB',});awaitsdk.neural.emitEvent('payment_created',{payment_id: 'pay_1'});sdk.on('neural:cache:hit',(key)=>console.debug('cache hit',key));

Pattern Analysis

constpatterns=awaitsdk.neural.patterns.analyze('user_behavior',{user_id: 123,project_id: 1,period: '30d',});constpredictions=awaitsdk.neural.patterns.predict('payment_success',{user_id: 123,project_id: 1,input_data: {amount: 1000,currency: 'RUB'},});

🎨 React Hooks

Admin Hooks (только оператор платформы)

Хуки useAdminUsers, useAdminStats, useAdminDashboardне для tenant npm-приложений. Нужен sdkAudience: 'platform_operator' в monorepo AgentStack.

Пример: examples/typescript/operator-admin-usage.ts · docs/INTEGRATOR_SCOPE_ru.md

Core Hooks (интегратор)

import{useAuth,useProjects,usePayments}from'@agentstack/react';functionApp(){const{ user, login, logout }=useAuth();const{ projects, createProject }=useProjects();const{ payments, createPayment }=usePayments();return(<div>{user ? (<div><h1>Welcome, {user.email}!</h1><buttononClick={logout}>Logout</button><h2>Projects</h2>{projects.map(project=>(<divkey={project.id}>{project.name}</div>))}</div>) : (<buttononClick={()=>login('user@example.com','password')}>
Login
</button>)}</div>);}

🔧 Конфигурация

TypeScript/JavaScript

constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'your_api_key',// Neural Architectureneural: {cache: {enabled: true,ttl: 300,maxSize: 1000},events: {enabled: true,bufferSize: 10000}},// Retry configurationretry: {attempts: 3,delay: 1000,backoff: 'exponential'},// Cache configurationcache: {enabled: true,ttl: 300},// Logginglogging: {level: 'info',enabled: true}});

Python

sdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key',
# Neural Architectureneural={
'cache': {
'enabled': True,
'ttl': 300,
'max_size': 1000
},
'events': {
'enabled': True,
'buffer_size': 10000
}
},
# Retry configurationretry={
'attempts': 3,
'delay': 1000,
'backoff': 'exponential'
},
# Cache configurationcache={
'enabled': True,
'ttl': 300
},
# Logginglogging={
'level': 'info',
'enabled': True
}
)

🧪 Тестирование

Unit Tests

import{AgentStackSDK}from'@agentstack/sdk';describe('Integrator SDK',()=>{letsdk: AgentStackSDK;beforeEach(()=>{sdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'test_key',});});it('should list projects via platform.api',async()=>{constprojects=awaitsdk.platform.api.getProjects();expect(Array.isArray(projects)).toBe(true);});it('should not expose admin in module catalog',()=>{constids=sdk.getModuleCatalog().modules.map((m)=>m.id);expect(ids).not.toContain('admin');});});

Integration Tests

describe('SDK Integration',()=>{it('should handle authentication flow',async()=>{consttokens=awaitsdk.platform.auth.login({email: 'test@example.com',password: 'password',project_id: 1,});expect(tokens.access_token).toBeDefined();expect(tokens.refresh_token).toBeDefined();constprofile=awaitsdk.platform.auth.getProfile();expect(profile.email).toBe('test@example.com');});});

📚 Примеры использования

Project dashboard (integrator)

classProjectDashboard{constructor(privatesdk: AgentStackSDK){}asyncgetDashboardData(projectId: number){constproject=awaitthis.sdk.platform.api.getProject(projectId);constcatalog=this.sdk.getModuleCatalog();return{ project, catalog };}}

Neural Cache Usage

// Пример использования Neural CacheclassUserService{privatesdk: AgentStackSDK;constructor(sdk: AgentStackSDK){this.sdk=sdk;}asyncgetMemberProfile(projectId: number,userId: number){constkey=`user:${userId}:profile`;constcached=awaitthis.sdk.neural.cache.get(key);if(cached)returncached;const{ users }=awaitthis.sdk.platform.api.getProjectUsers(projectId,{limit: 100});constmember=users.find((u)=>u.id===userId);if(member)awaitthis.sdk.neural.cache.set(key,member,300);returnmember;}asyncupdateMyProfile(updates: {display_name?: string}){awaitthis.sdk.platform.auth.updateProfileData(updates);awaitthis.sdk.neural.cache.invalidateByPattern('user:*');}}

🔒 Безопасность

  • Не коммитьте API keys; используйте AGENTSTACK_API_KEY / VITE_AGENTSTACK_API_KEY.
  • Tenant-приложения: безsdk.admindocs/INTEGRATOR_SCOPE.md.
  • Ключи проекта — через панель проекта / sdk.platform.api, не устаревший sdk.auth.createApiKey (deprecated).
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: process.env.AGENTSTACK_API_BASE??resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),timeout: 30000,});

📊 Мониторинг и метрики

SDK Metrics

// Получение метрик SDKconstmetrics=awaitsdk.getMetrics();console.log('Requests:',metrics.requests);console.log('Cache Hit Rate:',metrics.cacheHitRate);console.log('Average Latency:',metrics.averageLatency);

Neural Architecture Metrics

// Получение метрик Neural ArchitectureconstneuralMetrics=awaitsdk.neural.getMetrics();console.log('Neural Cache Hit Rate:',neuralMetrics.cache.hitRate);console.log('Neural Events Throughput:',neuralMetrics.events.throughput);console.log('Pattern Analysis Accuracy:',neuralMetrics.patterns.accuracy);

Production API base

Production REST base is https://agentstack.tech/api. Prefer the helper (Node, scripts, examples):

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});
EnvironmentConfiguration
Production (default)Omit AGENTSTACK_API_BASEhttps://agentstack.tech/api
Local CoreAGENTSTACK_API_BASE=http://localhost:8000/api
Vite SPAVITE_API_BASE_URL=https://agentstack.tech/api (no /api suffix in some setups — HTTPClient normalizes)
# Node / CI
AGENTSTACK_API_BASE=https://agentstack.tech/api
AGENTSTACK_API_KEY=your_api_key

The SDK is a client library — deploy your app as you normally would (static host, serverless, container). No separate “SDK Docker image” is required.

🤝 Contributing

Мы приветствуем вклад в развитие SDK! Пожалуйста, ознакомьтесь с нашими руководящими принципами:

  1. Следуйте TypeScript best practices
  2. Добавляйте тесты для нового функционала
  3. Обновляйте документацию
  4. Используйте Neural Architecture компоненты
  5. Поддерживайте обратную совместимость

📞 Поддержка


npm:@agentstack/sdk · AI entry:AGENTS.md · Integrator scope:docs/INTEGRATOR_SCOPE.md

About

SDK for fast AI build apps

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

AgentStack SDK

npm versionLicense: MIT

Languages:English (canonical) · Русский (this file)

English README (GitHub / npm / AI default):README.en.mdканон API и интеграции.

Этот файл (README.md) — расширенный русский narrative (история, примеры). Не дублируйте устаревшие API: сверяйтесь с EN.

Сверка стиля: docs/DOC_STYLE_GAP_ru.md · Doc hub:docs/DOC_HUB_ru.md

Универсальный TypeScript/JavaScript SDK для экосистемы AgentStack. Модульный API: auth, projects, payments, DNA, protocol, Neural Architecture.

Quick Start (TypeScript/JavaScript):

npm install @agentstack/sdk
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});constprojects=awaitsdk.platform.api.getProjects();constcatalog=sdk.getModuleCatalog();// AI: discover modules, hints, examples

AI entry:AGENTS.md · docs/AI_APPLICATION_FACTORY.md
Integrator scope (no ecosystem admin):docs/INTEGRATOR_SCOPE.md
All integration flows (npm, submodule, monorepo, …):docs/SDK_INTEGRATION_FLOWS.md

Links:Changelog | Contributing


How to add the SDK to your project

FlowWhenInstall
A — npm (default)Production apps, most integratorsnpm install @agentstack/sdk
B — git submodulePin SDK commit in git, vendored CIdocs/SUBMODULE_CONSUMER.mdvendor/agentstack-sdk
D — monorepo siblingYou work inside AgentStack"@agentstack/sdk": "file:../agentstack-unified-sdk/packages/core"
E — local file: / npm linkDeveloping SDK + app togetherPUBLISHING.md
G — PythonPython backendspip install agentstack-sdk

Full decision tree, CI, and env checklist: docs/SDK_INTEGRATION_FLOWS.md.

Submodule in one minute

git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
node vendor/agentstack-sdk/scripts/bootstrap-submodule-consumer.mjs --target . --tag v0.4.13

Then npm install in your app and set projectId — see docs/PROJECT_CONTEXT.md.


Современный, универсальный SDK для экосистемы AgentStack с интеграцией Neural Architecture и Admin SDK. Удобный и понятный API для разработчиков и AI агентов.

🎯 Цели проекта

  • Единообразие: Один SDK для всех API запросов
  • Простота: Интуитивный API для разработчиков
  • Надежность: Встроенные механизмы retry, кэширования, error handling
  • Производительность: Оптимизированные запросы с Neural Cache
  • Масштабируемость: Легкое добавление новых сервисов
  • Мультиязычность: Поддержка TypeScript, Python, и других языков
  • Neural Integration: Полная интеграция с Neural Architecture
  • Project-scoped APIs: RBAC, DNA, economy — без экосистемной /api/admin/* (см. INTEGRATOR_SCOPE)

🏗️ Архитектура

agentstack-sdk/
├── packages/
│ ├── core/ # @agentstack/sdk
│ │ ├── src/
│ │ │ ├── client/ # HTTP и WebSocket клиенты
│ │ │ │ ├── AgentHTTP.ts # HTTP клиент
│ │ │ │ └── AgentWebSocket.ts # WebSocket клиент
│ │ │ ├── modules/ # Модули SDK
│ │ │ │ ├── AgentAuth.ts # Аутентификация
│ │ │ │ ├── AgentAPI.ts # Основные API
│ │ │ │ ├── AgentAdmin.ts # Админ функции
│ │ │ │ ├── AgentNeural.ts # Neural Architecture
│ │ │ │ ├── AgentDocs.ts # Документация
│ │ │ │ ├── AgentPayments.ts # Платежи
│ │ │ │ ├── AgentAnalytics.ts # Аналитика
│ │ │ │ ├── AgentWebhooks.ts # Webhooks
│ │ │ │ └── AgentScheduler.ts # Планировщик
│ │ │ ├── types/ # TypeScript типы
│ │ │ ├── utils/ # Утилиты
│ │ │ │ ├── AgentCache.ts # Кэширование
│ │ │ │ ├── AgentRetry.ts # Retry логика
│ │ │ │ └── AgentLogger.ts # Логирование
│ │ │ └── index.ts
│ │ └── package.json
│ ├── react/ # @agentstack/react
│ │ ├── src/
│ │ │ ├── hooks/ # React хуки
│ │ │ │ ├── useAgentAuth.ts
│ │ │ │ ├── useAgentAdmin.ts
│ │ │ │ ├── useAgentPayments.ts
│ │ │ │ └── useAgentNeural.ts
│ │ │ ├── components/ # React компоненты
│ │ │ │ ├── AgentProvider.tsx
│ │ │ │ ├── AgentAuthGuard.tsx
│ │ │ │ └── AgentAdminPanel.tsx
│ │ │ └── index.ts
│ │ └── package.json
│ └── python/ # agentstack-sdk
│ ├── src/
│ │ ├── client/ # HTTP клиент
│ │ ├── modules/ # Модули Python SDK
│ │ │ ├── agent_auth.py
│ │ │ ├── agent_api.py
│ │ │ ├── agent_admin.py
│ │ │ ├── agent_neural.py
│ │ │ └── agent_payments.py
│ │ └── __init__.py
│ └── setup.py
├── docs/ # Документация
├── examples/ # Примеры использования
├── tests/ # Тесты
└── tools/ # Инструменты разработки

🚀 Ключевые особенности

Core SDK

  • Умный HTTP клиент с автоматическим retry и кэшированием
  • Автоматическая аутентификация с refresh токенами
  • Type-safe API с полной типизацией TypeScript
  • Модульная архитектура с понятными названиями модулей
  • Neural Cache Integration - интеллектуальное кэширование
  • Admin SDK - специализированные методы для администрирования
  • Error Handling с автоматическим retry и fallback
  • Request/Response Interceptors для логирования и мониторинга

🎯 Модули SDK

  • AgentAuth - аутентификация и авторизация
  • AgentAPI - основные API операции
  • AgentAdmin - административные функции
  • AgentNeural - Neural Architecture интеграция
  • AgentDocs - документация и справка
  • AgentPayments - платежная система
  • AgentAnalytics - аналитика и метрики
  • AgentWebhooks - webhook'и
  • AgentScheduler - планировщик задач

Admin SDK (NEW!)

  • User Management - полное управление пользователями
  • System Statistics - метрики и аналитика системы
  • Bulk Operations - массовые операции с пользователями
  • Security Management - управление безопасностью
  • Dashboard Metrics - метрики для дашборда

Neural Architecture Integration

  • Neural Cache - интеллектуальное кэширование с предсказаниями
  • Neural Events - система событий для межмодульной коммуникации
  • Pattern Analysis - анализ паттернов использования
  • Auto Optimization - автоматическая оптимизация запросов

React Integration

  • React Hooks для всех сервисов
  • Context Provider для глобального состояния
  • Admin Components - готовые компоненты для админки
  • Real-time Updates с WebSocket поддержкой

📦 Установка

See docs/SDK_INTEGRATION_FLOWS.md for npm vs submodule vs monorepo vs npm link.

Quick paths:

# A — npm (default)
npm install @agentstack/sdk
npm install @agentstack/react @tanstack/react-query # optional UI# B — git submodule (see SUBMODULE_CONSUMER.md)
git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
# G — Python
pip install agentstack-sdk

🚀 Быстрый старт

TypeScript/JavaScript

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});// Использование модулей SDK (tenant / integrator)awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password'});constprojects=awaitsdk.platform.api.getProjects();constpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB'});// Использование Neural Cacheawaitsdk.neural.cache.set('key','value');constvalue=awaitsdk.neural.cache.get('key');// Использование документацииconsthelp=awaitsdk.docs.getHelp('auth');

Python

fromagentstackimportAgentStackSDKsdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key'
)
# Tenant APIs (no ecosystem admin — see docs/INTEGRATOR_SCOPE.md)projects=awaitsdk.api.get("/projects")
# Использование Neural Cacheawaitsdk.neural.cache.set('key', 'value')
value=awaitsdk.neural.cache.get('key')

React

import{SDKProvider,useSDK}from'@agentstack/react';functionApp(){return(<SDKProviderconfig={{apiBase: 'https://agentstack.tech/api',apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),}}><ProjectList/></SDKProvider>);}functionProjectList(){constsdk=useSDK();// useSDKQuery / sdk.platform.api — see docs/REACT_QUERY_INTEGRATION.md}

Ecosystem admin hooks (useAdminUsers, …) require sdkAudience: 'platform_operator' in the AgentStack monorepo only — see docs/INTEGRATOR_SCOPE.md.

🔧 API Reference

Core Services

Auth Service

// Предпочитайте sdk.platform.auth (sdk.auth — тот же модуль)consttokens=awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password',project_id: 1,});constnewTokens=awaitsdk.platform.auth.refresh(tokens.refresh_token);constprofile=awaitsdk.platform.auth.getProfile();

Projects Service

// REST (preferred for apps and AI agents)constprojects=awaitsdk.platform.api.getProjects();constproject=awaitsdk.platform.api.getProject(projectId);// 8DNA project row (advanced)constrow=awaitsdk.platform.dna.get('data_projects_8dna',{id: projectId,project_id: 0,});

Payments Service

// Создание платежаconstpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB',description: 'Test payment'});// Получение статусаconststatus=awaitsdk.payments.getPaymentStatus(payment.id);// История платежейconsttransactions=awaitsdk.payments.getTransactions({limit: 20,offset: 0});

Platform operator only (not in npm integrator docs)

Ecosystem admin (sdk.admin, /api/admin/*) is not available to tenant apps. Default SDKConfig.sdkAudience is integrator. AgentStack monorepo ops shells use sdkAudience: 'platform_operator'. Details: docs/INTEGRATOR_SCOPE.md.

AgentDocs - Документация и справка

// Получение справки по темеconsthelp=awaitsdk.docs.getHelp('auth');// Поиск по документацииconstresults=awaitsdk.docs.search('payment integration');// Получение примеров кодаconstexamples=awaitsdk.docs.getCodeExamples({language: 'typescript',category: 'payments'});// Получение FAQconstfaq=awaitsdk.docs.getFAQ('payments');

Neural Architecture Integration

Neural Cache

// Кэширование данныхawaitsdk.neural.cache.set('user:123:profile',userProfile,300);constprofile=awaitsdk.neural.cache.get('user:123:profile');// Кэширование с тегамиawaitsdk.neural.cache.setWithTags('project:456',projectData,['projects','active'],600);// Инвалидация кэшаawaitsdk.neural.cache.invalidateByPattern('user:123:*');awaitsdk.neural.cache.invalidateByTag('projects');

Neural Events

awaitsdk.neural.emitEvent('payment_created',{payment_id: '123',amount: 1000,currency: 'RUB',});awaitsdk.neural.emitEvent('payment_created',{payment_id: 'pay_1'});sdk.on('neural:cache:hit',(key)=>console.debug('cache hit',key));

Pattern Analysis

constpatterns=awaitsdk.neural.patterns.analyze('user_behavior',{user_id: 123,project_id: 1,period: '30d',});constpredictions=awaitsdk.neural.patterns.predict('payment_success',{user_id: 123,project_id: 1,input_data: {amount: 1000,currency: 'RUB'},});

🎨 React Hooks

Admin Hooks (только оператор платформы)

Хуки useAdminUsers, useAdminStats, useAdminDashboardне для tenant npm-приложений. Нужен sdkAudience: 'platform_operator' в monorepo AgentStack.

Пример: examples/typescript/operator-admin-usage.ts · docs/INTEGRATOR_SCOPE_ru.md

Core Hooks (интегратор)

import{useAuth,useProjects,usePayments}from'@agentstack/react';functionApp(){const{ user, login, logout }=useAuth();const{ projects, createProject }=useProjects();const{ payments, createPayment }=usePayments();return(<div>{user ? (<div><h1>Welcome, {user.email}!</h1><buttononClick={logout}>Logout</button><h2>Projects</h2>{projects.map(project=>(<divkey={project.id}>{project.name}</div>))}</div>) : (<buttononClick={()=>login('user@example.com','password')}>
Login
</button>)}</div>);}

🔧 Конфигурация

TypeScript/JavaScript

constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'your_api_key',// Neural Architectureneural: {cache: {enabled: true,ttl: 300,maxSize: 1000},events: {enabled: true,bufferSize: 10000}},// Retry configurationretry: {attempts: 3,delay: 1000,backoff: 'exponential'},// Cache configurationcache: {enabled: true,ttl: 300},// Logginglogging: {level: 'info',enabled: true}});

Python

sdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key',
# Neural Architectureneural={
'cache': {
'enabled': True,
'ttl': 300,
'max_size': 1000
},
'events': {
'enabled': True,
'buffer_size': 10000
}
},
# Retry configurationretry={
'attempts': 3,
'delay': 1000,
'backoff': 'exponential'
},
# Cache configurationcache={
'enabled': True,
'ttl': 300
},
# Logginglogging={
'level': 'info',
'enabled': True
}
)

🧪 Тестирование

Unit Tests

import{AgentStackSDK}from'@agentstack/sdk';describe('Integrator SDK',()=>{letsdk: AgentStackSDK;beforeEach(()=>{sdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'test_key',});});it('should list projects via platform.api',async()=>{constprojects=awaitsdk.platform.api.getProjects();expect(Array.isArray(projects)).toBe(true);});it('should not expose admin in module catalog',()=>{constids=sdk.getModuleCatalog().modules.map((m)=>m.id);expect(ids).not.toContain('admin');});});

Integration Tests

describe('SDK Integration',()=>{it('should handle authentication flow',async()=>{consttokens=awaitsdk.platform.auth.login({email: 'test@example.com',password: 'password',project_id: 1,});expect(tokens.access_token).toBeDefined();expect(tokens.refresh_token).toBeDefined();constprofile=awaitsdk.platform.auth.getProfile();expect(profile.email).toBe('test@example.com');});});

📚 Примеры использования

Project dashboard (integrator)

classProjectDashboard{constructor(privatesdk: AgentStackSDK){}asyncgetDashboardData(projectId: number){constproject=awaitthis.sdk.platform.api.getProject(projectId);constcatalog=this.sdk.getModuleCatalog();return{ project, catalog };}}

Neural Cache Usage

// Пример использования Neural CacheclassUserService{privatesdk: AgentStackSDK;constructor(sdk: AgentStackSDK){this.sdk=sdk;}asyncgetMemberProfile(projectId: number,userId: number){constkey=`user:${userId}:profile`;constcached=awaitthis.sdk.neural.cache.get(key);if(cached)returncached;const{ users }=awaitthis.sdk.platform.api.getProjectUsers(projectId,{limit: 100});constmember=users.find((u)=>u.id===userId);if(member)awaitthis.sdk.neural.cache.set(key,member,300);returnmember;}asyncupdateMyProfile(updates: {display_name?: string}){awaitthis.sdk.platform.auth.updateProfileData(updates);awaitthis.sdk.neural.cache.invalidateByPattern('user:*');}}

🔒 Безопасность

  • Не коммитьте API keys; используйте AGENTSTACK_API_KEY / VITE_AGENTSTACK_API_KEY.
  • Tenant-приложения: безsdk.admindocs/INTEGRATOR_SCOPE.md.
  • Ключи проекта — через панель проекта / sdk.platform.api, не устаревший sdk.auth.createApiKey (deprecated).
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: process.env.AGENTSTACK_API_BASE??resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),timeout: 30000,});

📊 Мониторинг и метрики

SDK Metrics

// Получение метрик SDKconstmetrics=awaitsdk.getMetrics();console.log('Requests:',metrics.requests);console.log('Cache Hit Rate:',metrics.cacheHitRate);console.log('Average Latency:',metrics.averageLatency);

Neural Architecture Metrics

// Получение метрик Neural ArchitectureconstneuralMetrics=awaitsdk.neural.getMetrics();console.log('Neural Cache Hit Rate:',neuralMetrics.cache.hitRate);console.log('Neural Events Throughput:',neuralMetrics.events.throughput);console.log('Pattern Analysis Accuracy:',neuralMetrics.patterns.accuracy);

Production API base

Production REST base is https://agentstack.tech/api. Prefer the helper (Node, scripts, examples):

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});
EnvironmentConfiguration
Production (default)Omit AGENTSTACK_API_BASEhttps://agentstack.tech/api
Local CoreAGENTSTACK_API_BASE=http://localhost:8000/api
Vite SPAVITE_API_BASE_URL=https://agentstack.tech/api (no /api suffix in some setups — HTTPClient normalizes)
# Node / CI
AGENTSTACK_API_BASE=https://agentstack.tech/api
AGENTSTACK_API_KEY=your_api_key

The SDK is a client library — deploy your app as you normally would (static host, serverless, container). No separate “SDK Docker image” is required.

🤝 Contributing

Мы приветствуем вклад в развитие SDK! Пожалуйста, ознакомьтесь с нашими руководящими принципами:

  1. Следуйте TypeScript best practices
  2. Добавляйте тесты для нового функционала
  3. Обновляйте документацию
  4. Используйте Neural Architecture компоненты
  5. Поддерживайте обратную совместимость

📞 Поддержка


npm:@agentstack/sdk · AI entry:AGENTS.md · Integrator scope:docs/INTEGRATOR_SCOPE.md

About

SDK for fast AI build apps

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

AgentStack SDK

npm versionLicense: MIT

Languages:English (canonical) · Русский (this file)

English README (GitHub / npm / AI default):README.en.mdканон API и интеграции.

Этот файл (README.md) — расширенный русский narrative (история, примеры). Не дублируйте устаревшие API: сверяйтесь с EN.

Сверка стиля: docs/DOC_STYLE_GAP_ru.md · Doc hub:docs/DOC_HUB_ru.md

Универсальный TypeScript/JavaScript SDK для экосистемы AgentStack. Модульный API: auth, projects, payments, DNA, protocol, Neural Architecture.

Quick Start (TypeScript/JavaScript):

npm install @agentstack/sdk
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});constprojects=awaitsdk.platform.api.getProjects();constcatalog=sdk.getModuleCatalog();// AI: discover modules, hints, examples

AI entry:AGENTS.md · docs/AI_APPLICATION_FACTORY.md
Integrator scope (no ecosystem admin):docs/INTEGRATOR_SCOPE.md
All integration flows (npm, submodule, monorepo, …):docs/SDK_INTEGRATION_FLOWS.md

Links:Changelog | Contributing


How to add the SDK to your project

FlowWhenInstall
A — npm (default)Production apps, most integratorsnpm install @agentstack/sdk
B — git submodulePin SDK commit in git, vendored CIdocs/SUBMODULE_CONSUMER.mdvendor/agentstack-sdk
D — monorepo siblingYou work inside AgentStack"@agentstack/sdk": "file:../agentstack-unified-sdk/packages/core"
E — local file: / npm linkDeveloping SDK + app togetherPUBLISHING.md
G — PythonPython backendspip install agentstack-sdk

Full decision tree, CI, and env checklist: docs/SDK_INTEGRATION_FLOWS.md.

Submodule in one minute

git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
node vendor/agentstack-sdk/scripts/bootstrap-submodule-consumer.mjs --target . --tag v0.4.13

Then npm install in your app and set projectId — see docs/PROJECT_CONTEXT.md.


Современный, универсальный SDK для экосистемы AgentStack с интеграцией Neural Architecture и Admin SDK. Удобный и понятный API для разработчиков и AI агентов.

🎯 Цели проекта

  • Единообразие: Один SDK для всех API запросов
  • Простота: Интуитивный API для разработчиков
  • Надежность: Встроенные механизмы retry, кэширования, error handling
  • Производительность: Оптимизированные запросы с Neural Cache
  • Масштабируемость: Легкое добавление новых сервисов
  • Мультиязычность: Поддержка TypeScript, Python, и других языков
  • Neural Integration: Полная интеграция с Neural Architecture
  • Project-scoped APIs: RBAC, DNA, economy — без экосистемной /api/admin/* (см. INTEGRATOR_SCOPE)

🏗️ Архитектура

agentstack-sdk/
├── packages/
│ ├── core/ # @agentstack/sdk
│ │ ├── src/
│ │ │ ├── client/ # HTTP и WebSocket клиенты
│ │ │ │ ├── AgentHTTP.ts # HTTP клиент
│ │ │ │ └── AgentWebSocket.ts # WebSocket клиент
│ │ │ ├── modules/ # Модули SDK
│ │ │ │ ├── AgentAuth.ts # Аутентификация
│ │ │ │ ├── AgentAPI.ts # Основные API
│ │ │ │ ├── AgentAdmin.ts # Админ функции
│ │ │ │ ├── AgentNeural.ts # Neural Architecture
│ │ │ │ ├── AgentDocs.ts # Документация
│ │ │ │ ├── AgentPayments.ts # Платежи
│ │ │ │ ├── AgentAnalytics.ts # Аналитика
│ │ │ │ ├── AgentWebhooks.ts # Webhooks
│ │ │ │ └── AgentScheduler.ts # Планировщик
│ │ │ ├── types/ # TypeScript типы
│ │ │ ├── utils/ # Утилиты
│ │ │ │ ├── AgentCache.ts # Кэширование
│ │ │ │ ├── AgentRetry.ts # Retry логика
│ │ │ │ └── AgentLogger.ts # Логирование
│ │ │ └── index.ts
│ │ └── package.json
│ ├── react/ # @agentstack/react
│ │ ├── src/
│ │ │ ├── hooks/ # React хуки
│ │ │ │ ├── useAgentAuth.ts
│ │ │ │ ├── useAgentAdmin.ts
│ │ │ │ ├── useAgentPayments.ts
│ │ │ │ └── useAgentNeural.ts
│ │ │ ├── components/ # React компоненты
│ │ │ │ ├── AgentProvider.tsx
│ │ │ │ ├── AgentAuthGuard.tsx
│ │ │ │ └── AgentAdminPanel.tsx
│ │ │ └── index.ts
│ │ └── package.json
│ └── python/ # agentstack-sdk
│ ├── src/
│ │ ├── client/ # HTTP клиент
│ │ ├── modules/ # Модули Python SDK
│ │ │ ├── agent_auth.py
│ │ │ ├── agent_api.py
│ │ │ ├── agent_admin.py
│ │ │ ├── agent_neural.py
│ │ │ └── agent_payments.py
│ │ └── __init__.py
│ └── setup.py
├── docs/ # Документация
├── examples/ # Примеры использования
├── tests/ # Тесты
└── tools/ # Инструменты разработки

🚀 Ключевые особенности

Core SDK

  • Умный HTTP клиент с автоматическим retry и кэшированием
  • Автоматическая аутентификация с refresh токенами
  • Type-safe API с полной типизацией TypeScript
  • Модульная архитектура с понятными названиями модулей
  • Neural Cache Integration - интеллектуальное кэширование
  • Admin SDK - специализированные методы для администрирования
  • Error Handling с автоматическим retry и fallback
  • Request/Response Interceptors для логирования и мониторинга

🎯 Модули SDK

  • AgentAuth - аутентификация и авторизация
  • AgentAPI - основные API операции
  • AgentAdmin - административные функции
  • AgentNeural - Neural Architecture интеграция
  • AgentDocs - документация и справка
  • AgentPayments - платежная система
  • AgentAnalytics - аналитика и метрики
  • AgentWebhooks - webhook'и
  • AgentScheduler - планировщик задач

Admin SDK (NEW!)

  • User Management - полное управление пользователями
  • System Statistics - метрики и аналитика системы
  • Bulk Operations - массовые операции с пользователями
  • Security Management - управление безопасностью
  • Dashboard Metrics - метрики для дашборда

Neural Architecture Integration

  • Neural Cache - интеллектуальное кэширование с предсказаниями
  • Neural Events - система событий для межмодульной коммуникации
  • Pattern Analysis - анализ паттернов использования
  • Auto Optimization - автоматическая оптимизация запросов

React Integration

  • React Hooks для всех сервисов
  • Context Provider для глобального состояния
  • Admin Components - готовые компоненты для админки
  • Real-time Updates с WebSocket поддержкой

📦 Установка

See docs/SDK_INTEGRATION_FLOWS.md for npm vs submodule vs monorepo vs npm link.

Quick paths:

# A — npm (default)
npm install @agentstack/sdk
npm install @agentstack/react @tanstack/react-query # optional UI# B — git submodule (see SUBMODULE_CONSUMER.md)
git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
# G — Python
pip install agentstack-sdk

🚀 Быстрый старт

TypeScript/JavaScript

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});// Использование модулей SDK (tenant / integrator)awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password'});constprojects=awaitsdk.platform.api.getProjects();constpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB'});// Использование Neural Cacheawaitsdk.neural.cache.set('key','value');constvalue=awaitsdk.neural.cache.get('key');// Использование документацииconsthelp=awaitsdk.docs.getHelp('auth');

Python

fromagentstackimportAgentStackSDKsdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key'
)
# Tenant APIs (no ecosystem admin — see docs/INTEGRATOR_SCOPE.md)projects=awaitsdk.api.get("/projects")
# Использование Neural Cacheawaitsdk.neural.cache.set('key', 'value')
value=awaitsdk.neural.cache.get('key')

React

import{SDKProvider,useSDK}from'@agentstack/react';functionApp(){return(<SDKProviderconfig={{apiBase: 'https://agentstack.tech/api',apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),}}><ProjectList/></SDKProvider>);}functionProjectList(){constsdk=useSDK();// useSDKQuery / sdk.platform.api — see docs/REACT_QUERY_INTEGRATION.md}

Ecosystem admin hooks (useAdminUsers, …) require sdkAudience: 'platform_operator' in the AgentStack monorepo only — see docs/INTEGRATOR_SCOPE.md.

🔧 API Reference

Core Services

Auth Service

// Предпочитайте sdk.platform.auth (sdk.auth — тот же модуль)consttokens=awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password',project_id: 1,});constnewTokens=awaitsdk.platform.auth.refresh(tokens.refresh_token);constprofile=awaitsdk.platform.auth.getProfile();

Projects Service

// REST (preferred for apps and AI agents)constprojects=awaitsdk.platform.api.getProjects();constproject=awaitsdk.platform.api.getProject(projectId);// 8DNA project row (advanced)constrow=awaitsdk.platform.dna.get('data_projects_8dna',{id: projectId,project_id: 0,});

Payments Service

// Создание платежаconstpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB',description: 'Test payment'});// Получение статусаconststatus=awaitsdk.payments.getPaymentStatus(payment.id);// История платежейconsttransactions=awaitsdk.payments.getTransactions({limit: 20,offset: 0});

Platform operator only (not in npm integrator docs)

Ecosystem admin (sdk.admin, /api/admin/*) is not available to tenant apps. Default SDKConfig.sdkAudience is integrator. AgentStack monorepo ops shells use sdkAudience: 'platform_operator'. Details: docs/INTEGRATOR_SCOPE.md.

AgentDocs - Документация и справка

// Получение справки по темеconsthelp=awaitsdk.docs.getHelp('auth');// Поиск по документацииconstresults=awaitsdk.docs.search('payment integration');// Получение примеров кодаconstexamples=awaitsdk.docs.getCodeExamples({language: 'typescript',category: 'payments'});// Получение FAQconstfaq=awaitsdk.docs.getFAQ('payments');

Neural Architecture Integration

Neural Cache

// Кэширование данныхawaitsdk.neural.cache.set('user:123:profile',userProfile,300);constprofile=awaitsdk.neural.cache.get('user:123:profile');// Кэширование с тегамиawaitsdk.neural.cache.setWithTags('project:456',projectData,['projects','active'],600);// Инвалидация кэшаawaitsdk.neural.cache.invalidateByPattern('user:123:*');awaitsdk.neural.cache.invalidateByTag('projects');

Neural Events

awaitsdk.neural.emitEvent('payment_created',{payment_id: '123',amount: 1000,currency: 'RUB',});awaitsdk.neural.emitEvent('payment_created',{payment_id: 'pay_1'});sdk.on('neural:cache:hit',(key)=>console.debug('cache hit',key));

Pattern Analysis

constpatterns=awaitsdk.neural.patterns.analyze('user_behavior',{user_id: 123,project_id: 1,period: '30d',});constpredictions=awaitsdk.neural.patterns.predict('payment_success',{user_id: 123,project_id: 1,input_data: {amount: 1000,currency: 'RUB'},});

🎨 React Hooks

Admin Hooks (только оператор платформы)

Хуки useAdminUsers, useAdminStats, useAdminDashboardне для tenant npm-приложений. Нужен sdkAudience: 'platform_operator' в monorepo AgentStack.

Пример: examples/typescript/operator-admin-usage.ts · docs/INTEGRATOR_SCOPE_ru.md

Core Hooks (интегратор)

import{useAuth,useProjects,usePayments}from'@agentstack/react';functionApp(){const{ user, login, logout }=useAuth();const{ projects, createProject }=useProjects();const{ payments, createPayment }=usePayments();return(<div>{user ? (<div><h1>Welcome, {user.email}!</h1><buttononClick={logout}>Logout</button><h2>Projects</h2>{projects.map(project=>(<divkey={project.id}>{project.name}</div>))}</div>) : (<buttononClick={()=>login('user@example.com','password')}>
Login
</button>)}</div>);}

🔧 Конфигурация

TypeScript/JavaScript

constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'your_api_key',// Neural Architectureneural: {cache: {enabled: true,ttl: 300,maxSize: 1000},events: {enabled: true,bufferSize: 10000}},// Retry configurationretry: {attempts: 3,delay: 1000,backoff: 'exponential'},// Cache configurationcache: {enabled: true,ttl: 300},// Logginglogging: {level: 'info',enabled: true}});

Python

sdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key',
# Neural Architectureneural={
'cache': {
'enabled': True,
'ttl': 300,
'max_size': 1000
},
'events': {
'enabled': True,
'buffer_size': 10000
}
},
# Retry configurationretry={
'attempts': 3,
'delay': 1000,
'backoff': 'exponential'
},
# Cache configurationcache={
'enabled': True,
'ttl': 300
},
# Logginglogging={
'level': 'info',
'enabled': True
}
)

🧪 Тестирование

Unit Tests

import{AgentStackSDK}from'@agentstack/sdk';describe('Integrator SDK',()=>{letsdk: AgentStackSDK;beforeEach(()=>{sdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'test_key',});});it('should list projects via platform.api',async()=>{constprojects=awaitsdk.platform.api.getProjects();expect(Array.isArray(projects)).toBe(true);});it('should not expose admin in module catalog',()=>{constids=sdk.getModuleCatalog().modules.map((m)=>m.id);expect(ids).not.toContain('admin');});});

Integration Tests

describe('SDK Integration',()=>{it('should handle authentication flow',async()=>{consttokens=awaitsdk.platform.auth.login({email: 'test@example.com',password: 'password',project_id: 1,});expect(tokens.access_token).toBeDefined();expect(tokens.refresh_token).toBeDefined();constprofile=awaitsdk.platform.auth.getProfile();expect(profile.email).toBe('test@example.com');});});

📚 Примеры использования

Project dashboard (integrator)

classProjectDashboard{constructor(privatesdk: AgentStackSDK){}asyncgetDashboardData(projectId: number){constproject=awaitthis.sdk.platform.api.getProject(projectId);constcatalog=this.sdk.getModuleCatalog();return{ project, catalog };}}

Neural Cache Usage

// Пример использования Neural CacheclassUserService{privatesdk: AgentStackSDK;constructor(sdk: AgentStackSDK){this.sdk=sdk;}asyncgetMemberProfile(projectId: number,userId: number){constkey=`user:${userId}:profile`;constcached=awaitthis.sdk.neural.cache.get(key);if(cached)returncached;const{ users }=awaitthis.sdk.platform.api.getProjectUsers(projectId,{limit: 100});constmember=users.find((u)=>u.id===userId);if(member)awaitthis.sdk.neural.cache.set(key,member,300);returnmember;}asyncupdateMyProfile(updates: {display_name?: string}){awaitthis.sdk.platform.auth.updateProfileData(updates);awaitthis.sdk.neural.cache.invalidateByPattern('user:*');}}

🔒 Безопасность

  • Не коммитьте API keys; используйте AGENTSTACK_API_KEY / VITE_AGENTSTACK_API_KEY.
  • Tenant-приложения: безsdk.admindocs/INTEGRATOR_SCOPE.md.
  • Ключи проекта — через панель проекта / sdk.platform.api, не устаревший sdk.auth.createApiKey (deprecated).
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: process.env.AGENTSTACK_API_BASE??resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),timeout: 30000,});

📊 Мониторинг и метрики

SDK Metrics

// Получение метрик SDKconstmetrics=awaitsdk.getMetrics();console.log('Requests:',metrics.requests);console.log('Cache Hit Rate:',metrics.cacheHitRate);console.log('Average Latency:',metrics.averageLatency);

Neural Architecture Metrics

// Получение метрик Neural ArchitectureconstneuralMetrics=awaitsdk.neural.getMetrics();console.log('Neural Cache Hit Rate:',neuralMetrics.cache.hitRate);console.log('Neural Events Throughput:',neuralMetrics.events.throughput);console.log('Pattern Analysis Accuracy:',neuralMetrics.patterns.accuracy);

Production API base

Production REST base is https://agentstack.tech/api. Prefer the helper (Node, scripts, examples):

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});
EnvironmentConfiguration
Production (default)Omit AGENTSTACK_API_BASEhttps://agentstack.tech/api
Local CoreAGENTSTACK_API_BASE=http://localhost:8000/api
Vite SPAVITE_API_BASE_URL=https://agentstack.tech/api (no /api suffix in some setups — HTTPClient normalizes)
# Node / CI
AGENTSTACK_API_BASE=https://agentstack.tech/api
AGENTSTACK_API_KEY=your_api_key

The SDK is a client library — deploy your app as you normally would (static host, serverless, container). No separate “SDK Docker image” is required.

🤝 Contributing

Мы приветствуем вклад в развитие SDK! Пожалуйста, ознакомьтесь с нашими руководящими принципами:

  1. Следуйте TypeScript best practices
  2. Добавляйте тесты для нового функционала
  3. Обновляйте документацию
  4. Используйте Neural Architecture компоненты
  5. Поддерживайте обратную совместимость

📞 Поддержка


npm:@agentstack/sdk · AI entry:AGENTS.md · Integrator scope:docs/INTEGRATOR_SCOPE.md

About

SDK for fast AI build apps

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

AgentStack SDK

npm versionLicense: MIT

Languages:English (canonical) · Русский (this file)

English README (GitHub / npm / AI default):README.en.mdканон API и интеграции.

Этот файл (README.md) — расширенный русский narrative (история, примеры). Не дублируйте устаревшие API: сверяйтесь с EN.

Сверка стиля: docs/DOC_STYLE_GAP_ru.md · Doc hub:docs/DOC_HUB_ru.md

Универсальный TypeScript/JavaScript SDK для экосистемы AgentStack. Модульный API: auth, projects, payments, DNA, protocol, Neural Architecture.

Quick Start (TypeScript/JavaScript):

npm install @agentstack/sdk
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});constprojects=awaitsdk.platform.api.getProjects();constcatalog=sdk.getModuleCatalog();// AI: discover modules, hints, examples

AI entry:AGENTS.md · docs/AI_APPLICATION_FACTORY.md
Integrator scope (no ecosystem admin):docs/INTEGRATOR_SCOPE.md
All integration flows (npm, submodule, monorepo, …):docs/SDK_INTEGRATION_FLOWS.md

Links:Changelog | Contributing


How to add the SDK to your project

FlowWhenInstall
A — npm (default)Production apps, most integratorsnpm install @agentstack/sdk
B — git submodulePin SDK commit in git, vendored CIdocs/SUBMODULE_CONSUMER.mdvendor/agentstack-sdk
D — monorepo siblingYou work inside AgentStack"@agentstack/sdk": "file:../agentstack-unified-sdk/packages/core"
E — local file: / npm linkDeveloping SDK + app togetherPUBLISHING.md
G — PythonPython backendspip install agentstack-sdk

Full decision tree, CI, and env checklist: docs/SDK_INTEGRATION_FLOWS.md.

Submodule in one minute

git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
node vendor/agentstack-sdk/scripts/bootstrap-submodule-consumer.mjs --target . --tag v0.4.13

Then npm install in your app and set projectId — see docs/PROJECT_CONTEXT.md.


Современный, универсальный SDK для экосистемы AgentStack с интеграцией Neural Architecture и Admin SDK. Удобный и понятный API для разработчиков и AI агентов.

🎯 Цели проекта

  • Единообразие: Один SDK для всех API запросов
  • Простота: Интуитивный API для разработчиков
  • Надежность: Встроенные механизмы retry, кэширования, error handling
  • Производительность: Оптимизированные запросы с Neural Cache
  • Масштабируемость: Легкое добавление новых сервисов
  • Мультиязычность: Поддержка TypeScript, Python, и других языков
  • Neural Integration: Полная интеграция с Neural Architecture
  • Project-scoped APIs: RBAC, DNA, economy — без экосистемной /api/admin/* (см. INTEGRATOR_SCOPE)

🏗️ Архитектура

agentstack-sdk/
├── packages/
│ ├── core/ # @agentstack/sdk
│ │ ├── src/
│ │ │ ├── client/ # HTTP и WebSocket клиенты
│ │ │ │ ├── AgentHTTP.ts # HTTP клиент
│ │ │ │ └── AgentWebSocket.ts # WebSocket клиент
│ │ │ ├── modules/ # Модули SDK
│ │ │ │ ├── AgentAuth.ts # Аутентификация
│ │ │ │ ├── AgentAPI.ts # Основные API
│ │ │ │ ├── AgentAdmin.ts # Админ функции
│ │ │ │ ├── AgentNeural.ts # Neural Architecture
│ │ │ │ ├── AgentDocs.ts # Документация
│ │ │ │ ├── AgentPayments.ts # Платежи
│ │ │ │ ├── AgentAnalytics.ts # Аналитика
│ │ │ │ ├── AgentWebhooks.ts # Webhooks
│ │ │ │ └── AgentScheduler.ts # Планировщик
│ │ │ ├── types/ # TypeScript типы
│ │ │ ├── utils/ # Утилиты
│ │ │ │ ├── AgentCache.ts # Кэширование
│ │ │ │ ├── AgentRetry.ts # Retry логика
│ │ │ │ └── AgentLogger.ts # Логирование
│ │ │ └── index.ts
│ │ └── package.json
│ ├── react/ # @agentstack/react
│ │ ├── src/
│ │ │ ├── hooks/ # React хуки
│ │ │ │ ├── useAgentAuth.ts
│ │ │ │ ├── useAgentAdmin.ts
│ │ │ │ ├── useAgentPayments.ts
│ │ │ │ └── useAgentNeural.ts
│ │ │ ├── components/ # React компоненты
│ │ │ │ ├── AgentProvider.tsx
│ │ │ │ ├── AgentAuthGuard.tsx
│ │ │ │ └── AgentAdminPanel.tsx
│ │ │ └── index.ts
│ │ └── package.json
│ └── python/ # agentstack-sdk
│ ├── src/
│ │ ├── client/ # HTTP клиент
│ │ ├── modules/ # Модули Python SDK
│ │ │ ├── agent_auth.py
│ │ │ ├── agent_api.py
│ │ │ ├── agent_admin.py
│ │ │ ├── agent_neural.py
│ │ │ └── agent_payments.py
│ │ └── __init__.py
│ └── setup.py
├── docs/ # Документация
├── examples/ # Примеры использования
├── tests/ # Тесты
└── tools/ # Инструменты разработки

🚀 Ключевые особенности

Core SDK

  • Умный HTTP клиент с автоматическим retry и кэшированием
  • Автоматическая аутентификация с refresh токенами
  • Type-safe API с полной типизацией TypeScript
  • Модульная архитектура с понятными названиями модулей
  • Neural Cache Integration - интеллектуальное кэширование
  • Admin SDK - специализированные методы для администрирования
  • Error Handling с автоматическим retry и fallback
  • Request/Response Interceptors для логирования и мониторинга

🎯 Модули SDK

  • AgentAuth - аутентификация и авторизация
  • AgentAPI - основные API операции
  • AgentAdmin - административные функции
  • AgentNeural - Neural Architecture интеграция
  • AgentDocs - документация и справка
  • AgentPayments - платежная система
  • AgentAnalytics - аналитика и метрики
  • AgentWebhooks - webhook'и
  • AgentScheduler - планировщик задач

Admin SDK (NEW!)

  • User Management - полное управление пользователями
  • System Statistics - метрики и аналитика системы
  • Bulk Operations - массовые операции с пользователями
  • Security Management - управление безопасностью
  • Dashboard Metrics - метрики для дашборда

Neural Architecture Integration

  • Neural Cache - интеллектуальное кэширование с предсказаниями
  • Neural Events - система событий для межмодульной коммуникации
  • Pattern Analysis - анализ паттернов использования
  • Auto Optimization - автоматическая оптимизация запросов

React Integration

  • React Hooks для всех сервисов
  • Context Provider для глобального состояния
  • Admin Components - готовые компоненты для админки
  • Real-time Updates с WebSocket поддержкой

📦 Установка

See docs/SDK_INTEGRATION_FLOWS.md for npm vs submodule vs monorepo vs npm link.

Quick paths:

# A — npm (default)
npm install @agentstack/sdk
npm install @agentstack/react @tanstack/react-query # optional UI# B — git submodule (see SUBMODULE_CONSUMER.md)
git submodule add https://github.com/agentstacktech/agentstack-sdk.git vendor/agentstack-sdk
# G — Python
pip install agentstack-sdk

🚀 Быстрый старт

TypeScript/JavaScript

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});// Использование модулей SDK (tenant / integrator)awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password'});constprojects=awaitsdk.platform.api.getProjects();constpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB'});// Использование Neural Cacheawaitsdk.neural.cache.set('key','value');constvalue=awaitsdk.neural.cache.get('key');// Использование документацииconsthelp=awaitsdk.docs.getHelp('auth');

Python

fromagentstackimportAgentStackSDKsdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key'
)
# Tenant APIs (no ecosystem admin — see docs/INTEGRATOR_SCOPE.md)projects=awaitsdk.api.get("/projects")
# Использование Neural Cacheawaitsdk.neural.cache.set('key', 'value')
value=awaitsdk.neural.cache.get('key')

React

import{SDKProvider,useSDK}from'@agentstack/react';functionApp(){return(<SDKProviderconfig={{apiBase: 'https://agentstack.tech/api',apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),}}><ProjectList/></SDKProvider>);}functionProjectList(){constsdk=useSDK();// useSDKQuery / sdk.platform.api — see docs/REACT_QUERY_INTEGRATION.md}

Ecosystem admin hooks (useAdminUsers, …) require sdkAudience: 'platform_operator' in the AgentStack monorepo only — see docs/INTEGRATOR_SCOPE.md.

🔧 API Reference

Core Services

Auth Service

// Предпочитайте sdk.platform.auth (sdk.auth — тот же модуль)consttokens=awaitsdk.platform.auth.login({email: 'user@example.com',password: 'password',project_id: 1,});constnewTokens=awaitsdk.platform.auth.refresh(tokens.refresh_token);constprofile=awaitsdk.platform.auth.getProfile();

Projects Service

// REST (preferred for apps and AI agents)constprojects=awaitsdk.platform.api.getProjects();constproject=awaitsdk.platform.api.getProject(projectId);// 8DNA project row (advanced)constrow=awaitsdk.platform.dna.get('data_projects_8dna',{id: projectId,project_id: 0,});

Payments Service

// Создание платежаconstpayment=awaitsdk.payments.createPayment({amount: 1000,currency: 'RUB',description: 'Test payment'});// Получение статусаconststatus=awaitsdk.payments.getPaymentStatus(payment.id);// История платежейconsttransactions=awaitsdk.payments.getTransactions({limit: 20,offset: 0});

Platform operator only (not in npm integrator docs)

Ecosystem admin (sdk.admin, /api/admin/*) is not available to tenant apps. Default SDKConfig.sdkAudience is integrator. AgentStack monorepo ops shells use sdkAudience: 'platform_operator'. Details: docs/INTEGRATOR_SCOPE.md.

AgentDocs - Документация и справка

// Получение справки по темеconsthelp=awaitsdk.docs.getHelp('auth');// Поиск по документацииconstresults=awaitsdk.docs.search('payment integration');// Получение примеров кодаconstexamples=awaitsdk.docs.getCodeExamples({language: 'typescript',category: 'payments'});// Получение FAQconstfaq=awaitsdk.docs.getFAQ('payments');

Neural Architecture Integration

Neural Cache

// Кэширование данныхawaitsdk.neural.cache.set('user:123:profile',userProfile,300);constprofile=awaitsdk.neural.cache.get('user:123:profile');// Кэширование с тегамиawaitsdk.neural.cache.setWithTags('project:456',projectData,['projects','active'],600);// Инвалидация кэшаawaitsdk.neural.cache.invalidateByPattern('user:123:*');awaitsdk.neural.cache.invalidateByTag('projects');

Neural Events

awaitsdk.neural.emitEvent('payment_created',{payment_id: '123',amount: 1000,currency: 'RUB',});awaitsdk.neural.emitEvent('payment_created',{payment_id: 'pay_1'});sdk.on('neural:cache:hit',(key)=>console.debug('cache hit',key));

Pattern Analysis

constpatterns=awaitsdk.neural.patterns.analyze('user_behavior',{user_id: 123,project_id: 1,period: '30d',});constpredictions=awaitsdk.neural.patterns.predict('payment_success',{user_id: 123,project_id: 1,input_data: {amount: 1000,currency: 'RUB'},});

🎨 React Hooks

Admin Hooks (только оператор платформы)

Хуки useAdminUsers, useAdminStats, useAdminDashboardне для tenant npm-приложений. Нужен sdkAudience: 'platform_operator' в monorepo AgentStack.

Пример: examples/typescript/operator-admin-usage.ts · docs/INTEGRATOR_SCOPE_ru.md

Core Hooks (интегратор)

import{useAuth,useProjects,usePayments}from'@agentstack/react';functionApp(){const{ user, login, logout }=useAuth();const{ projects, createProject }=useProjects();const{ payments, createPayment }=usePayments();return(<div>{user ? (<div><h1>Welcome, {user.email}!</h1><buttononClick={logout}>Logout</button><h2>Projects</h2>{projects.map(project=>(<divkey={project.id}>{project.name}</div>))}</div>) : (<buttononClick={()=>login('user@example.com','password')}>
Login
</button>)}</div>);}

🔧 Конфигурация

TypeScript/JavaScript

constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'your_api_key',// Neural Architectureneural: {cache: {enabled: true,ttl: 300,maxSize: 1000},events: {enabled: true,bufferSize: 10000}},// Retry configurationretry: {attempts: 3,delay: 1000,backoff: 'exponential'},// Cache configurationcache: {enabled: true,ttl: 300},// Logginglogging: {level: 'info',enabled: true}});

Python

sdk=AgentStackSDK(
api_base='https://agentstack.tech/api',
api_key='your_api_key',
# Neural Architectureneural={
'cache': {
'enabled': True,
'ttl': 300,
'max_size': 1000
},
'events': {
'enabled': True,
'buffer_size': 10000
}
},
# Retry configurationretry={
'attempts': 3,
'delay': 1000,
'backoff': 'exponential'
},
# Cache configurationcache={
'enabled': True,
'ttl': 300
},
# Logginglogging={
'level': 'info',
'enabled': True
}
)

🧪 Тестирование

Unit Tests

import{AgentStackSDK}from'@agentstack/sdk';describe('Integrator SDK',()=>{letsdk: AgentStackSDK;beforeEach(()=>{sdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: 'test_key',});});it('should list projects via platform.api',async()=>{constprojects=awaitsdk.platform.api.getProjects();expect(Array.isArray(projects)).toBe(true);});it('should not expose admin in module catalog',()=>{constids=sdk.getModuleCatalog().modules.map((m)=>m.id);expect(ids).not.toContain('admin');});});

Integration Tests

describe('SDK Integration',()=>{it('should handle authentication flow',async()=>{consttokens=awaitsdk.platform.auth.login({email: 'test@example.com',password: 'password',project_id: 1,});expect(tokens.access_token).toBeDefined();expect(tokens.refresh_token).toBeDefined();constprofile=awaitsdk.platform.auth.getProfile();expect(profile.email).toBe('test@example.com');});});

📚 Примеры использования

Project dashboard (integrator)

classProjectDashboard{constructor(privatesdk: AgentStackSDK){}asyncgetDashboardData(projectId: number){constproject=awaitthis.sdk.platform.api.getProject(projectId);constcatalog=this.sdk.getModuleCatalog();return{ project, catalog };}}

Neural Cache Usage

// Пример использования Neural CacheclassUserService{privatesdk: AgentStackSDK;constructor(sdk: AgentStackSDK){this.sdk=sdk;}asyncgetMemberProfile(projectId: number,userId: number){constkey=`user:${userId}:profile`;constcached=awaitthis.sdk.neural.cache.get(key);if(cached)returncached;const{ users }=awaitthis.sdk.platform.api.getProjectUsers(projectId,{limit: 100});constmember=users.find((u)=>u.id===userId);if(member)awaitthis.sdk.neural.cache.set(key,member,300);returnmember;}asyncupdateMyProfile(updates: {display_name?: string}){awaitthis.sdk.platform.auth.updateProfileData(updates);awaitthis.sdk.neural.cache.invalidateByPattern('user:*');}}

🔒 Безопасность

  • Не коммитьте API keys; используйте AGENTSTACK_API_KEY / VITE_AGENTSTACK_API_KEY.
  • Tenant-приложения: безsdk.admindocs/INTEGRATOR_SCOPE.md.
  • Ключи проекта — через панель проекта / sdk.platform.api, не устаревший sdk.auth.createApiKey (deprecated).
import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: process.env.AGENTSTACK_API_BASE??resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,projectId: Number(process.env.AGENTSTACK_PROJECT_ID),timeout: 30000,});

📊 Мониторинг и метрики

SDK Metrics

// Получение метрик SDKconstmetrics=awaitsdk.getMetrics();console.log('Requests:',metrics.requests);console.log('Cache Hit Rate:',metrics.cacheHitRate);console.log('Average Latency:',metrics.averageLatency);

Neural Architecture Metrics

// Получение метрик Neural ArchitectureconstneuralMetrics=awaitsdk.neural.getMetrics();console.log('Neural Cache Hit Rate:',neuralMetrics.cache.hitRate);console.log('Neural Events Throughput:',neuralMetrics.events.throughput);console.log('Pattern Analysis Accuracy:',neuralMetrics.patterns.accuracy);

Production API base

Production REST base is https://agentstack.tech/api. Prefer the helper (Node, scripts, examples):

import{AgentStackSDK,resolveAgentStackApiBase}from'@agentstack/sdk';constsdk=newAgentStackSDK({apiBase: resolveAgentStackApiBase(),apiKey: process.env.AGENTSTACK_API_KEY,});
EnvironmentConfiguration
Production (default)Omit AGENTSTACK_API_BASEhttps://agentstack.tech/api
Local CoreAGENTSTACK_API_BASE=http://localhost:8000/api
Vite SPAVITE_API_BASE_URL=https://agentstack.tech/api (no /api suffix in some setups — HTTPClient normalizes)
# Node / CI
AGENTSTACK_API_BASE=https://agentstack.tech/api
AGENTSTACK_API_KEY=your_api_key

The SDK is a client library — deploy your app as you normally would (static host, serverless, container). No separate “SDK Docker image” is required.

🤝 Contributing

Мы приветствуем вклад в развитие SDK! Пожалуйста, ознакомьтесь с нашими руководящими принципами:

  1. Следуйте TypeScript best practices
  2. Добавляйте тесты для нового функционала
  3. Обновляйте документацию
  4. Используйте Neural Architecture компоненты
  5. Поддерживайте обратную совместимость

📞 Поддержка


npm:@agentstack/sdk · AI entry:AGENTS.md · Integrator scope:docs/INTEGRATOR_SCOPE.md

About

SDK for fast AI build apps

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages