Unify gitgram + aitimemachine into the monorepo (de-submodule) and merge vendored engines
Convert gitgram/ and aitimemachine/ from embedded git repos (which showed as opaque submodule gitlinks on GitHub) into fully-tracked first-party content. AITM now merges its 7 vendored repos as first-party engines: - memory: beads (Go task DAG) + context7 (docs SDK), unified into saved_contexts - git: vendored C git (bundled binary) + gitnexus (in-process code intelligence) - agentic: a2a (@a2a-js/sdk) + pal (AITM-managed Python subprocess) Includes the full session's product build: Gitgram web/mobile/backend features, AITM website/CLI/MCP, the unified memory layer, engine build tooling (scripts/build-engines.sh, Dockerfile, CI), docs (README, ENGINES.md, ARCHITECTURE.md), and extensive test suites. Build artifacts, node_modules, external/, and gemini-cli are gitignored. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
be50a0dd88
commit
49b183818c
227
.github/workflows/aitm-engines.yml
vendored
Normal file
227
.github/workflows/aitm-engines.yml
vendored
Normal file
@ -0,0 +1,227 @@
|
||||
# =============================================================================
|
||||
# AITM Engines - Build first-party engines and run AITM test suites.
|
||||
# Builds the vendored engines (beads/Go, git/C, pal/Python, TS libs) via
|
||||
# scripts/build-engines.sh, verifies the produced artifacts, then runs the
|
||||
# AITM core + api-server + mcp test suites and typechecks.
|
||||
# Triggers only on changes under aitimemachine/**.
|
||||
# =============================================================================
|
||||
name: AITM Engines
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "aitimemachine/**"
|
||||
- ".github/workflows/aitm-engines.yml"
|
||||
pull_request:
|
||||
paths:
|
||||
- "aitimemachine/**"
|
||||
- ".github/workflows/aitm-engines.yml"
|
||||
|
||||
env:
|
||||
GO_VERSION: "1.26"
|
||||
NODE_VERSION: "20"
|
||||
PYTHON_VERSION: "3.12"
|
||||
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# Build every vendored engine and verify the produced binaries / venv.
|
||||
# ---------------------------------------------------------------------------
|
||||
build-engines:
|
||||
name: "Build: AITM Engines"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Go ${{ env.GO_VERSION }}
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ env.GO_VERSION }}
|
||||
cache-dependency-path: aitimemachine/beads/go.sum
|
||||
|
||||
- name: Setup Node.js ${{ env.NODE_VERSION }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Setup Python ${{ env.PYTHON_VERSION }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
|
||||
- name: Install system build deps (git C source + ICU)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libicu-dev build-essential gettext zlib1g-dev libssl-dev libcurl4-openssl-dev
|
||||
|
||||
- name: Cache Go modules
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cache/go-build
|
||||
~/go/pkg/mod
|
||||
key: go-aitm-${{ hashFiles('aitimemachine/beads/go.sum') }}
|
||||
restore-keys: go-aitm-
|
||||
|
||||
- name: Cache npm dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-aitm-engines-${{ hashFiles('aitimemachine/**/package-lock.json') }}
|
||||
restore-keys: npm-aitm-engines-
|
||||
|
||||
- name: Build engines
|
||||
run: bash aitimemachine/scripts/build-engines.sh
|
||||
|
||||
- name: Verify engine artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
BIN="aitimemachine/bin"
|
||||
ENGINES="aitimemachine/engines"
|
||||
|
||||
echo "== verify bd =="
|
||||
test -x "$BIN/bd" || { echo "::error::aitimemachine/bin/bd missing or not executable"; exit 1; }
|
||||
"$BIN/bd" --version
|
||||
|
||||
echo "== verify git =="
|
||||
test -x "$BIN/git" || { echo "::error::aitimemachine/bin/git missing or not executable"; exit 1; }
|
||||
"$BIN/git" --version
|
||||
|
||||
echo "== verify pal venv =="
|
||||
test -x "$ENGINES/pal/bin/python" || { echo "::error::engines/pal venv missing"; exit 1; }
|
||||
"$ENGINES/pal/bin/python" --version
|
||||
|
||||
echo "All engine artifacts present."
|
||||
|
||||
- name: Upload engine binaries
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: aitm-engines
|
||||
path: |
|
||||
aitimemachine/bin/bd
|
||||
aitimemachine/bin/git
|
||||
if-no-files-found: warn
|
||||
retention-days: 7
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Run AITM core + api-server + mcp test suites. Depends on a clean engine build.
|
||||
# ---------------------------------------------------------------------------
|
||||
test:
|
||||
name: "Test: AITM Suites"
|
||||
needs: build-engines
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js ${{ env.NODE_VERSION }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Cache npm dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-aitm-test-${{ hashFiles('aitimemachine/**/package-lock.json') }}
|
||||
restore-keys: npm-aitm-test-
|
||||
|
||||
- name: Install AITM core dependencies
|
||||
working-directory: aitimemachine
|
||||
run: npm install --no-audit --no-fund
|
||||
|
||||
- name: Run AITM core tests (vitest)
|
||||
working-directory: aitimemachine
|
||||
run: npm test -- --coverage
|
||||
|
||||
- name: Install api-server dependencies
|
||||
working-directory: aitimemachine/api-server
|
||||
run: npm install --no-audit --no-fund
|
||||
|
||||
- name: Run api-server tests (vitest)
|
||||
working-directory: aitimemachine/api-server
|
||||
run: npm test -- --coverage
|
||||
|
||||
- name: Install mcp dependencies
|
||||
working-directory: aitimemachine/mcp
|
||||
run: npm install --no-audit --no-fund
|
||||
|
||||
- name: Run mcp tests (vitest)
|
||||
working-directory: aitimemachine/mcp
|
||||
run: npx vitest run --coverage --passWithNoTests
|
||||
|
||||
- name: Upload coverage reports
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: aitm-coverage
|
||||
path: |
|
||||
aitimemachine/coverage/**
|
||||
aitimemachine/api-server/coverage/**
|
||||
aitimemachine/mcp/coverage/**
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TypeScript type checking for api-server + mcp.
|
||||
# The known @types/uuid (v9) stub mismatch against uuid v10/v11 is tolerated.
|
||||
# ---------------------------------------------------------------------------
|
||||
typecheck:
|
||||
name: "Typecheck: api-server + mcp"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js ${{ env.NODE_VERSION }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Cache npm dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-aitm-typecheck-${{ hashFiles('aitimemachine/**/package-lock.json') }}
|
||||
restore-keys: npm-aitm-typecheck-
|
||||
|
||||
- name: Install api-server dependencies
|
||||
working-directory: aitimemachine/api-server
|
||||
run: npm install --no-audit --no-fund
|
||||
|
||||
- name: Install mcp dependencies
|
||||
working-directory: aitimemachine/mcp
|
||||
run: npm install --no-audit --no-fund
|
||||
|
||||
- name: Typecheck api-server
|
||||
working-directory: aitimemachine/api-server
|
||||
run: |
|
||||
# Allow the known @types/uuid stub warning; fail on any other error.
|
||||
npx tsc --noEmit 2>&1 | tee tsc.log
|
||||
if grep -vE "@types/uuid|node_modules/uuid" tsc.log | grep -qE "error TS"; then
|
||||
echo "::error::Unexpected TypeScript errors in api-server"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Typecheck mcp
|
||||
working-directory: aitimemachine/mcp
|
||||
run: |
|
||||
npx tsc --noEmit 2>&1 | tee tsc.log
|
||||
if grep -vE "@types/uuid|node_modules/uuid" tsc.log | grep -qE "error TS"; then
|
||||
echo "::error::Unexpected TypeScript errors in mcp"
|
||||
exit 1
|
||||
fi
|
||||
179
.github/workflows/gitgram-tests.yml
vendored
Normal file
179
.github/workflows/gitgram-tests.yml
vendored
Normal file
@ -0,0 +1,179 @@
|
||||
# =============================================================================
|
||||
# Gitgram Tests - Backend Jest suites, Web typecheck, and Playwright smoke.
|
||||
# Triggers only on changes under gitgram/**.
|
||||
# fail-fast: false so backend / web / e2e all report independently.
|
||||
# =============================================================================
|
||||
name: Gitgram Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "gitgram/**"
|
||||
- ".github/workflows/gitgram-tests.yml"
|
||||
pull_request:
|
||||
paths:
|
||||
- "gitgram/**"
|
||||
- ".github/workflows/gitgram-tests.yml"
|
||||
|
||||
env:
|
||||
NODE_VERSION: "20"
|
||||
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# Backend - Jest against live Postgres + Redis.
|
||||
# ---------------------------------------------------------------------------
|
||||
backend:
|
||||
name: "Test: Gitgram Backend (Jest)"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
fail-fast: false
|
||||
defaults:
|
||||
run:
|
||||
working-directory: gitgram/backend
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16
|
||||
env:
|
||||
POSTGRES_PASSWORD: test
|
||||
POSTGRES_DB: gitgram_test
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd pg_isready
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
redis:
|
||||
image: redis:7
|
||||
ports:
|
||||
- 6379:6379
|
||||
options: >-
|
||||
--health-cmd "redis-cli ping"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js ${{ env.NODE_VERSION }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Cache npm dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-gitgram-backend-${{ hashFiles('gitgram/backend/package-lock.json') }}
|
||||
restore-keys: npm-gitgram-backend-
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Generate Prisma client
|
||||
run: npm run prisma:generate
|
||||
|
||||
- name: Run Jest suites
|
||||
run: npm run test:coverage -- --forceExit
|
||||
env:
|
||||
DATABASE_URL: postgresql://postgres:test@localhost:5432/gitgram_test
|
||||
REDIS_URL: redis://localhost:6379
|
||||
NODE_ENV: test
|
||||
|
||||
- name: Upload backend coverage
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: gitgram-backend-coverage
|
||||
path: gitgram/backend/coverage/**
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Web - TypeScript type checking.
|
||||
# ---------------------------------------------------------------------------
|
||||
web-typecheck:
|
||||
name: "Typecheck: Gitgram Web"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
strategy:
|
||||
fail-fast: false
|
||||
defaults:
|
||||
run:
|
||||
working-directory: gitgram/web
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js ${{ env.NODE_VERSION }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Cache npm dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-gitgram-web-${{ hashFiles('gitgram/web/package-lock.json') }}
|
||||
restore-keys: npm-gitgram-web-
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Typecheck web
|
||||
run: npx tsc --noEmit
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Web - Playwright smoke (chromium, navigation flow only).
|
||||
# ---------------------------------------------------------------------------
|
||||
web-e2e-smoke:
|
||||
name: "E2E Smoke: Gitgram Web (Playwright)"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
strategy:
|
||||
fail-fast: false
|
||||
defaults:
|
||||
run:
|
||||
working-directory: gitgram/web
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js ${{ env.NODE_VERSION }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Cache npm dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-gitgram-web-${{ hashFiles('gitgram/web/package-lock.json') }}
|
||||
restore-keys: npm-gitgram-web-
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers (chromium)
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Run Playwright smoke (navigation)
|
||||
run: npx playwright test e2e/navigation.spec.ts --project=chromium
|
||||
env:
|
||||
CI: "true"
|
||||
|
||||
- name: Upload Playwright report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: gitgram-web-playwright-report
|
||||
path: gitgram/web/playwright-report/**
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
17
.gitignore
vendored
17
.gitignore
vendored
@ -1,6 +1,23 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# AITM bundled first-party engines (built by aitimemachine/scripts/build-engines.sh)
|
||||
aitimemachine/bin/
|
||||
aitimemachine/engines/
|
||||
# Built engine binaries left inside vendored source dirs (regenerated by build-engines.sh)
|
||||
aitimemachine/beads/bd
|
||||
aitimemachine/git/git
|
||||
aitimemachine/git/git-*
|
||||
aitimemachine/**/*.node
|
||||
|
||||
# Third-party repos (not our code) — large, not part of the product
|
||||
external/
|
||||
aitimemachine/gemini-cli/
|
||||
|
||||
# Compiled native parser objects / large generated artifacts
|
||||
*.o
|
||||
*.a
|
||||
|
||||
# Build outputs
|
||||
dist/
|
||||
build/
|
||||
|
||||
277
README.md
277
README.md
@ -1,50 +1,232 @@
|
||||
# gitgram-ai (Monorepo)
|
||||
# gitgram-ai
|
||||
|
||||
Two products:
|
||||
**Gitgram** is the new GitHub — every repository is a TikTok/Instagram-style social
|
||||
profile. **AITimeMachine (AITM)** is the new Git — AI-native, deterministic version
|
||||
control with a unified memory layer and built-in agent orchestration.
|
||||
|
||||
1. `gitgram` (GitHub social network)
|
||||
2. `aitimemachine` (AITM, "Time Machine for AI coding")
|
||||
This monorepo ships both products together: a repository-first social network on top
|
||||
of an AI-native version-control substrate.
|
||||
|
||||
This repo is organized as a monorepo for local development and ops docs. Each product has its own `README.md`, and the repo still contains historical automation artifacts that are not the launch source of truth.
|
||||
---
|
||||
|
||||
## Quick Start (Local, Full Stack)
|
||||
## Monorepo Map
|
||||
|
||||
Runs Postgres + Redis + Gitgram backend + Gitgram web + AITM API via Docker Compose.
|
||||
|
||||
```bash
|
||||
docker compose up
|
||||
```
|
||||
gitgram-ai/
|
||||
├── gitgram/ # The social network (the "new GitHub")
|
||||
│ ├── web/ # Next.js 14 + React 18 web app (:3000)
|
||||
│ ├── backend/ # Express 5 + Prisma + GraphQL/tRPC/WS (:4000)
|
||||
│ └── mobile/ # Expo 54 / React Native + expo-router
|
||||
│
|
||||
├── aitimemachine/ # The version-control substrate (the "new Git")
|
||||
│ ├── api-server/ # HTTP API over the engines (Drizzle ORM) (:3001)
|
||||
│ ├── mcp/ # Model Context Protocol server (stdio/HTTP :3003)
|
||||
│ ├── cli/ (src/cli*) # `aitm` command-line client
|
||||
│ ├── website/ # Marketing / docs site (:3002)
|
||||
│ └── ─── 7 first-party engines (vendored, built in-tree) ───
|
||||
│ ├── beads/ # memory — task/issue DAG (Go, Dolt-backed)
|
||||
│ ├── context7/ # memory — up-to-date library docs (TS)
|
||||
│ ├── git/ # git — real upstream Git (vendored C)
|
||||
│ ├── gitnexus/ # git — code-intelligence graph (TS)
|
||||
│ ├── a2a/ # agentic — agent-to-agent protocol (TS)
|
||||
│ └── pal-mcp-server/ # agentic — Python agent execution (Python)
|
||||
│ # (gitnexus-shared/ supports the gitnexus engine)
|
||||
│
|
||||
├── scripts/ # Monorepo dev/ops scripts (dev.sh, smoke, verify)
|
||||
├── docs/ # Architecture, runbook, deploy, secrets, env matrix
|
||||
└── docker-compose.yml # Full local stack (Postgres + Redis + apps)
|
||||
```
|
||||
|
||||
Service URLs (when running the full stack together):
|
||||
- Gitgram web: `http://localhost:3000`
|
||||
- Gitgram backend: `http://localhost:4000` (`GET /health`)
|
||||
- AITM API: `http://localhost:3001` (`GET /health`)
|
||||
The seven engines are **first-party**: vendored, built, and managed as part of the
|
||||
product. There are no "assumed external service" seams — the old `GITNEXUS_URL`,
|
||||
`CONTEXT7_URL`, and `PAL_MCP_URL` environment seams have been removed.
|
||||
|
||||
Notes:
|
||||
- AITM website is not started by the root `docker-compose.yml` (to avoid port conflicts with Gitgram web). Run it separately if needed.
|
||||
- AITM database defaults to whatever `aitimemachine/api-server/.env` provides (`DATABASE_URL`). In production, use Neon; locally you can use a local Postgres if you want.
|
||||
---
|
||||
|
||||
## Start AITM Website Locally
|
||||
## AITM's 7 Merged Engines
|
||||
|
||||
When Gitgram web is already on `:3000`, run AITM website on `:3002`:
|
||||
AITM merges seven vendored repos as engines across three layers. Full wiring details
|
||||
live in **[aitimemachine/ENGINES.md](aitimemachine/ENGINES.md)**.
|
||||
|
||||
| Layer | Engine | Lang | What it does | How it's wired |
|
||||
|-------|--------|------|--------------|----------------|
|
||||
| **Memory** | `beads` | Go | Task/issue DAG memory (Dolt-backed) | Built to `bin/bd`; `routes/beads.ts` spawns it; tasks write through to memory |
|
||||
| **Memory** | `context7` | TS | Up-to-date library/framework docs | In-process `@upstash/context7-sdk`; `CONTEXT7_API_KEY` |
|
||||
| **Git** | `git` | C | The real upstream Git | Built to `bin/git`; `git-engine.ts` shells out; checkpoints mirror to real commits |
|
||||
| **Git** | `gitnexus` | TS | Code-intelligence graph (Tree-sitter + LadybugDB) | In-process via `gitnexus/src/index.ts`; `gn_*` MCP tools |
|
||||
| **Agentic** | `a2a` | TS | Agent-to-agent protocol | `@a2a-js/sdk` (`DefaultRequestHandler`, `InMemoryTaskStore`, `A2AClient`) |
|
||||
| **Agentic** | `pal` | Python | Agent code execution / multi-model orchestration | AITM-managed subprocess (`palEngine.ts`) speaking MCP over stdio |
|
||||
|
||||
The seventh, `gitnexus-shared`, is a TS support library the `gitnexus` engine inlines
|
||||
at build time.
|
||||
|
||||
Both memory engines feed AITM's **unified memory**: `services/memoryService.ts`
|
||||
ingests beads tasks (`source='task'`) and context7 docs (`source='library'`) into
|
||||
`saved_contexts` with embeddings, so `/v1/contexts/search/*` returns them alongside
|
||||
conversation memory.
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
|
||||
| Tool | Version | Needed for |
|
||||
|------|---------|-----------|
|
||||
| Node.js | 20+ | all apps and engines |
|
||||
| npm | 10+ | dependency install |
|
||||
| Docker + Compose v2 | latest | Postgres, Redis, full stack |
|
||||
| Go | 1.21+ | building the `beads` engine |
|
||||
| `make` + `cc` | any | building the vendored `git` engine |
|
||||
| Python | 3.10+ | building the `pal` engine venv |
|
||||
|
||||
> Engine builds **soft-fail**: a missing toolchain for one engine never blocks the
|
||||
> others. `git` falls back to the system binary; missing engines simply report
|
||||
> unavailable in the health endpoint.
|
||||
|
||||
### 1. Clone and bootstrap
|
||||
|
||||
```bash
|
||||
cd aitimemachine/website
|
||||
cp .env.example .env.local
|
||||
PORT=3002 npm run dev
|
||||
git clone <repo-url> gitgram-ai && cd gitgram-ai
|
||||
|
||||
# One-shot dev setup: prereq checks, .env scaffolding, infra, deps, migrations
|
||||
bash scripts/dev.sh
|
||||
```
|
||||
|
||||
Open `http://localhost:3002`.
|
||||
`scripts/dev.sh` copies every `.env.*.example` to its real counterpart (never
|
||||
overwriting), starts Postgres + Redis, runs `npm ci` for each package, and applies
|
||||
Prisma (Gitgram) and Drizzle (AITM) migrations.
|
||||
|
||||
## Production Compose (Single VPS)
|
||||
Use `bash scripts/dev.sh --infra` to bring up only Postgres + Redis.
|
||||
|
||||
Use `docs/runbook.md` as the canonical manual launch contract.
|
||||
### 2. Build the AITM engines
|
||||
|
||||
`docker-compose.prod.yml` is retained as a non-canonical full-docker reference, not the launch source of truth.
|
||||
```bash
|
||||
bash aitimemachine/scripts/build-engines.sh
|
||||
```
|
||||
|
||||
## Release Gates
|
||||
This builds the TS engine libraries, compiles `beads` → `aitimemachine/bin/bd` and
|
||||
`git` → `aitimemachine/bin/git`, provisions the `pal` Python venv under
|
||||
`aitimemachine/engines/pal`, and links workspace deps into `api-server` and `mcp`.
|
||||
Both `bin/` and `engines/` are git-ignored. Verify with `GET /v1/health/providers`.
|
||||
|
||||
Run these before staging/production deploys:
|
||||
### 3. Run the dev stack
|
||||
|
||||
```bash
|
||||
docker compose up # Postgres + Redis + Gitgram + AITM API
|
||||
docker compose --profile tools up # + GitNexus + Context7 helpers
|
||||
```
|
||||
|
||||
Or run individual services natively (hot reload):
|
||||
|
||||
```bash
|
||||
npm run dev:gitgram-backend # → http://localhost:4000 (GET /health)
|
||||
npm run dev:gitgram-web # → http://localhost:3000
|
||||
npm run dev:aitm-api # → http://localhost:3001 (GET /health)
|
||||
npm run dev:aitm-mcp # → stdio / http://localhost:3003
|
||||
```
|
||||
|
||||
The AITM website is intentionally **not** started by the root compose file (to avoid a
|
||||
port clash with Gitgram web). Run it on `:3002` separately:
|
||||
|
||||
```bash
|
||||
cd aitimemachine/website && cp .env.example .env.local && PORT=3002 npm run dev
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
|
||||
`dev.sh` scaffolds these from their `.example` siblings:
|
||||
|
||||
| File | Service |
|
||||
|------|---------|
|
||||
| `.env.gitgram` | Gitgram backend |
|
||||
| `.env.gitgram-web` | Gitgram web |
|
||||
| `.env.aitm-api` | AITM API server |
|
||||
| `.env.aitm-website` | AITM website |
|
||||
| `.env.postgres` | Postgres container |
|
||||
|
||||
Key AITM engine vars (see [ENGINES.md](aitimemachine/ENGINES.md) for the full matrix):
|
||||
`CONTEXT7_API_KEY`, `AITM_GIT_BIN`, `AITM_GIT_MIRROR`, `BEADS_BINARY`,
|
||||
`PAL_VENV_DIR` / `PAL_PYTHON`, `AITM_MEMORY_USER_ID` / `AITM_MEMORY_PROJECT_ID`.
|
||||
The full per-environment matrix lives in [docs/environment-matrix.md](docs/environment-matrix.md).
|
||||
|
||||
---
|
||||
|
||||
## Architecture at a Glance
|
||||
|
||||
```
|
||||
┌──────────────┐ ┌──────────────┐
|
||||
│ Gitgram web │ │ Gitgram │
|
||||
│ (Next.js) │ │ mobile (Expo)│
|
||||
└──────┬───────┘ └──────┬───────┘
|
||||
│ GraphQL / tRPC / WebSocket
|
||||
└───────────┬────────┘
|
||||
▼
|
||||
┌──────────────────────┐
|
||||
│ Gitgram backend │ Express 5
|
||||
│ (controllers, jobs) │ Prisma ORM
|
||||
└──────────┬───────────┘
|
||||
▼
|
||||
┌───────────────────┐
|
||||
│ Postgres + Redis │
|
||||
└───────────────────┘
|
||||
|
||||
────────────────── AITM substrate ──────────────────
|
||||
|
||||
┌──────────┐ ┌──────────┐
|
||||
│ aitm CLI │ │ MCP │ (Claude, IDEs, agents)
|
||||
└────┬─────┘ └────┬─────┘
|
||||
│ HTTP / MCP │
|
||||
└───────┬────────┘
|
||||
▼
|
||||
┌────────────────────────┐
|
||||
│ AITM api-server │ Drizzle ORM
|
||||
│ engineManager.ts │ resolves bundled engine paths
|
||||
└───────────┬────────────┘
|
||||
▼
|
||||
┌──────── 7 first-party engines ────────┐
|
||||
│ memory : beads (bin/bd) · context7 │
|
||||
│ git : git (bin/git) · gitnexus │
|
||||
│ agentic: a2a (@a2a-js) · pal (venv) │
|
||||
└────────────────────────────────────────┘
|
||||
|
||||
Gitgram ↔ AITM bridge: gitgramBridgeService.ts + routes/gitgram*.ts
|
||||
```
|
||||
|
||||
For data flow, the unified memory layer, checkpoint mirroring, and how each MCP tool
|
||||
maps to an engine, see **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)**.
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
Each package owns its test suite:
|
||||
|
||||
```bash
|
||||
npm test --prefix gitgram/web # Vitest + Testing Library
|
||||
npm test --prefix gitgram/backend # needs live Postgres + Redis
|
||||
npm test --prefix aitimemachine/api-server # Vitest + supertest
|
||||
npm test --prefix aitimemachine # Vitest (core + engines)
|
||||
```
|
||||
|
||||
Engine and integration smokes:
|
||||
|
||||
```bash
|
||||
bash aitimemachine/scripts/mcp-smoke-test.sh # MCP tools end-to-end
|
||||
bash aitimemachine/scripts/cli-smoke-test.sh # aitm CLI
|
||||
bash aitimemachine/scripts/a2a-smoke-test.sh # agent-to-agent protocol
|
||||
npm run smoke:local-launch # whole-stack local smoke gate
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Deployment
|
||||
|
||||
Local and CI use Docker Compose (`docker-compose.yml`). Production runs on a single
|
||||
VPS following the manual launch contract in [docs/runbook.md](docs/runbook.md);
|
||||
`docker-compose.prod.yml` is a non-canonical full-docker reference.
|
||||
|
||||
Run release gates before any staging/production deploy:
|
||||
|
||||
```bash
|
||||
npm run verify:aitm-packages
|
||||
@ -53,30 +235,25 @@ npm run verify:secrets:staging
|
||||
npm run verify:secrets:production
|
||||
```
|
||||
|
||||
AITM API local startup without external secret keys:
|
||||
Deploy pipeline and secrets contracts: [docs/deploy-pipeline.md](docs/deploy-pipeline.md),
|
||||
[docs/secrets-contract.md](docs/secrets-contract.md).
|
||||
|
||||
```bash
|
||||
npm run verify:aitm-local
|
||||
npm run dev:aitm-api:clean
|
||||
```
|
||||
---
|
||||
|
||||
Stage A local smoke gate:
|
||||
## Contributing
|
||||
|
||||
```bash
|
||||
npm run smoke:local-launch
|
||||
```
|
||||
1. Read [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) and
|
||||
[aitimemachine/ENGINES.md](aitimemachine/ENGINES.md) to understand the layering.
|
||||
2. Run `bash scripts/dev.sh` then `bash aitimemachine/scripts/build-engines.sh`.
|
||||
3. Keep engines first-party — do not reintroduce external-URL seams.
|
||||
4. Add tests with your change; run the relevant suite and smoke scripts above.
|
||||
5. Run the verify/secrets gates before opening a deploy-bound PR.
|
||||
|
||||
Optional flags:
|
||||
- `SKIP_HTTP=1 npm run smoke:local-launch`
|
||||
- `AUTO_START=1 npm run smoke:local-launch`
|
||||
- `RUN_AITM_CLI_SMOKE=1 npm run smoke:local-launch`
|
||||
- `RUN_AITM_MCP_SMOKE=1 npm run smoke:local-launch`
|
||||
### Docs index
|
||||
|
||||
## Docs Index
|
||||
|
||||
- Strict execution queue: `REMAINING.md`
|
||||
- North star PRD/architecture: `NORTH_STAR_PRD_ARCHITECTURE_V1.md`
|
||||
- Manual launch runbook: `docs/runbook.md`
|
||||
- Deploy pipeline contract: `docs/deploy-pipeline.md`
|
||||
- Env var matrix: `docs/environment-matrix.md`
|
||||
- Secrets contract: `docs/secrets-contract.md`
|
||||
- North-star PRD / architecture — [NORTH_STAR_PRD_ARCHITECTURE_V1.md](NORTH_STAR_PRD_ARCHITECTURE_V1.md)
|
||||
- Deeper architecture — [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
|
||||
- Engine wiring — [aitimemachine/ENGINES.md](aitimemachine/ENGINES.md)
|
||||
- Manual launch runbook — [docs/runbook.md](docs/runbook.md)
|
||||
- Environment matrix — [docs/environment-matrix.md](docs/environment-matrix.md)
|
||||
- Agents guide — [docs/AGENTS.md](docs/AGENTS.md)
|
||||
|
||||
@ -1 +0,0 @@
|
||||
Subproject commit 937722abe0db76e8f3915fb9861d9479b5902dc2
|
||||
79
aitimemachine/.dockerignore
Normal file
79
aitimemachine/.dockerignore
Normal file
@ -0,0 +1,79 @@
|
||||
# .dockerignore for the AITM api-server production image.
|
||||
# Build context is the aitimemachine root (see api-server/Dockerfile).
|
||||
# Goal: ship engine SOURCE only — let build-engines.sh produce all artifacts
|
||||
# from scratch inside the image, and keep the context small.
|
||||
|
||||
# ── VCS / editor / OS cruft ──
|
||||
.git
|
||||
.gitignore
|
||||
.github
|
||||
.vscode
|
||||
.idea
|
||||
**/.DS_Store
|
||||
**/*.log
|
||||
|
||||
# ── Pre-built artifacts (rebuilt inside the image) ──
|
||||
bin
|
||||
engines
|
||||
**/node_modules
|
||||
**/dist
|
||||
**/build
|
||||
**/out
|
||||
**/.tsbuildinfo
|
||||
**/*.tsbuildinfo
|
||||
|
||||
# ── Engine intermediate build output (recompiled in stage 1) ──
|
||||
beads/bd
|
||||
git/git
|
||||
**/__pycache__
|
||||
**/*.pyc
|
||||
**/.venv
|
||||
**/venv
|
||||
|
||||
# ── Test / coverage / tooling state ──
|
||||
coverage
|
||||
**/coverage
|
||||
**/tests
|
||||
**/test
|
||||
**/*.test.*
|
||||
**/*.spec.*
|
||||
**/vitest.config.*
|
||||
**/jest.config.*
|
||||
.tmp
|
||||
tmp
|
||||
**/.tmp
|
||||
|
||||
# ── Local secrets / env (never bake into the image) ──
|
||||
**/.env
|
||||
**/.env.*
|
||||
!**/.env.example
|
||||
**/.kb-credentials.json
|
||||
**/.kb-indexer-state.json
|
||||
**/.mega-indexer-state.json
|
||||
**/.aitimemachine
|
||||
|
||||
# ── Docker / compose (not needed in the build context) ──
|
||||
**/Dockerfile
|
||||
**/.dockerignore
|
||||
docker-compose*.yml
|
||||
|
||||
# ── Subprojects not part of the api-server runtime ──
|
||||
# (engine source kept: a2a, context7, gitnexus, gitnexus-shared, beads, git,
|
||||
# pal-mcp-server, scripts, api-server)
|
||||
gemini-cli
|
||||
gitnexus-web
|
||||
website
|
||||
extensions
|
||||
nvim-plugin
|
||||
asset
|
||||
docs
|
||||
deploy
|
||||
agents
|
||||
tools
|
||||
|
||||
# ── Misc dev scripts / demos at the root ──
|
||||
*.mjs
|
||||
*-check.sh
|
||||
final-test.sh
|
||||
test-*.sh
|
||||
test-*.ts
|
||||
143
aitimemachine/.env.example
Normal file
143
aitimemachine/.env.example
Normal file
@ -0,0 +1,143 @@
|
||||
# =============================================================================
|
||||
# Gitgram TimeMachine - Environment Variables
|
||||
# =============================================================================
|
||||
# Copy this file to .env and fill in the values.
|
||||
# Validated at startup by src/config/env-contract.ts
|
||||
#
|
||||
# Tier legend:
|
||||
# [REQUIRED] -- server will NOT start without this in any environment
|
||||
# [PROD] -- required in production only; optional in dev/test
|
||||
# (no marker) -- optional with sensible default or feature disabled when absent
|
||||
# =============================================================================
|
||||
|
||||
# ── Core ─────────────────────────────────────────────────────────────────────
|
||||
# Runtime environment: development | staging | production | test
|
||||
NODE_ENV=development
|
||||
# HTTP port for the API server
|
||||
PORT=3001
|
||||
|
||||
# ── Database [REQUIRED] ─────────────────────────────────────────────────────
|
||||
# Neon PostgreSQL connection string (include ?sslmode=require for Neon)
|
||||
DATABASE_URL=postgresql://user:password@host/database?sslmode=require
|
||||
|
||||
# ── Networking ───────────────────────────────────────────────────────────────
|
||||
# Allowed CORS origin(s); restrict in production
|
||||
CORS_ORIGIN=*
|
||||
# AITM website URL (for redirects, billing success pages, emails)
|
||||
WEBSITE_URL=http://localhost:3000
|
||||
|
||||
# ── Auth ─────────────────────────────────────────────────────────────────────
|
||||
# Shared secret for website-to-API internal calls [PROD]
|
||||
# INTERNAL_SECRET=your-internal-secret-here
|
||||
# JWT signing secret for session tokens (auto-generated if not set)
|
||||
# AITM_JWT_SECRET=
|
||||
# Clerk webhook secret (for user sync)
|
||||
# CLERK_WEBHOOK_SECRET=
|
||||
|
||||
# ── AWS / S3 ─────────────────────────────────────────────────────────────────
|
||||
AWS_REGION=us-east-1
|
||||
# AWS IAM credentials (leave blank for SDK default chain)
|
||||
# AWS_ACCESS_KEY_ID=
|
||||
# AWS_SECRET_ACCESS_KEY=
|
||||
# S3 bucket for knowledge base blobs
|
||||
# KB_S3_BUCKET=
|
||||
KB_S3_PREFIX=knowledge-base
|
||||
# Content size thresholds (bytes)
|
||||
KB_MAX_CONTENT_BYTES=500000
|
||||
KB_MAX_FILE_BYTES=1048576
|
||||
KB_S3_THRESHOLD_BYTES=102400
|
||||
# Embeddings
|
||||
KB_EMBEDDINGS_ENABLED=true
|
||||
KB_EMBEDDING_MAX_BYTES=100000
|
||||
|
||||
# ── Polar.sh Billing ────────────────────────────────────────────────────────
|
||||
# Get from https://polar.sh/dashboard
|
||||
# POLAR_ACCESS_TOKEN=polar_at_xxx
|
||||
# POLAR_MODE=sandbox
|
||||
# POLAR_WEBHOOK_SECRET=whsec_xxx
|
||||
# POLAR_PRO_PRODUCT_ID=prod_xxx
|
||||
# POLAR_TEAM_PRODUCT_ID=prod_xxx
|
||||
|
||||
# ── Email (Resend) ──────────────────────────────────────────────────────────
|
||||
# Get API key from https://resend.com/api-keys
|
||||
# Falls back to console logging when not set
|
||||
# RESEND_API_KEY=re_...
|
||||
|
||||
# ── Monitoring ───────────────────────────────────────────────────────────────
|
||||
# Sentry DSN for error tracking (optional)
|
||||
# SENTRY_DSN=
|
||||
# Logging level: debug | info | warn | error
|
||||
# LOG_LEVEL=
|
||||
# API version string reported in health endpoint
|
||||
API_VERSION=1.0.0
|
||||
|
||||
# ── LLM / AI ────────────────────────────────────────────────────────────────
|
||||
# At least one LLM key is recommended for AI features (oracle, research)
|
||||
# OPENAI_API_KEY=sk-...
|
||||
# ANTHROPIC_API_KEY=sk-ant-...
|
||||
# Voyage AI for embeddings (alternative to OpenAI)
|
||||
# VOYAGE_API_KEY=
|
||||
|
||||
# ── Web Search ───────────────────────────────────────────────────────────────
|
||||
# At least one search provider key enables web search
|
||||
# BRAVE_SEARCH_API_KEY=
|
||||
# SERPAPI_KEY=
|
||||
# SERPER_API_KEY=
|
||||
# FIRECRAWL_API_KEY=
|
||||
|
||||
# ── Data Privacy ─────────────────────────────────────────────────────────────
|
||||
REQUIRE_EXPLICIT_CONSENT=false
|
||||
|
||||
# ── Redis (optional) ────────────────────────────────────────────────────────
|
||||
# Used for distributed rate limiting. Falls back to in-memory when not set.
|
||||
# REDIS_URL=redis://localhost:6379
|
||||
|
||||
# ── Background Workers ──────────────────────────────────────────────────────
|
||||
# Enable managed cron scheduler in API server (recommended for production)
|
||||
ENABLE_WORKERS=false
|
||||
DELETE_WORKER_ENABLED=false
|
||||
DELETE_WORKER_LIMIT=50
|
||||
DELETE_WORKER_DRY_RUN=false
|
||||
# DELETE_WORKER_USER_ID=
|
||||
DELETE_CRON="*/5 * * * *"
|
||||
RETENTION_WORKER_ENABLED=false
|
||||
RETENTION_WORKER_LIMIT=100
|
||||
RETENTION_WORKER_DRY_RUN=false
|
||||
# RETENTION_WORKER_PROJECT_ID=
|
||||
# RETENTION_WORKER_USER_ID=
|
||||
# RETENTION_WORKER_DATA_CLASS=
|
||||
RETENTION_CRON="0 3 * * *"
|
||||
GC_WORKER_ENABLED=false
|
||||
GC_WORKER_LIMIT=200
|
||||
GC_WORKER_DRY_RUN=false
|
||||
GC_WORKER_OLDER_THAN_DAYS=30
|
||||
# GC_WORKER_USER_ID=
|
||||
GC_CRON="0 4 * * 0"
|
||||
|
||||
# ── CLI / MCP ────────────────────────────────────────────────────────────────
|
||||
# API server URL for CLI/MCP connections
|
||||
# AITM_API_URL=http://localhost:3001
|
||||
# API key for authenticating CLI/MCP requests
|
||||
# AITM_API_KEY=
|
||||
# Enable cloud sync from CLI
|
||||
# AITM_CLOUD_SYNC=false
|
||||
# Website URL for CLI auth redirects
|
||||
# AITM_WEBSITE_URL=https://timemachine.gitgram.app
|
||||
# Custom audit log directory
|
||||
# AITM_AUDIT_DIR=
|
||||
# Override AITM home directory
|
||||
# AITM_HOME=
|
||||
# Remote metrics endpoint
|
||||
# AITM_METRICS_ENDPOINT=
|
||||
# Enable experimental MCP tools (0/1)
|
||||
# AITM_MCP_EXPERIMENTAL=0
|
||||
# Run daemon in foreground (0/1)
|
||||
# AITM_DAEMON=0
|
||||
# Auto-start daemon (0/1)
|
||||
# AITM_AUTO_DAEMON=0
|
||||
# Debug stack traces (0/1)
|
||||
# AITM_DEBUG=0
|
||||
# Disable auto-listen on import (for testing) (0/1)
|
||||
# AITM_DISABLE_AUTOLISTEN=0
|
||||
# v3 store data directory
|
||||
# TM_DATA_DIR=
|
||||
1
aitimemachine/.eslintrc.json
Normal file
1
aitimemachine/.eslintrc.json
Normal file
@ -0,0 +1 @@
|
||||
{"extends": ["@typescript-eslint/recommended"], "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "rules": {}}
|
||||
697
aitimemachine/.github/workflows/ci.yml
vendored
Normal file
697
aitimemachine/.github/workflows/ci.yml
vendored
Normal file
@ -0,0 +1,697 @@
|
||||
# =============================================================================
|
||||
# AITimeMachine CI - Comprehensive Production Gates
|
||||
# =============================================================================
|
||||
# Runs on push to main/master and on all PRs. Includes tag-based releases.
|
||||
#
|
||||
# Gates:
|
||||
# 1. Build gates - TypeScript compilation, ESLint, build artifacts
|
||||
# 2. Migration gates - Drizzle migration validation
|
||||
# 3. Test gates - Unit tests, integration-safe tests, service tests
|
||||
# 4. Quality gates - Redaction gate, search relevance gate
|
||||
# 5. Smoke tests - API server build-and-start verification
|
||||
# =============================================================================
|
||||
name: CI/CD
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
|
||||
concurrency:
|
||||
group: aitm-ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 1: Core package - Lint & TypeScript check
|
||||
# ---------------------------------------------------------------------------
|
||||
core-lint:
|
||||
name: "Core: Lint & Type Check"
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: ESLint
|
||||
run: npm run lint
|
||||
|
||||
- name: TypeScript strict check
|
||||
run: npx tsc --noEmit --strict
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 2: Core package - Build & test
|
||||
# ---------------------------------------------------------------------------
|
||||
core-build-test:
|
||||
name: "Core: Build & Test"
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
|
||||
- name: Upload build artifacts
|
||||
if: matrix.node-version == 20
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: core-lib
|
||||
path: lib/
|
||||
retention-days: 7
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 3: Core - Redaction quality gate
|
||||
# ---------------------------------------------------------------------------
|
||||
redaction-gate:
|
||||
name: "Quality: Redaction Gate"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [core-build-test]
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Redaction quality gate
|
||||
env:
|
||||
AITM_REDACTION_MIN_PRECISION: "0.80"
|
||||
AITM_REDACTION_MIN_RECALL: "0.95"
|
||||
AITM_REDACTION_MIN_F1: "0.88"
|
||||
run: npm run test:redaction-gate
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 4: Core - Search relevance gate
|
||||
# ---------------------------------------------------------------------------
|
||||
search-relevance-gate:
|
||||
name: "Quality: Search Relevance Gate"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [core-build-test]
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Search relevance gate
|
||||
env:
|
||||
AITM_SEARCH_RELEVANCE_MIN_TOP1: "0.65"
|
||||
AITM_SEARCH_RELEVANCE_MIN_MRR: "0.78"
|
||||
AITM_SEARCH_RELEVANCE_MIN_RECALL_AT3: "0.95"
|
||||
run: npm run test:search-relevance-gate
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 5: API Server - Lint & TypeScript check
|
||||
# ---------------------------------------------------------------------------
|
||||
api-server-lint:
|
||||
name: "API Server: Lint & Type Check"
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: TypeScript type-check
|
||||
run: npx tsc --noEmit
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 6: API Server - Build
|
||||
# ---------------------------------------------------------------------------
|
||||
api-server-build:
|
||||
name: "API Server: Build"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [api-server-lint]
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Upload API server build
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: api-server-dist
|
||||
path: api-server/dist
|
||||
retention-days: 7
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 7: API Server - Drizzle migration validation
|
||||
# ---------------------------------------------------------------------------
|
||||
api-server-migration-check:
|
||||
name: "API Server: Migration Validation"
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Validate drizzle migration files
|
||||
run: |
|
||||
echo "Checking drizzle migration files..."
|
||||
|
||||
DRIZZLE_DIR="drizzle"
|
||||
if [ ! -d "$DRIZZLE_DIR" ]; then
|
||||
echo "No drizzle migration directory found. Checking parent..."
|
||||
DRIZZLE_DIR="../drizzle"
|
||||
fi
|
||||
|
||||
if [ -d "$DRIZZLE_DIR" ]; then
|
||||
MIGRATION_COUNT=$(find "$DRIZZLE_DIR" -name "*.sql" -not -path "*/meta/*" | wc -l)
|
||||
echo "Found $MIGRATION_COUNT migration file(s)."
|
||||
|
||||
# Validate migration file syntax
|
||||
for f in $(find "$DRIZZLE_DIR" -name "*.sql" -not -path "*/meta/*"); do
|
||||
echo "Validating: $f"
|
||||
|
||||
# Check for common issues
|
||||
if grep -qi "DROP TABLE" "$f"; then
|
||||
echo "WARNING: DROP TABLE detected in $f"
|
||||
fi
|
||||
if grep -qi "DROP COLUMN" "$f"; then
|
||||
echo "WARNING: DROP COLUMN detected in $f"
|
||||
fi
|
||||
done
|
||||
|
||||
# Check meta directory for journal integrity
|
||||
if [ -d "$DRIZZLE_DIR/meta" ]; then
|
||||
if [ -f "$DRIZZLE_DIR/meta/_journal.json" ]; then
|
||||
echo "Drizzle migration journal found."
|
||||
JOURNAL_COUNT=$(node -e "const j = require('./$DRIZZLE_DIR/meta/_journal.json'); console.log(j.entries?.length || 0)" 2>/dev/null || echo "unknown")
|
||||
echo "Journal entries: $JOURNAL_COUNT"
|
||||
else
|
||||
echo "WARNING: Drizzle migration journal (_journal.json) not found."
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "No drizzle migration directory found."
|
||||
fi
|
||||
|
||||
echo "Migration validation complete."
|
||||
|
||||
- name: Drizzle schema check
|
||||
run: |
|
||||
echo "Running drizzle-kit check..."
|
||||
npx drizzle-kit check 2>&1 || echo "drizzle-kit check completed (may not be configured)."
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 8a: API Server - Full test suite (vitest run)
|
||||
# ---------------------------------------------------------------------------
|
||||
api-server-tests:
|
||||
name: "API Server: Tests"
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run all tests
|
||||
run: npx vitest run
|
||||
env:
|
||||
AITM_TEST_NO_LISTEN: "1"
|
||||
NODE_ENV: test
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 8b: API Server - Service tests (no external deps)
|
||||
# ---------------------------------------------------------------------------
|
||||
api-server-service-tests:
|
||||
name: "API Server: Service Tests"
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run service tests
|
||||
run: npx vitest run tests/services --passWithNoTests
|
||||
env:
|
||||
AITM_TEST_NO_LISTEN: "1"
|
||||
NODE_ENV: test
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 9: API Server - Integration-safe tests
|
||||
# ---------------------------------------------------------------------------
|
||||
api-server-integration-safe:
|
||||
name: "API Server: Integration-Safe Tests"
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run integration-safe tests
|
||||
run: npm run test:integration:safe
|
||||
env:
|
||||
NODE_ENV: test
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 10: API Server - Smoke test (build, start, health)
|
||||
# ---------------------------------------------------------------------------
|
||||
api-server-smoke-test:
|
||||
name: "Smoke: API Server Starts & Responds"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [api-server-build]
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Start server and verify health
|
||||
run: |
|
||||
PORT=3001
|
||||
export PORT
|
||||
|
||||
# Start the API server in the background
|
||||
node dist/server.js &
|
||||
SERVER_PID=$!
|
||||
|
||||
echo "Waiting for API server to start (PID $SERVER_PID)..."
|
||||
|
||||
RETRIES=20
|
||||
INTERVAL=3
|
||||
SUCCESS=false
|
||||
|
||||
for i in $(seq 1 $RETRIES); do
|
||||
HTTP_CODE=$(curl -sf -o /dev/null -w "%{http_code}" "http://localhost:${PORT}/health" 2>/dev/null || echo "000")
|
||||
if [ "$HTTP_CODE" = "200" ]; then
|
||||
echo "Health check PASSED (HTTP $HTTP_CODE) on attempt $i"
|
||||
SUCCESS=true
|
||||
break
|
||||
fi
|
||||
echo "Attempt $i/$RETRIES: HTTP $HTTP_CODE - waiting ${INTERVAL}s..."
|
||||
sleep $INTERVAL
|
||||
done
|
||||
|
||||
# Clean up
|
||||
kill $SERVER_PID 2>/dev/null || true
|
||||
|
||||
if [ "$SUCCESS" = "false" ]; then
|
||||
echo "FAIL: API server did not respond to /health within timeout."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "API server smoke test PASSED."
|
||||
env:
|
||||
NODE_ENV: test
|
||||
# Provide minimal env so the server can start without crashing
|
||||
DATABASE_URL: "postgresql://localhost:5432/aitm_smoke_test"
|
||||
JWT_SECRET: "smoke-test-secret"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 11: VS Code Extension - Type check
|
||||
# ---------------------------------------------------------------------------
|
||||
extension-check:
|
||||
name: "Extension: Type Check"
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: extensions/vscode
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Check if extension directory exists
|
||||
id: check-ext
|
||||
run: |
|
||||
if [ -f extensions/vscode/package.json ]; then
|
||||
echo "exists=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "exists=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
working-directory: .
|
||||
|
||||
- name: Setup Node.js 20
|
||||
if: steps.check-ext.outputs.exists == 'true'
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: extensions/vscode/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.check-ext.outputs.exists == 'true'
|
||||
run: npm ci
|
||||
|
||||
- name: TypeScript type-check
|
||||
if: steps.check-ext.outputs.exists == 'true'
|
||||
run: npx tsc --noEmit
|
||||
|
||||
- name: Run tests (if present)
|
||||
if: steps.check-ext.outputs.exists == 'true'
|
||||
run: npm test --if-present
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 12: Website - Build check
|
||||
# ---------------------------------------------------------------------------
|
||||
website-check:
|
||||
name: "Website: Build Check"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Check if website directory exists
|
||||
id: check-website
|
||||
run: |
|
||||
if [ -f website/package.json ]; then
|
||||
echo "exists=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "exists=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Setup Node.js 20
|
||||
if: steps.check-website.outputs.exists == 'true'
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: website/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.check-website.outputs.exists == 'true'
|
||||
working-directory: website
|
||||
run: npm ci
|
||||
|
||||
- name: Build website
|
||||
if: steps.check-website.outputs.exists == 'true'
|
||||
working-directory: website
|
||||
run: npm run build
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 13: Universal Search Eval (gated on secrets)
|
||||
# ---------------------------------------------------------------------------
|
||||
universal-search-eval:
|
||||
name: "Quality: Universal Search Eval"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [api-server-build]
|
||||
if: ${{ secrets.EVAL_API_KEY != '' && vars.EVAL_BASE_URL != '' }}
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Universal Search Eval (thresholded)
|
||||
env:
|
||||
EVAL_API_KEY: ${{ secrets.EVAL_API_KEY }}
|
||||
EVAL_BASE_URL: ${{ vars.EVAL_BASE_URL }}
|
||||
EVAL_K: 1,3,5,10
|
||||
EVAL_MIN_MRR: 0.35
|
||||
EVAL_MIN_RECALL: 0.6
|
||||
EVAL_MIN_WEIGHTED_MRR: 0.4
|
||||
EVAL_MIN_WEIGHTED_RECALL: 0.65
|
||||
run: npm run eval:universal-search
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 14: OpenAPI spec validation (shared script)
|
||||
# ---------------------------------------------------------------------------
|
||||
openapi-validation:
|
||||
name: "Quality: OpenAPI Route Coverage"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install API server dependencies
|
||||
working-directory: api-server
|
||||
run: npm ci
|
||||
|
||||
- name: Install root dependencies (for script)
|
||||
run: |
|
||||
if [ -f package.json ]; then
|
||||
npm ci --ignore-scripts 2>/dev/null || true
|
||||
fi
|
||||
working-directory: .
|
||||
|
||||
- name: Validate OpenAPI route coverage
|
||||
run: npx tsx scripts/validate-openapi-routes.ts
|
||||
working-directory: .
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Gate summary (all critical checks must pass)
|
||||
# ---------------------------------------------------------------------------
|
||||
ci-gate:
|
||||
name: "CI Gate (all checks)"
|
||||
runs-on: ubuntu-latest
|
||||
if: always()
|
||||
needs:
|
||||
- core-lint
|
||||
- core-build-test
|
||||
- redaction-gate
|
||||
- search-relevance-gate
|
||||
- api-server-lint
|
||||
- api-server-build
|
||||
- api-server-migration-check
|
||||
- api-server-tests
|
||||
- api-server-service-tests
|
||||
- api-server-integration-safe
|
||||
- api-server-smoke-test
|
||||
steps:
|
||||
- name: Check all gates
|
||||
run: |
|
||||
echo "Checking all AITM CI gate results..."
|
||||
echo "core-lint: ${{ needs.core-lint.result }}"
|
||||
echo "core-build-test: ${{ needs.core-build-test.result }}"
|
||||
echo "redaction-gate: ${{ needs.redaction-gate.result }}"
|
||||
echo "search-relevance-gate: ${{ needs.search-relevance-gate.result }}"
|
||||
echo "api-server-lint: ${{ needs.api-server-lint.result }}"
|
||||
echo "api-server-build: ${{ needs.api-server-build.result }}"
|
||||
echo "api-server-migration-check: ${{ needs.api-server-migration-check.result }}"
|
||||
echo "api-server-tests: ${{ needs.api-server-tests.result }}"
|
||||
echo "api-server-service-tests: ${{ needs.api-server-service-tests.result }}"
|
||||
echo "api-server-integration-safe: ${{ needs.api-server-integration-safe.result }}"
|
||||
echo "api-server-smoke-test: ${{ needs.api-server-smoke-test.result }}"
|
||||
|
||||
FAILED=false
|
||||
for result in \
|
||||
"${{ needs.core-lint.result }}" \
|
||||
"${{ needs.core-build-test.result }}" \
|
||||
"${{ needs.redaction-gate.result }}" \
|
||||
"${{ needs.search-relevance-gate.result }}" \
|
||||
"${{ needs.api-server-lint.result }}" \
|
||||
"${{ needs.api-server-build.result }}" \
|
||||
"${{ needs.api-server-migration-check.result }}" \
|
||||
"${{ needs.api-server-tests.result }}" \
|
||||
"${{ needs.api-server-service-tests.result }}" \
|
||||
"${{ needs.api-server-integration-safe.result }}" \
|
||||
"${{ needs.api-server-smoke-test.result }}"; do
|
||||
if [ "$result" != "success" ]; then
|
||||
FAILED=true
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$FAILED" = "true" ]; then
|
||||
echo "FAIL: One or more AITM CI gates did not pass."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "All AITM CI gates passed."
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Release (only on tag push, after all jobs pass)
|
||||
# ---------------------------------------------------------------------------
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
|
||||
needs: [ci-gate]
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Download core build artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: core-lib
|
||||
path: lib/
|
||||
|
||||
- name: Extract version from package.json
|
||||
id: pkg-version
|
||||
run: echo "version=$(node -p "require('./package.json').version")" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: v${{ steps.pkg-version.outputs.version }}
|
||||
generate_release_notes: true
|
||||
|
||||
- name: Publish to npm
|
||||
run: npm publish --access public
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
673
aitimemachine/.github/workflows/deploy.yml
vendored
Normal file
673
aitimemachine/.github/workflows/deploy.yml
vendored
Normal file
@ -0,0 +1,673 @@
|
||||
# =============================================================================
|
||||
# Deploy AITimeMachine - API Server + Workers
|
||||
# =============================================================================
|
||||
# Triggered by:
|
||||
# - Push to main (auto-deploy to staging, then production with approval)
|
||||
# - Version tag (auto-deploy to production)
|
||||
# - Manual workflow_dispatch
|
||||
#
|
||||
# Strategy:
|
||||
# - Rolling deployment with health check validation
|
||||
# - Automatic rollback on health check failure
|
||||
# - Pre-deploy gate: build + test + migration dry-run
|
||||
# - Post-deploy gate: smoke tests
|
||||
# =============================================================================
|
||||
name: Deploy AITM
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
tags: ["v*"]
|
||||
paths:
|
||||
- "api-server/**"
|
||||
- "drizzle/**"
|
||||
- "src/**"
|
||||
- ".github/workflows/deploy.yml"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
environment:
|
||||
description: "Target environment"
|
||||
type: choice
|
||||
options:
|
||||
- staging
|
||||
- production
|
||||
default: staging
|
||||
skip_tests:
|
||||
description: "Skip pre-deploy tests (emergency only)"
|
||||
type: boolean
|
||||
default: false
|
||||
deploy_workers:
|
||||
description: "Also deploy background workers"
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
concurrency:
|
||||
group: deploy-aitm-${{ github.event.inputs.environment || (startsWith(github.ref, 'refs/tags/v') && 'production') || 'staging' }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
NODE_VERSION: "20"
|
||||
DOCKER_REGISTRY: ghcr.io
|
||||
DOCKER_IMAGE_API: ghcr.io/${{ github.repository }}/aitm-api
|
||||
HEALTH_CHECK_RETRIES: 15
|
||||
HEALTH_CHECK_INTERVAL: 10
|
||||
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# Determine deployment target
|
||||
# ---------------------------------------------------------------------------
|
||||
resolve-environment:
|
||||
name: Resolve Environment
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 2
|
||||
outputs:
|
||||
environment: ${{ steps.resolve.outputs.environment }}
|
||||
is_production: ${{ steps.resolve.outputs.is_production }}
|
||||
image_tag: ${{ steps.resolve.outputs.image_tag }}
|
||||
deploy_workers: ${{ steps.resolve.outputs.deploy_workers }}
|
||||
steps:
|
||||
- name: Resolve deployment environment
|
||||
id: resolve
|
||||
run: |
|
||||
if [ -n "${{ github.event.inputs.environment }}" ]; then
|
||||
ENV="${{ github.event.inputs.environment }}"
|
||||
elif [[ "${{ github.ref }}" == refs/tags/v* ]]; then
|
||||
ENV="production"
|
||||
else
|
||||
ENV="staging"
|
||||
fi
|
||||
|
||||
IS_PROD="false"
|
||||
if [ "$ENV" = "production" ]; then
|
||||
IS_PROD="true"
|
||||
fi
|
||||
|
||||
# Image tag
|
||||
if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
|
||||
IMAGE_TAG="${{ github.ref_name }}"
|
||||
else
|
||||
IMAGE_TAG="sha-$(echo ${{ github.sha }} | cut -c1-7)"
|
||||
fi
|
||||
|
||||
# Workers flag
|
||||
DEPLOY_WORKERS="${{ github.event.inputs.deploy_workers || 'true' }}"
|
||||
|
||||
echo "environment=$ENV" >> "$GITHUB_OUTPUT"
|
||||
echo "is_production=$IS_PROD" >> "$GITHUB_OUTPUT"
|
||||
echo "image_tag=$IMAGE_TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "deploy_workers=$DEPLOY_WORKERS" >> "$GITHUB_OUTPUT"
|
||||
|
||||
echo "### AITM Deploy Configuration" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Setting | Value |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|---------|-------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Environment | $ENV |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Image Tag | $IMAGE_TAG |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Deploy Workers | $DEPLOY_WORKERS |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Ref | ${{ github.sha }} |" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pre-deploy checks
|
||||
# ---------------------------------------------------------------------------
|
||||
pre-deploy-checks:
|
||||
name: Pre-Deploy Checks
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
needs: [resolve-environment]
|
||||
if: ${{ github.event.inputs.skip_tests != 'true' }}
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: TypeScript type check
|
||||
run: npx tsc --noEmit
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Run tests
|
||||
run: npm test --if-present
|
||||
env:
|
||||
NODE_ENV: test
|
||||
|
||||
- name: Validate database migrations
|
||||
run: |
|
||||
echo "Checking drizzle migration files..."
|
||||
if [ -d "drizzle" ]; then
|
||||
MIGRATION_COUNT=$(ls drizzle/*.sql 2>/dev/null | wc -l)
|
||||
echo "Found $MIGRATION_COUNT migration file(s)."
|
||||
|
||||
# Verify migration file syntax (basic SQL parse check)
|
||||
for f in drizzle/*.sql; do
|
||||
if [ -f "$f" ]; then
|
||||
echo "Validating: $f"
|
||||
# Check for common SQL issues
|
||||
if grep -qi "DROP TABLE" "$f" && [ "${{ needs.resolve-environment.outputs.is_production }}" = "true" ]; then
|
||||
echo "WARNING: DROP TABLE detected in $f - review carefully for production deploy"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
else
|
||||
echo "No drizzle migration directory found."
|
||||
fi
|
||||
|
||||
- name: Check for breaking API changes
|
||||
run: |
|
||||
echo "Checking for potential breaking API changes..."
|
||||
if [ -f "docs/openapi.yaml" ]; then
|
||||
CHANGED=$(git diff --name-only HEAD~1 HEAD -- 'docs/openapi.yaml' 2>/dev/null || true)
|
||||
if [ -n "$CHANGED" ]; then
|
||||
echo "OpenAPI spec has been modified. Review for breaking changes."
|
||||
git diff HEAD~1 HEAD -- 'docs/openapi.yaml' | head -100
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check for removed route handlers
|
||||
REMOVED_ROUTES=$(git diff HEAD~1 HEAD -- 'src/**/*.ts' | grep "^-.*\(app\|router\)\.\(get\|post\|put\|patch\|delete\)" 2>/dev/null || true)
|
||||
if [ -n "$REMOVED_ROUTES" ]; then
|
||||
echo "WARNING: Potentially removed route handlers:"
|
||||
echo "$REMOVED_ROUTES"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Build Docker image
|
||||
# ---------------------------------------------------------------------------
|
||||
build-image:
|
||||
name: Build Docker Image
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: [resolve-environment, pre-deploy-checks]
|
||||
if: always() && (needs.pre-deploy-checks.result == 'success' || needs.pre-deploy-checks.result == 'skipped')
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.DOCKER_REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and push API server image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./api-server
|
||||
file: ./api-server/Dockerfile
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.DOCKER_IMAGE_API }}:${{ needs.resolve-environment.outputs.image_tag }}
|
||||
${{ env.DOCKER_IMAGE_API }}:${{ needs.resolve-environment.outputs.environment }}-latest
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
labels: |
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
org.opencontainers.image.revision=${{ github.sha }}
|
||||
deploy.environment=${{ needs.resolve-environment.outputs.environment }}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deploy to staging
|
||||
# ---------------------------------------------------------------------------
|
||||
deploy-staging:
|
||||
name: Deploy to Staging
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: [resolve-environment, build-image]
|
||||
if: needs.resolve-environment.outputs.environment == 'staging'
|
||||
environment:
|
||||
name: staging
|
||||
url: ${{ vars.AITM_STAGING_URL }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Record previous deployment version
|
||||
id: previous
|
||||
run: |
|
||||
PREV_TAG="${{ vars.CURRENT_DEPLOY_TAG || 'none' }}"
|
||||
echo "previous_tag=$PREV_TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "Previous deployment tag: $PREV_TAG"
|
||||
|
||||
- name: Run database migrations
|
||||
run: |
|
||||
echo "Running drizzle migrations on staging database..."
|
||||
docker run --rm \
|
||||
-e DATABASE_URL="${{ secrets.AITM_DATABASE_URL }}" \
|
||||
${{ env.DOCKER_IMAGE_API }}:${{ needs.resolve-environment.outputs.image_tag }} \
|
||||
npm run db:migrate
|
||||
echo "Migrations complete."
|
||||
|
||||
- name: Deploy API server
|
||||
run: |
|
||||
echo "Deploying AITM API to staging..."
|
||||
IMAGE_TAG="${{ needs.resolve-environment.outputs.image_tag }}"
|
||||
|
||||
if [ -n "${{ secrets.DEPLOY_SSH_KEY }}" ]; then
|
||||
echo "${{ secrets.DEPLOY_SSH_KEY }}" > /tmp/deploy_key
|
||||
chmod 600 /tmp/deploy_key
|
||||
ssh -o StrictHostKeyChecking=no -i /tmp/deploy_key \
|
||||
${{ secrets.STAGING_SSH_USER }}@${{ secrets.STAGING_SSH_HOST }} \
|
||||
"docker pull ${{ env.DOCKER_IMAGE_API }}:$IMAGE_TAG && \
|
||||
cd /opt/aitm && \
|
||||
API_IMAGE=${{ env.DOCKER_IMAGE_API }}:$IMAGE_TAG \
|
||||
ENABLE_WORKERS=${{ needs.resolve-environment.outputs.deploy_workers == 'true' && 'true' || 'false' }} \
|
||||
RETENTION_CRON='${{ vars.AITM_RETENTION_CRON || '0 3 * * *' }}' \
|
||||
DELETE_CRON='${{ vars.AITM_DELETE_CRON || '*/5 * * * *' }}' \
|
||||
GC_CRON='${{ vars.AITM_GC_CRON || '0 4 * * 0' }}' \
|
||||
docker compose up -d --remove-orphans aitm-api"
|
||||
rm -f /tmp/deploy_key
|
||||
else
|
||||
echo "No SSH key configured. Using placeholder deployment."
|
||||
echo "Configure DEPLOY_SSH_KEY, STAGING_SSH_USER, and STAGING_SSH_HOST secrets."
|
||||
fi
|
||||
|
||||
- name: Deploy workers
|
||||
if: needs.resolve-environment.outputs.deploy_workers == 'true'
|
||||
run: |
|
||||
echo "Deploying AITM background workers to staging..."
|
||||
IMAGE_TAG="${{ needs.resolve-environment.outputs.image_tag }}"
|
||||
|
||||
if [ -n "${{ secrets.DEPLOY_SSH_KEY }}" ]; then
|
||||
echo "${{ secrets.DEPLOY_SSH_KEY }}" > /tmp/deploy_key
|
||||
chmod 600 /tmp/deploy_key
|
||||
|
||||
# Deploy delete-request worker
|
||||
ssh -o StrictHostKeyChecking=no -i /tmp/deploy_key \
|
||||
${{ secrets.STAGING_SSH_USER }}@${{ secrets.STAGING_SSH_HOST }} \
|
||||
"cd /opt/aitm && \
|
||||
API_IMAGE=${{ env.DOCKER_IMAGE_API }}:$IMAGE_TAG \
|
||||
ENABLE_WORKERS=true \
|
||||
DELETE_WORKER_ENABLED=true \
|
||||
RETENTION_WORKER_ENABLED=true \
|
||||
GC_WORKER_ENABLED=true \
|
||||
RETENTION_CRON='${{ vars.AITM_RETENTION_CRON || '0 3 * * *' }}' \
|
||||
DELETE_CRON='${{ vars.AITM_DELETE_CRON || '*/5 * * * *' }}' \
|
||||
GC_CRON='${{ vars.AITM_GC_CRON || '0 4 * * 0' }}' \
|
||||
docker compose up -d --remove-orphans aitm-worker-delete aitm-worker-retention"
|
||||
rm -f /tmp/deploy_key
|
||||
fi
|
||||
|
||||
- name: Health check - API server
|
||||
id: health_api
|
||||
run: |
|
||||
API_URL="${{ vars.AITM_STAGING_URL || 'http://localhost:3001' }}"
|
||||
echo "Running health checks against $API_URL..."
|
||||
|
||||
SUCCESS=false
|
||||
for i in $(seq 1 ${{ env.HEALTH_CHECK_RETRIES }}); do
|
||||
echo "Health check attempt $i/${{ env.HEALTH_CHECK_RETRIES }}..."
|
||||
HTTP_CODE=$(curl -sf -o /dev/null -w "%{http_code}" "$API_URL/health" 2>/dev/null || echo "000")
|
||||
|
||||
if [ "$HTTP_CODE" = "200" ]; then
|
||||
echo "API health check PASSED (HTTP $HTTP_CODE)"
|
||||
SUCCESS=true
|
||||
break
|
||||
fi
|
||||
|
||||
echo "API not ready (HTTP $HTTP_CODE). Waiting ${{ env.HEALTH_CHECK_INTERVAL }}s..."
|
||||
sleep ${{ env.HEALTH_CHECK_INTERVAL }}
|
||||
done
|
||||
|
||||
if [ "$SUCCESS" = "false" ]; then
|
||||
echo "health_passed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "API health check FAILED after ${{ env.HEALTH_CHECK_RETRIES }} attempts."
|
||||
else
|
||||
echo "health_passed=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Health check - managed workers
|
||||
if: needs.resolve-environment.outputs.deploy_workers == 'true'
|
||||
id: health_workers
|
||||
run: |
|
||||
API_URL="${{ vars.AITM_STAGING_URL || 'http://localhost:3001' }}"
|
||||
INTERNAL_SECRET="${{ secrets.AITM_INTERNAL_SECRET }}"
|
||||
|
||||
if [ -z "$INTERNAL_SECRET" ]; then
|
||||
echo "health_passed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "AITM_INTERNAL_SECRET is required for worker status checks."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Checking managed worker scheduler status..."
|
||||
BODY=$(curl -sf -H "x-internal-secret: $INTERNAL_SECRET" "$API_URL/v1/workers/status" || true)
|
||||
if [ -z "$BODY" ]; then
|
||||
echo "health_passed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "Worker status endpoint returned empty response."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "$BODY"
|
||||
if echo "$BODY" | grep -q '"managed":[[:space:]]*true' && \
|
||||
echo "$BODY" | grep -q '"name":"retention"' && \
|
||||
echo "$BODY" | grep -q '"name":"delete"'; then
|
||||
echo "health_passed=true" >> "$GITHUB_OUTPUT"
|
||||
echo "Managed workers are active."
|
||||
else
|
||||
echo "health_passed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "Managed worker scheduler is not healthy."
|
||||
fi
|
||||
|
||||
- name: Rollback on failure
|
||||
if: steps.health_api.outputs.health_passed != 'true' || (needs.resolve-environment.outputs.deploy_workers == 'true' && steps.health_workers.outputs.health_passed != 'true')
|
||||
run: |
|
||||
PREV_TAG="${{ steps.previous.outputs.previous_tag }}"
|
||||
echo "ROLLING BACK AITM to previous version: $PREV_TAG"
|
||||
|
||||
if [ "$PREV_TAG" = "none" ]; then
|
||||
echo "No previous version to roll back to. Manual intervention required."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -n "${{ secrets.DEPLOY_SSH_KEY }}" ]; then
|
||||
echo "${{ secrets.DEPLOY_SSH_KEY }}" > /tmp/deploy_key
|
||||
chmod 600 /tmp/deploy_key
|
||||
ssh -o StrictHostKeyChecking=no -i /tmp/deploy_key \
|
||||
${{ secrets.STAGING_SSH_USER }}@${{ secrets.STAGING_SSH_HOST }} \
|
||||
"cd /opt/aitm && \
|
||||
API_IMAGE=${{ env.DOCKER_IMAGE_API }}:$PREV_TAG \
|
||||
docker compose up -d --remove-orphans"
|
||||
rm -f /tmp/deploy_key
|
||||
fi
|
||||
|
||||
echo "Rollback complete. Failing the job."
|
||||
exit 1
|
||||
|
||||
- name: Update deployment tag
|
||||
if: steps.health_api.outputs.health_passed == 'true' && (needs.resolve-environment.outputs.deploy_workers != 'true' || steps.health_workers.outputs.health_passed == 'true')
|
||||
run: |
|
||||
echo "Staging deployment successful. Tag: ${{ needs.resolve-environment.outputs.image_tag }}"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deploy to production
|
||||
# ---------------------------------------------------------------------------
|
||||
deploy-production:
|
||||
name: Deploy to Production
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
needs: [resolve-environment, build-image]
|
||||
if: needs.resolve-environment.outputs.environment == 'production'
|
||||
environment:
|
||||
name: production
|
||||
url: ${{ vars.AITM_PROD_URL }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Record previous deployment version
|
||||
id: previous
|
||||
run: |
|
||||
PREV_TAG="${{ vars.CURRENT_DEPLOY_TAG || 'none' }}"
|
||||
echo "previous_tag=$PREV_TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "Previous production deployment tag: $PREV_TAG"
|
||||
|
||||
- name: Pre-deploy database backup
|
||||
run: |
|
||||
echo "Creating pre-deploy Neon database backup..."
|
||||
# Neon: create a branch as a point-in-time backup
|
||||
# neon branches create --name "pre-deploy-$(date +%Y%m%d-%H%M%S)" --project-id $PROJECT_ID
|
||||
echo "Backup step complete (delegate to Neon branch or pg_dump)."
|
||||
|
||||
- name: Run database migrations
|
||||
run: |
|
||||
echo "Running drizzle migrations on production database..."
|
||||
docker run --rm \
|
||||
-e DATABASE_URL="${{ secrets.AITM_DATABASE_URL }}" \
|
||||
${{ env.DOCKER_IMAGE_API }}:${{ needs.resolve-environment.outputs.image_tag }} \
|
||||
npm run db:migrate
|
||||
echo "Migrations complete."
|
||||
|
||||
- name: Deploy API server
|
||||
run: |
|
||||
echo "Deploying AITM API to production..."
|
||||
IMAGE_TAG="${{ needs.resolve-environment.outputs.image_tag }}"
|
||||
|
||||
if [ -n "${{ secrets.DEPLOY_SSH_KEY }}" ]; then
|
||||
echo "${{ secrets.DEPLOY_SSH_KEY }}" > /tmp/deploy_key
|
||||
chmod 600 /tmp/deploy_key
|
||||
ssh -o StrictHostKeyChecking=no -i /tmp/deploy_key \
|
||||
${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }} \
|
||||
"docker pull ${{ env.DOCKER_IMAGE_API }}:$IMAGE_TAG && \
|
||||
cd /opt/aitm && \
|
||||
API_IMAGE=${{ env.DOCKER_IMAGE_API }}:$IMAGE_TAG \
|
||||
ENABLE_WORKERS=${{ needs.resolve-environment.outputs.deploy_workers == 'true' && 'true' || 'false' }} \
|
||||
RETENTION_CRON='${{ vars.AITM_RETENTION_CRON || '0 3 * * *' }}' \
|
||||
DELETE_CRON='${{ vars.AITM_DELETE_CRON || '*/5 * * * *' }}' \
|
||||
GC_CRON='${{ vars.AITM_GC_CRON || '0 4 * * 0' }}' \
|
||||
docker compose up -d --remove-orphans aitm-api"
|
||||
rm -f /tmp/deploy_key
|
||||
else
|
||||
echo "No SSH key configured. Using placeholder deployment."
|
||||
fi
|
||||
|
||||
- name: Deploy workers
|
||||
if: needs.resolve-environment.outputs.deploy_workers == 'true'
|
||||
run: |
|
||||
echo "Deploying AITM background workers to production..."
|
||||
IMAGE_TAG="${{ needs.resolve-environment.outputs.image_tag }}"
|
||||
|
||||
if [ -n "${{ secrets.DEPLOY_SSH_KEY }}" ]; then
|
||||
echo "${{ secrets.DEPLOY_SSH_KEY }}" > /tmp/deploy_key
|
||||
chmod 600 /tmp/deploy_key
|
||||
ssh -o StrictHostKeyChecking=no -i /tmp/deploy_key \
|
||||
${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }} \
|
||||
"cd /opt/aitm && \
|
||||
API_IMAGE=${{ env.DOCKER_IMAGE_API }}:$IMAGE_TAG \
|
||||
ENABLE_WORKERS=true \
|
||||
DELETE_WORKER_ENABLED=true \
|
||||
RETENTION_WORKER_ENABLED=true \
|
||||
GC_WORKER_ENABLED=true \
|
||||
RETENTION_CRON='${{ vars.AITM_RETENTION_CRON || '0 3 * * *' }}' \
|
||||
DELETE_CRON='${{ vars.AITM_DELETE_CRON || '*/5 * * * *' }}' \
|
||||
GC_CRON='${{ vars.AITM_GC_CRON || '0 4 * * 0' }}' \
|
||||
docker compose up -d --remove-orphans aitm-worker-delete aitm-worker-retention"
|
||||
rm -f /tmp/deploy_key
|
||||
fi
|
||||
|
||||
- name: Health check - API server
|
||||
id: health_api
|
||||
run: |
|
||||
API_URL="${{ vars.AITM_PROD_URL || 'https://timemachine-api.gitgram.app' }}"
|
||||
echo "Running production health checks against $API_URL..."
|
||||
|
||||
SUCCESS=false
|
||||
for i in $(seq 1 ${{ env.HEALTH_CHECK_RETRIES }}); do
|
||||
echo "Health check attempt $i/${{ env.HEALTH_CHECK_RETRIES }}..."
|
||||
HTTP_CODE=$(curl -sf -o /dev/null -w "%{http_code}" "$API_URL/health" 2>/dev/null || echo "000")
|
||||
|
||||
if [ "$HTTP_CODE" = "200" ]; then
|
||||
echo "API health check PASSED (HTTP $HTTP_CODE)"
|
||||
SUCCESS=true
|
||||
break
|
||||
fi
|
||||
|
||||
echo "API not ready (HTTP $HTTP_CODE). Waiting ${{ env.HEALTH_CHECK_INTERVAL }}s..."
|
||||
sleep ${{ env.HEALTH_CHECK_INTERVAL }}
|
||||
done
|
||||
|
||||
if [ "$SUCCESS" = "false" ]; then
|
||||
echo "health_passed=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "health_passed=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Health check - managed workers
|
||||
if: needs.resolve-environment.outputs.deploy_workers == 'true'
|
||||
id: health_workers
|
||||
run: |
|
||||
API_URL="${{ vars.AITM_PROD_URL || 'https://timemachine-api.gitgram.app' }}"
|
||||
INTERNAL_SECRET="${{ secrets.AITM_INTERNAL_SECRET }}"
|
||||
|
||||
if [ -z "$INTERNAL_SECRET" ]; then
|
||||
echo "health_passed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "AITM_INTERNAL_SECRET is required for worker status checks."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Checking managed worker scheduler status..."
|
||||
BODY=$(curl -sf -H "x-internal-secret: $INTERNAL_SECRET" "$API_URL/v1/workers/status" || true)
|
||||
if [ -z "$BODY" ]; then
|
||||
echo "health_passed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "Worker status endpoint returned empty response."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "$BODY"
|
||||
if echo "$BODY" | grep -q '"managed":[[:space:]]*true' && \
|
||||
echo "$BODY" | grep -q '"name":"retention"' && \
|
||||
echo "$BODY" | grep -q '"name":"delete"'; then
|
||||
echo "health_passed=true" >> "$GITHUB_OUTPUT"
|
||||
echo "Managed workers are active."
|
||||
else
|
||||
echo "health_passed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "Managed worker scheduler is not healthy."
|
||||
fi
|
||||
|
||||
- name: Automatic rollback on failure
|
||||
if: steps.health_api.outputs.health_passed != 'true' || (needs.resolve-environment.outputs.deploy_workers == 'true' && steps.health_workers.outputs.health_passed != 'true')
|
||||
run: |
|
||||
PREV_TAG="${{ steps.previous.outputs.previous_tag }}"
|
||||
echo "PRODUCTION ROLLBACK to version: $PREV_TAG"
|
||||
|
||||
if [ "$PREV_TAG" = "none" ]; then
|
||||
echo "No previous version to roll back to. MANUAL INTERVENTION REQUIRED."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -n "${{ secrets.DEPLOY_SSH_KEY }}" ]; then
|
||||
echo "${{ secrets.DEPLOY_SSH_KEY }}" > /tmp/deploy_key
|
||||
chmod 600 /tmp/deploy_key
|
||||
ssh -o StrictHostKeyChecking=no -i /tmp/deploy_key \
|
||||
${{ secrets.PROD_SSH_USER }}@${{ secrets.PROD_SSH_HOST }} \
|
||||
"cd /opt/aitm && \
|
||||
API_IMAGE=${{ env.DOCKER_IMAGE_API }}:$PREV_TAG \
|
||||
docker compose up -d --remove-orphans"
|
||||
rm -f /tmp/deploy_key
|
||||
fi
|
||||
|
||||
echo "Rollback complete. Failing the job to alert the team."
|
||||
exit 1
|
||||
|
||||
- name: Update deployment tag
|
||||
if: steps.health_api.outputs.health_passed == 'true' && (needs.resolve-environment.outputs.deploy_workers != 'true' || steps.health_workers.outputs.health_passed == 'true')
|
||||
run: |
|
||||
echo "Production deployment successful. Tag: ${{ needs.resolve-environment.outputs.image_tag }}"
|
||||
|
||||
- name: Notify deployment success
|
||||
if: steps.health_api.outputs.health_passed == 'true' && (needs.resolve-environment.outputs.deploy_workers != 'true' || steps.health_workers.outputs.health_passed == 'true')
|
||||
run: |
|
||||
echo "### AITM Production Deployment Complete" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- **Image Tag:** ${{ needs.resolve-environment.outputs.image_tag }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- **Commit:** ${{ github.sha }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- **Workers deployed:** ${{ needs.resolve-environment.outputs.deploy_workers }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- **Deployed at:** $(date -u +'%Y-%m-%d %H:%M:%S UTC')" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
if [ -n "${{ secrets.SLACK_WEBHOOK_URL }}" ]; then
|
||||
curl -sf -X POST "${{ secrets.SLACK_WEBHOOK_URL }}" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"text\":\"AITM production deploy complete: ${{ needs.resolve-environment.outputs.image_tag }}\"}" \
|
||||
|| echo "Slack notification failed (non-blocking)"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Post-deploy smoke tests
|
||||
# ---------------------------------------------------------------------------
|
||||
smoke-tests:
|
||||
name: Post-Deploy Smoke Tests
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
needs: [resolve-environment, deploy-staging, deploy-production]
|
||||
if: always() && (needs.deploy-staging.result == 'success' || needs.deploy-production.result == 'success')
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run AITM smoke tests
|
||||
run: |
|
||||
ENV="${{ needs.resolve-environment.outputs.environment }}"
|
||||
|
||||
if [ "$ENV" = "production" ]; then
|
||||
API_URL="${{ vars.AITM_PROD_URL || 'https://timemachine-api.gitgram.app' }}"
|
||||
else
|
||||
API_URL="${{ vars.AITM_STAGING_URL || 'https://api.aitimemachine.dev' }}"
|
||||
fi
|
||||
|
||||
echo "Running AITM smoke tests for $ENV..."
|
||||
echo "API: $API_URL"
|
||||
|
||||
FAILURES=0
|
||||
|
||||
# Test 1: Health endpoint
|
||||
echo ""
|
||||
echo "--- Test 1: Health endpoint ---"
|
||||
HEALTH_CODE=$(curl -sf -o /dev/null -w "%{http_code}" "$API_URL/health" 2>/dev/null || echo "000")
|
||||
if [ "$HEALTH_CODE" = "200" ]; then
|
||||
echo "PASS: Health endpoint returned 200"
|
||||
else
|
||||
echo "FAIL: Health endpoint returned $HEALTH_CODE"
|
||||
FAILURES=$((FAILURES + 1))
|
||||
fi
|
||||
|
||||
# Test 2: Sessions endpoint (expect 401 unauthenticated, not 500)
|
||||
echo ""
|
||||
echo "--- Test 2: Sessions endpoint ---"
|
||||
SESSIONS_CODE=$(curl -sf -o /dev/null -w "%{http_code}" "$API_URL/api/sessions" 2>/dev/null || echo "000")
|
||||
if [ "$SESSIONS_CODE" != "500" ] && [ "$SESSIONS_CODE" != "000" ]; then
|
||||
echo "PASS: Sessions endpoint returned $SESSIONS_CODE (not 500)"
|
||||
else
|
||||
echo "FAIL: Sessions endpoint returned $SESSIONS_CODE"
|
||||
FAILURES=$((FAILURES + 1))
|
||||
fi
|
||||
|
||||
# Test 3: Sync endpoint (expect 401 or 400, not 500)
|
||||
echo ""
|
||||
echo "--- Test 3: Sync endpoint ---"
|
||||
SYNC_CODE=$(curl -sf -o /dev/null -w "%{http_code}" "$API_URL/api/sync" \
|
||||
-X POST -H "Content-Type: application/json" -d '{}' 2>/dev/null || echo "000")
|
||||
if [ "$SYNC_CODE" != "500" ] && [ "$SYNC_CODE" != "000" ]; then
|
||||
echo "PASS: Sync endpoint returned $SYNC_CODE (not 500)"
|
||||
else
|
||||
echo "FAIL: Sync endpoint returned $SYNC_CODE"
|
||||
FAILURES=$((FAILURES + 1))
|
||||
fi
|
||||
|
||||
# Test 4: Keys endpoint (expect 401, not 500)
|
||||
echo ""
|
||||
echo "--- Test 4: Keys endpoint ---"
|
||||
KEYS_CODE=$(curl -sf -o /dev/null -w "%{http_code}" "$API_URL/api/keys" 2>/dev/null || echo "000")
|
||||
if [ "$KEYS_CODE" != "500" ] && [ "$KEYS_CODE" != "000" ]; then
|
||||
echo "PASS: Keys endpoint returned $KEYS_CODE (not 500)"
|
||||
else
|
||||
echo "FAIL: Keys endpoint returned $KEYS_CODE"
|
||||
FAILURES=$((FAILURES + 1))
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "### AITM Smoke Test Results ($ENV)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- API URL: $API_URL" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Failures: $FAILURES" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
if [ "$FAILURES" -gt 0 ]; then
|
||||
echo "SMOKE TESTS FAILED: $FAILURES failure(s)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "All AITM smoke tests passed."
|
||||
267
aitimemachine/.github/workflows/pr-check.yml
vendored
Normal file
267
aitimemachine/.github/workflows/pr-check.yml
vendored
Normal file
@ -0,0 +1,267 @@
|
||||
# =============================================================================
|
||||
# AITimeMachine PR Check - Fast feedback for pull requests
|
||||
# =============================================================================
|
||||
# Lightweight checks that run on every PR. The full CI pipeline (ci.yml) also
|
||||
# runs on PRs, but this workflow provides quicker initial feedback on each
|
||||
# component independently.
|
||||
# =============================================================================
|
||||
name: PR Check
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
|
||||
concurrency:
|
||||
group: aitm-pr-${{ github.head_ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# Core package quick checks
|
||||
# ---------------------------------------------------------------------------
|
||||
core-check:
|
||||
name: "Core: Build, Test & Quality Gates"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: ESLint
|
||||
run: npm run lint
|
||||
|
||||
- name: TypeScript type-check
|
||||
run: npx tsc --noEmit
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
|
||||
- name: Redaction quality gate
|
||||
env:
|
||||
AITM_REDACTION_MIN_PRECISION: "0.80"
|
||||
AITM_REDACTION_MIN_RECALL: "0.95"
|
||||
AITM_REDACTION_MIN_F1: "0.88"
|
||||
run: npm run test:redaction-gate
|
||||
|
||||
- name: Search relevance gate
|
||||
env:
|
||||
AITM_SEARCH_RELEVANCE_MIN_TOP1: "0.65"
|
||||
AITM_SEARCH_RELEVANCE_MIN_MRR: "0.78"
|
||||
AITM_SEARCH_RELEVANCE_MIN_RECALL_AT3: "0.95"
|
||||
run: npm run test:search-relevance-gate
|
||||
|
||||
- name: Universal Search Eval (thresholded)
|
||||
if: ${{ secrets.EVAL_API_KEY != '' && vars.EVAL_BASE_URL != '' }}
|
||||
env:
|
||||
EVAL_API_KEY: ${{ secrets.EVAL_API_KEY }}
|
||||
EVAL_BASE_URL: ${{ vars.EVAL_BASE_URL }}
|
||||
EVAL_K: 1,3,5,10
|
||||
EVAL_MIN_MRR: 0.35
|
||||
EVAL_MIN_RECALL: 0.6
|
||||
EVAL_MIN_WEIGHTED_MRR: 0.4
|
||||
EVAL_MIN_WEIGHTED_RECALL: 0.65
|
||||
run: npm run eval:universal-search
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# API Server quick checks
|
||||
# ---------------------------------------------------------------------------
|
||||
api-server-check:
|
||||
name: "API Server: Build, Type Check & Tests"
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: TypeScript type-check
|
||||
run: npx tsc --noEmit
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Service tests (no external deps)
|
||||
run: npx vitest run tests/services --passWithNoTests
|
||||
env:
|
||||
AITM_TEST_NO_LISTEN: "1"
|
||||
NODE_ENV: test
|
||||
|
||||
- name: Integration-safe tests
|
||||
run: npm run test:integration:safe
|
||||
env:
|
||||
NODE_ENV: test
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Drizzle migration check
|
||||
# ---------------------------------------------------------------------------
|
||||
migration-check:
|
||||
name: "API Server: Migration Files Check"
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api-server
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Validate drizzle migration files
|
||||
run: |
|
||||
echo "Checking drizzle migration files..."
|
||||
|
||||
DRIZZLE_DIR="drizzle"
|
||||
if [ -d "$DRIZZLE_DIR" ]; then
|
||||
MIGRATION_COUNT=$(find "$DRIZZLE_DIR" -name "*.sql" -not -path "*/meta/*" | wc -l)
|
||||
echo "Found $MIGRATION_COUNT migration file(s)."
|
||||
|
||||
for f in $(find "$DRIZZLE_DIR" -name "*.sql" -not -path "*/meta/*"); do
|
||||
echo "Validating: $f"
|
||||
if grep -qi "DROP TABLE" "$f"; then
|
||||
echo "WARNING: DROP TABLE detected in $f - review carefully"
|
||||
fi
|
||||
done
|
||||
else
|
||||
echo "No drizzle migration directory found."
|
||||
fi
|
||||
|
||||
- name: Drizzle schema check
|
||||
run: npx drizzle-kit check 2>&1 || echo "drizzle-kit check completed."
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# VS Code Extension check
|
||||
# ---------------------------------------------------------------------------
|
||||
extension-check:
|
||||
name: "Extension: Type Check"
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: extensions/vscode
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Check if extension directory exists
|
||||
id: check-ext
|
||||
run: |
|
||||
if [ -f extensions/vscode/package.json ]; then
|
||||
echo "exists=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "exists=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
working-directory: .
|
||||
|
||||
- name: Setup Node.js 20
|
||||
if: steps.check-ext.outputs.exists == 'true'
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: extensions/vscode/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.check-ext.outputs.exists == 'true'
|
||||
run: npm ci
|
||||
|
||||
- name: TypeScript type-check
|
||||
if: steps.check-ext.outputs.exists == 'true'
|
||||
run: npx tsc --noEmit
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Website check
|
||||
# ---------------------------------------------------------------------------
|
||||
website-check:
|
||||
name: "Website: Build Check"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Check if website directory exists
|
||||
id: check-website
|
||||
run: |
|
||||
if [ -f website/package.json ]; then
|
||||
echo "exists=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "exists=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Setup Node.js 20
|
||||
if: steps.check-website.outputs.exists == 'true'
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: website/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.check-website.outputs.exists == 'true'
|
||||
working-directory: website
|
||||
run: npm ci
|
||||
|
||||
- name: Build website
|
||||
if: steps.check-website.outputs.exists == 'true'
|
||||
working-directory: website
|
||||
run: npm run build
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OpenAPI validation
|
||||
# ---------------------------------------------------------------------------
|
||||
openapi-check:
|
||||
name: "Quality: OpenAPI Coverage"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: api-server/package-lock.json
|
||||
|
||||
- name: Install API server dependencies
|
||||
working-directory: api-server
|
||||
run: npm ci
|
||||
|
||||
- name: Install root dependencies (for script)
|
||||
run: |
|
||||
if [ -f package.json ]; then
|
||||
npm ci --ignore-scripts 2>/dev/null || true
|
||||
fi
|
||||
working-directory: .
|
||||
|
||||
- name: Validate OpenAPI route coverage
|
||||
run: npx tsx scripts/validate-openapi-routes.ts
|
||||
working-directory: .
|
||||
12
aitimemachine/.gitignore
vendored
Normal file
12
aitimemachine/.gitignore
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
node_modules/
|
||||
dist/
|
||||
lib/
|
||||
coverage/
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
*.log
|
||||
.DS_Store
|
||||
.aitimemachine/
|
||||
*.aitm
|
||||
.next/
|
||||
11
aitimemachine/.mcp.json
Normal file
11
aitimemachine/.mcp.json
Normal file
@ -0,0 +1,11 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"ai-time-machine": {
|
||||
"command": "node",
|
||||
"args": ["./mcp/dist/index.js"],
|
||||
"env": {
|
||||
"TM_DATA_DIR": "${HOME}/.aitimemachine-server"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
33
aitimemachine/.npmignore
Normal file
33
aitimemachine/.npmignore
Normal file
@ -0,0 +1,33 @@
|
||||
# Source (compiled output in lib/ is what gets published)
|
||||
src/
|
||||
tests/
|
||||
*.test.ts
|
||||
*.test.js
|
||||
*.spec.ts
|
||||
|
||||
# Development
|
||||
.aitimemachine/
|
||||
coverage/
|
||||
*.log
|
||||
.DS_Store
|
||||
*.aitm
|
||||
tsconfig.json
|
||||
vitest.config.*
|
||||
jest.config.*
|
||||
.eslintrc*
|
||||
|
||||
# Project files
|
||||
api-server/
|
||||
website/
|
||||
mcp/
|
||||
kilocode/
|
||||
gemini-cli/
|
||||
docs/
|
||||
.github/
|
||||
deploy/
|
||||
docker-compose*
|
||||
Dockerfile
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
244
aitimemachine/API.md
Normal file
244
aitimemachine/API.md
Normal file
@ -0,0 +1,244 @@
|
||||
# AITimeMachine API Reference
|
||||
|
||||
## TimeMachine Class
|
||||
|
||||
### Constructor
|
||||
```typescript
|
||||
new TimeMachine(projectPath: string)
|
||||
```
|
||||
|
||||
### Methods
|
||||
|
||||
#### `initialize(): Promise<void>`
|
||||
Initializes the time machine, setting up git repo and loading existing data.
|
||||
|
||||
#### `createSnapshot(filePath?: string): Promise<void>`
|
||||
Creates a timestamped snapshot of the current code state and conversation.
|
||||
|
||||
#### `revertToSnapshot(index: number): Promise<void>`
|
||||
Reverts to the snapshot at the given index, with user confirmation if configured.
|
||||
|
||||
#### `getSnapshots(): Snapshot[]`
|
||||
Returns array of all snapshots.
|
||||
|
||||
#### `getSnapshot(index: number): Snapshot | undefined`
|
||||
Returns a specific snapshot by index.
|
||||
|
||||
#### `logConversation(role: 'user' | 'assistant', message: string): void`
|
||||
Logs a conversation entry.
|
||||
|
||||
#### `getCurrentConversation(): ConversationEntry[]`
|
||||
Returns the current conversation log.
|
||||
|
||||
#### `getDiff(fromIndex: number, toIndex?: number): string`
|
||||
Returns a diff between the snapshot at fromIndex and toIndex (or current state if not specified).
|
||||
|
||||
#### `clearConversation(): void`
|
||||
Clears the conversation log.
|
||||
|
||||
#### `startWatching(): void`
|
||||
Starts file watching for automatic snapshots.
|
||||
|
||||
#### `stopWatching(): void`
|
||||
Stops file watching.
|
||||
|
||||
---
|
||||
|
||||
## MCP Tools
|
||||
|
||||
### Core Snapshot Tools
|
||||
|
||||
#### `create_snapshot`
|
||||
Create a timestamped snapshot of the current code state and conversation.
|
||||
- **Input**: `{ filePath?: string }`
|
||||
- **Output**: `"Snapshot created"`
|
||||
|
||||
#### `list_snapshots`
|
||||
List all available snapshots.
|
||||
- **Input**: `{}`
|
||||
- **Output**: JSON array of snapshots with index, timestamp, conversationCount
|
||||
|
||||
#### `revert_to_snapshot`
|
||||
Revert to a specific snapshot by index.
|
||||
- **Input**: `{ index: number }`
|
||||
- **Output**: Confirmation message
|
||||
|
||||
#### `get_diff`
|
||||
Get diff between snapshots or current state.
|
||||
- **Input**: `{ fromIndex: number, toIndex?: number }`
|
||||
- **Output**: Text diff
|
||||
|
||||
### Conversation Tools
|
||||
|
||||
#### `log_conversation`
|
||||
Log a conversation entry to persist AI memory.
|
||||
- **Input**: `{ role: 'user' | 'assistant', message: string }`
|
||||
- **Output**: Confirmation message
|
||||
|
||||
#### `get_conversation`
|
||||
Get the current conversation log.
|
||||
- **Input**: `{}`
|
||||
- **Output**: JSON array of conversation entries
|
||||
|
||||
#### `search_history`
|
||||
Search conversations and code across all snapshots.
|
||||
- **Input**: `{ query: string, type?: 'all' | 'conversation' | 'code' }`
|
||||
- **Output**: JSON array of matching snapshots with previews
|
||||
|
||||
### Cloud Sync Tools
|
||||
|
||||
#### `cloud_sync`
|
||||
Sync snapshots with cloud storage (push and pull).
|
||||
- **Input**: `{}`
|
||||
- **Output**: Sync results (pushed/pulled counts)
|
||||
|
||||
#### `cloud_push`
|
||||
Push local snapshots to cloud.
|
||||
- **Input**: `{}`
|
||||
- **Output**: Upload count
|
||||
|
||||
#### `cloud_pull`
|
||||
Pull snapshots from cloud.
|
||||
- **Input**: `{}`
|
||||
- **Output**: Download count
|
||||
|
||||
#### `cloud_status`
|
||||
Get cloud sync status and configuration.
|
||||
- **Input**: `{}`
|
||||
- **Output**: JSON with configured, endpoint, projectId, lastSync, syncedCount
|
||||
|
||||
#### `cloud_configure`
|
||||
Configure cloud sync endpoint and API key.
|
||||
- **Input**: `{ endpoint: string, apiKey: string }`
|
||||
- **Output**: Confirmation with project ID
|
||||
|
||||
### Timeline Tools
|
||||
|
||||
#### `get_timeline`
|
||||
Get a formatted timeline of all snapshots.
|
||||
- **Input**: `{}`
|
||||
- **Output**: Formatted text timeline
|
||||
|
||||
#### `restore_by_description`
|
||||
Find and restore a snapshot by searching conversation history.
|
||||
- **Input**: `{ description: string }`
|
||||
- **Output**: Confirmation of restored snapshot
|
||||
|
||||
---
|
||||
|
||||
## CLI Commands
|
||||
|
||||
### Core Commands
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `aitm init <path>` | Initialize project |
|
||||
| `aitm snapshot [file]` | Create snapshot |
|
||||
| `aitm list` | List snapshots |
|
||||
| `aitm revert <index>` | Revert to snapshot |
|
||||
| `aitm diff <from> [to]` | Show diff |
|
||||
| `aitm log <role> <msg>` | Log conversation |
|
||||
|
||||
### Timeline & Search
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `aitm timeline` | Interactive TUI browser |
|
||||
| `aitm timeline -s` | Simple text timeline |
|
||||
| `aitm search <query>` | Search all history |
|
||||
| `aitm search -c <query>` | Search conversations only |
|
||||
| `aitm search -f <query>` | Search code only |
|
||||
| `aitm restore <desc>` | Find & restore by description |
|
||||
|
||||
### Cloud Sync
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `aitm sync` | Sync with cloud |
|
||||
| `aitm sync-config <url> <key>` | Configure cloud |
|
||||
| `aitm sync-status` | Show sync status |
|
||||
| `aitm export <file>` | Export to file |
|
||||
| `aitm import <file>` | Import from file |
|
||||
|
||||
### UI & Integration
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `aitm ui` | Start web UI |
|
||||
| `aitm ui -p <port>` | Web UI on custom port |
|
||||
| `aitm watch <cmd>` | Monitor AI CLI tool |
|
||||
| `aitm mcp` | Run MCP server |
|
||||
| `aitm config` | Show config |
|
||||
| `aitm set-config <k> <v>` | Update config |
|
||||
|
||||
---
|
||||
|
||||
## Data Structures
|
||||
|
||||
### Snapshot
|
||||
```typescript
|
||||
interface Snapshot {
|
||||
timestamp: Date;
|
||||
codeState: string;
|
||||
conversationLog?: ConversationEntry[];
|
||||
}
|
||||
```
|
||||
|
||||
### ConversationEntry
|
||||
```typescript
|
||||
interface ConversationEntry {
|
||||
timestamp: Date;
|
||||
role: 'user' | 'assistant';
|
||||
message: string;
|
||||
}
|
||||
```
|
||||
|
||||
### SyncConfig
|
||||
```typescript
|
||||
interface SyncConfig {
|
||||
endpoint?: string;
|
||||
apiKey?: string;
|
||||
projectId?: string;
|
||||
autoSync?: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
### SearchResult
|
||||
```typescript
|
||||
interface SearchResult {
|
||||
snapshotIndex: number;
|
||||
timestamp: Date;
|
||||
matches: SearchMatch[];
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MCP Integration Example
|
||||
|
||||
Add to your AI tool's MCP config:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"aitimemachine": {
|
||||
"command": "aitm",
|
||||
"args": ["mcp"],
|
||||
"cwd": "/path/to/your/project"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Transport
|
||||
|
||||
AITimeMachine’s MCP server uses **stdio** by default:
|
||||
|
||||
```bash
|
||||
aitm mcp
|
||||
```
|
||||
|
||||
Optional HTTP/SSE transports can be layered for custom clients, but stdio is the supported v1 path.
|
||||
|
||||
The AI can then use tools like:
|
||||
- `create_snapshot` before making changes
|
||||
- `log_conversation` to persist memory
|
||||
- `search_history` to recall past discussions
|
||||
- `cloud_sync` to backup across devices
|
||||
- `restore_by_description` to time travel
|
||||
89
aitimemachine/CHANGELOG.md
Normal file
89
aitimemachine/CHANGELOG.md
Normal file
@ -0,0 +1,89 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to AITimeMachine will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [2.0.0] - 2026-01-15
|
||||
|
||||
### Added
|
||||
|
||||
#### CLI v2
|
||||
- Complete rewrite with interactive TUI mode
|
||||
- `aitm init` — initialize a new project with guided setup
|
||||
- `aitm checkpoint` — create timestamped checkpoints with metadata
|
||||
- `aitm restore` — restore any previous checkpoint with confirmation prompts
|
||||
- `aitm diff` — line-by-line comparison between checkpoints
|
||||
- `aitm list` — browse checkpoint history with filtering and search
|
||||
- `aitm setup` — configure MCP integration and CLAUDE.md for AI tools
|
||||
- `aitm status` — show current project state and data sources
|
||||
|
||||
#### Cloud Sync
|
||||
- End-to-end encrypted cloud backup and sync
|
||||
- Cross-device checkpoint access
|
||||
- Team sharing with granular permissions
|
||||
- Conflict resolution for concurrent edits
|
||||
- Bandwidth-efficient delta sync
|
||||
|
||||
#### MCP Protocol
|
||||
- Full Model Context Protocol server implementation
|
||||
- Tool registration: `checkpoint`, `restore`, `list`, `diff`, `timeline`
|
||||
- Compatible with Claude, Cursor, Windsurf, and other MCP clients
|
||||
- Streaming support for large checkpoint operations
|
||||
- Context-aware checkpoint suggestions
|
||||
|
||||
#### API Server
|
||||
- RESTful API with OpenAPI 3.0 specification
|
||||
- Authentication via API keys and OAuth 2.0
|
||||
- Health endpoints: `/health`, `/health/db`, `/health/live`, `/health/ready`, `/health/schema`
|
||||
- Rate limiting and request validation
|
||||
- PostgreSQL database with Drizzle ORM
|
||||
- Session management and audit logging
|
||||
|
||||
#### Web Dashboard
|
||||
- Project overview with checkpoint timeline
|
||||
- Visual diff viewer with side-by-side comparison
|
||||
- Team management and invitation system
|
||||
- Usage analytics and storage monitoring
|
||||
- Responsive design for mobile access
|
||||
|
||||
#### Teams & Organizations
|
||||
- Organization accounts with role-based access control
|
||||
- Team workspaces with shared checkpoint history
|
||||
- Admin dashboard for member management
|
||||
- Usage quotas and billing per organization
|
||||
- SSO integration support
|
||||
|
||||
#### Infrastructure
|
||||
- Docker support with multi-stage builds
|
||||
- Health check endpoints for container orchestration
|
||||
- Structured JSON logging
|
||||
- Database migration system with Drizzle Kit
|
||||
- Environment-based configuration
|
||||
|
||||
### Changed
|
||||
- Migrated from isomorphic-git to custom checkpoint engine for better performance
|
||||
- Redesigned CLI output with colored, structured formatting
|
||||
- Improved checkpoint storage format for 3x space efficiency
|
||||
|
||||
### Fixed
|
||||
- Checkpoint corruption on interrupted writes
|
||||
- Memory leak in watch mode for large repositories
|
||||
- Incorrect diff output for binary files
|
||||
|
||||
---
|
||||
|
||||
## [1.0.0] - 2025-06-01
|
||||
|
||||
### Added
|
||||
- Core TimeMachine library with checkpoint/restore functionality
|
||||
- Conversation memory for persistent AI interactions
|
||||
- MCP protocol server for AI tool integrations
|
||||
- CLI interface with commands for init, checkpoint, list, restore, status, mcp
|
||||
- Git integration using isomorphic-git for versioned checkpoints
|
||||
- Docusaurus website for documentation
|
||||
- Comprehensive docs: README, DEVELOPMENT.md, API.md, ROADMAP.md
|
||||
- Diff feature: view line-by-line differences between checkpoints via CLI and MCP
|
||||
- Configuration system: user settings for auto-confirm, watch enabled, max checkpoints
|
||||
- Confirmation prompts: user approval for destructive actions like restores
|
||||
25
aitimemachine/CLAUDE.md
Normal file
25
aitimemachine/CLAUDE.md
Normal file
@ -0,0 +1,25 @@
|
||||
# AITimeMachine Integration
|
||||
|
||||
This project uses AITimeMachine for automatic backup and restore.
|
||||
|
||||
## IMPORTANT: Before making ANY file changes
|
||||
|
||||
Call the `before_action` MCP tool with a description of what you're about to do:
|
||||
```
|
||||
before_action({ action: "description of changes" })
|
||||
```
|
||||
|
||||
## After completing changes
|
||||
|
||||
Call the `after_action` MCP tool:
|
||||
```
|
||||
after_action({ action: "description of what was done", success: true })
|
||||
```
|
||||
|
||||
## Available Commands
|
||||
|
||||
- `checkpoint` - Create a manual save point
|
||||
- `list_sessions` - See all saved states
|
||||
- `restore_session` - Go back to any previous state
|
||||
|
||||
This ensures all file changes are tracked and can be rolled back if needed.
|
||||
128
aitimemachine/DEVELOPMENT.md
Normal file
128
aitimemachine/DEVELOPMENT.md
Normal file
@ -0,0 +1,128 @@
|
||||
# AITimeMachine Development Guide
|
||||
|
||||
## For AI Contributors and Developers
|
||||
|
||||
This guide provides detailed context for understanding, extending, and contributing to AITimeMachine. The project is in early stages with much coding required. It aims to solve AI coding tool issues like memory loss and unasked changes through time travel and memory persistence.
|
||||
|
||||
### Project Context Recap
|
||||
- **Problem**: AI tools modify code unexpectedly, lose conversation context, lack revert mechanisms.
|
||||
- **Solution**: Time machine for code/conversations with MCP integration for AI tools.
|
||||
- **Scope**: Infra-focused, cross-platform, open-source. Future: cloud sync, UI, enterprise features.
|
||||
- **Status**: Core implemented; needs testing, features, optimizations.
|
||||
|
||||
### Core Concepts
|
||||
|
||||
#### Time Travel Mechanism
|
||||
- **Snapshots**: Immutable captures of project state at a point in time.
|
||||
- **Conversations**: Logged AI/user interactions with timestamps.
|
||||
- **Reverts**: Restoration to previous snapshots, including code and memory.
|
||||
- **Confirmation**: User gates to prevent unintended AI actions.
|
||||
|
||||
#### MCP Integration
|
||||
- **Protocol**: Model Context Protocol for AI tool communication.
|
||||
- **Tools**: Exposed functions (create_snapshot, revert, etc.) for AI to call.
|
||||
- **Server**: Express-based server handling MCP requests over stdio/HTTP.
|
||||
|
||||
#### Git Integration
|
||||
- **Purpose**: Provide git-based versioning for snapshots.
|
||||
- **Implementation**: Uses isomorphic-git for commits on snapshot creation.
|
||||
- **Fallback**: File-based storage if git fails.
|
||||
|
||||
### Code Structure
|
||||
|
||||
#### `src/index.ts` - Core Library
|
||||
- `TimeMachine` class: Main API.
|
||||
- Methods: `initialize()`, `createSnapshot()`, `revertToSnapshot()`, `logConversation()`.
|
||||
- Handles file watching, snapshot persistence, conversation memory.
|
||||
|
||||
#### `src/cli.ts` - Command Line Interface
|
||||
- Uses Commander.js for commands (init, snapshot, list, revert, log, mcp).
|
||||
- Entry point for users.
|
||||
|
||||
#### `src/mcp-server.ts` - MCP Server
|
||||
- Implements MCP with tools for AI integration.
|
||||
- Handles requests like creating snapshots or logging conversations.
|
||||
|
||||
#### `src/server.ts` - REST Server
|
||||
- Basic Express server for testing; may be expanded.
|
||||
|
||||
#### `website/` - Documentation
|
||||
- Docusaurus site with guides, API docs.
|
||||
|
||||
### Key Files and Directories
|
||||
- `.aitimemachine/`: Stores snapshots and conversations.
|
||||
- `lib/`: Compiled output.
|
||||
- `test/`: Unit tests (expand needed).
|
||||
- `tsconfig.json`: TypeScript config for ESM.
|
||||
|
||||
### Development Workflow
|
||||
1. **Setup**: `npm install`, `npm run build`.
|
||||
2. **Code**: Edit `src/`, build with `npm run build`.
|
||||
3. **Test**: `npm test` (fix ESM issues).
|
||||
4. **Run**: `node lib/cli.js <command>`.
|
||||
5. **Lint**: `npm run lint`.
|
||||
|
||||
### Universal Search Evaluation
|
||||
Use the golden-set eval harness to measure MRR/Recall@K against your current data.
|
||||
|
||||
From `api-server/`:
|
||||
- `EVAL_API_KEY=... EVAL_BASE_URL=http://localhost:3001/v1 npm run eval:universal-search`
|
||||
- Fixture path: `tests/fixtures/universal-search-eval.json`
|
||||
|
||||
Adjust the fixture to match your datasets and expected targets.
|
||||
|
||||
Optional outputs:
|
||||
- `EVAL_OUTPUT_JSON=eval.json` writes a JSON summary for dashboards
|
||||
- `EVAL_OUTPUT_CSV=eval.csv` writes per-case CSV rows
|
||||
- `EVAL_K=1,3,5,10` custom K values
|
||||
|
||||
CI thresholds (non-zero exit on failure):
|
||||
- `EVAL_MIN_MRR=0.35`
|
||||
- `EVAL_MIN_RECALL=0.60` (uses the first K in `EVAL_K`)
|
||||
- `EVAL_MIN_WEIGHTED_MRR=0.40`
|
||||
- `EVAL_MIN_WEIGHTED_RECALL=0.65`
|
||||
|
||||
### Detailed Implementation Notes
|
||||
- **ESM Handling**: Package uses "type": "module"; imports must include .js extensions.
|
||||
- **File Watching**: Chokidar monitors changes; triggers snapshots.
|
||||
- **Persistence**: JSON files in .aitimemachine/; conversations in conversation.json.
|
||||
- **Git Commits**: On snapshot; uses isomorphic-git for portability.
|
||||
- **MCP Tools**: JSON-RPC over stdio; tools call TimeMachine methods.
|
||||
- **Error Handling**: Try-catch with console.warn; graceful degradation.
|
||||
|
||||
### Outstanding Tasks (Much Coding Needed)
|
||||
- **Testing**: Comprehensive Jest suite for all methods (fix ESM in Jest config).
|
||||
- **Performance**: Optimize for large projects (selective watching, efficient diffs).
|
||||
- **Features**:
|
||||
- Diff visualization (use diff library for colored diffs).
|
||||
- Cloud sync (add optional server for upload/download).
|
||||
- Advanced confirmations (UI prompts, auto-approve rules).
|
||||
- **Integrations**:
|
||||
- More MCP tools (e.g., analyze_reverts).
|
||||
- AI tool partnerships (PRs to repos).
|
||||
- **Docs**: API references (see API.md), tutorials, examples.
|
||||
- **Security**: Encrypt sensitive data, audit logs.
|
||||
- **UI**: Enhance website, add simple web UI for browsing.
|
||||
- **Deployment**: CI/CD (GitHub Actions), npm publish, website hosting (Netlify).
|
||||
- **Bug Fixes**: Handle edge cases (no git, permissions, large files).
|
||||
|
||||
### Best Practices
|
||||
- **Error Handling**: Always catch and log errors (e.g., git failures).
|
||||
- **Cross-Platform**: Use Node.js APIs; test on Windows/Mac/Linux.
|
||||
- **Modularity**: Keep features in separate modules.
|
||||
- **Documentation**: Comment code; update docs for changes.
|
||||
- **Commits**: Use conventional commits; run tests before PR.
|
||||
|
||||
### Examples
|
||||
#### Adding a New MCP Tool
|
||||
1. Edit `src/mcp-server.ts` to add tool in `ListToolsRequestSchema`.
|
||||
2. Implement handler in `CallToolRequestSchema`.
|
||||
3. Update API.md.
|
||||
|
||||
#### Extending CLI
|
||||
1. Add command in `src/cli.ts`.
|
||||
2. Call TimeMachine method.
|
||||
3. Update README usage.
|
||||
|
||||
### Contact
|
||||
For questions, open issues or PRs on GitHub. See ROADMAP.md for priorities.
|
||||
61
aitimemachine/ENGINES.md
Normal file
61
aitimemachine/ENGINES.md
Normal file
@ -0,0 +1,61 @@
|
||||
# AITM Engines
|
||||
|
||||
AITM merges seven vendored repos in as **first-party engines** — built, imported,
|
||||
and managed as part of the product. There are no "assumed external service" seams
|
||||
(`GITNEXUS_URL`, `CONTEXT7_URL`, `PAL_MCP_URL` are gone).
|
||||
|
||||
Build everything with:
|
||||
|
||||
```bash
|
||||
bash aitimemachine/scripts/build-engines.sh
|
||||
```
|
||||
|
||||
This produces bundled binaries under `aitimemachine/bin/` and a Python venv under
|
||||
`aitimemachine/engines/pal/`, and builds the TS engine libraries. Both directories
|
||||
are git-ignored.
|
||||
|
||||
## The three layers
|
||||
|
||||
### Memory — `beads` + `context7`
|
||||
| Engine | What | How it's wired |
|
||||
|---|---|---|
|
||||
| **beads** (`beads/`, Go) | Task/issue DAG memory (Dolt-backed). | Built to `bin/bd`; `api-server/src/routes/beads.ts` spawns it. Task creates write through to AITM memory. |
|
||||
| **context7** (`context7/`, TS) | Up-to-date library/framework docs. | In-process `@upstash/context7-sdk` (`Context7` client). Configured by `CONTEXT7_API_KEY`. |
|
||||
|
||||
Both feed AITM's unified memory: `services/memoryService.ts` ingests beads tasks
|
||||
(`source='task'`) and context7 docs (`source='library'`) into `saved_contexts` with
|
||||
embeddings, so `/v1/contexts/search/*` returns them alongside conversation memory.
|
||||
Schema change: `saved_contexts.source` (migration `0005_add_saved_context_source.sql`).
|
||||
|
||||
### Git — vendored C `git` + `gitnexus`
|
||||
| Engine | What | How it's wired |
|
||||
|---|---|---|
|
||||
| **git** (`git/`, C) | The real Git (upstream C source). The Rust `gitcore` crate is a non-functional stub and is **not** used. | Built to `bin/git`; `src/core/git-engine.ts` shells out (falls back to system `git`). Checkpoints mirror to a real git commit (`AITM_GIT_MIRROR`). `aitm git …` passthrough. |
|
||||
| **gitnexus** (`gitnexus/` + `gitnexus-shared/`, TS) | Code-intelligence graph (Tree-sitter + LadybugDB). | In-process via the new `gitnexus` library entry (`gitnexus/src/index.ts` → `LocalBackend.callTool`). `gitNexusService.ts` calls it directly; `gn_*` MCP tools unchanged. |
|
||||
|
||||
### Agentic comms — `pal` + `a2a`
|
||||
| Engine | What | How it's wired |
|
||||
|---|---|---|
|
||||
| **a2a** (`a2a/`, TS) | Agent-to-agent protocol. | Consolidated onto `@a2a-js/sdk` (`DefaultRequestHandler`, `InMemoryTaskStore`, `A2AClient`). The hand-rolled `a2aService` is replaced; registry backed by the SDK TaskStore. |
|
||||
| **pal** (`pal-mcp-server/`, Python) | Agent Python execution / multi-model orchestration (MCP, stdio). | AITM-managed subprocess: `api-server/src/engines/palEngine.ts` spawns the bundled venv and speaks MCP over stdio. `pal_*` tools route through it. |
|
||||
|
||||
## Path resolution & health
|
||||
|
||||
- `api-server/src/services/engineManager.ts` resolves bundled engine paths
|
||||
(`bin/bd`, `bin/git`, `engines/pal`) with first-party defaults — no external URLs.
|
||||
- `GET /v1/health/providers` reports each engine in-process/bundled:
|
||||
GitNexus → `gitNexusService.isAvailable()`; Context7 → `CONTEXT7_API_KEY`;
|
||||
PAL → `palEngine.health()`; beads → `bin/bd --version`; git → bundled/system.
|
||||
|
||||
## Environment
|
||||
|
||||
| Var | Purpose | Default |
|
||||
|---|---|---|
|
||||
| `CONTEXT7_API_KEY` | Enable Context7 (replaces `CONTEXT7_URL`). | — |
|
||||
| `AITM_MEMORY_USER_ID` / `AITM_MEMORY_PROJECT_ID` | Target for memory write-through when a request has no user/project. | write-through skipped if unset |
|
||||
| `AITM_GIT_BIN` | Override git binary. | `bin/git` → system `git` |
|
||||
| `AITM_GIT_MIRROR` | `0` disables mirroring checkpoints to git. | enabled |
|
||||
| `PAL_VENV_DIR` / `PAL_PYTHON` | PAL venv / interpreter. | `engines/pal` |
|
||||
| `BEADS_BINARY` | Override beads binary. | `bin/bd` |
|
||||
|
||||
Removed: `GITNEXUS_URL`, `CONTEXT7_URL`, `PAL_URL`, `PAL_MCP_URL`, `AITM_A2A_AGENTS`.
|
||||
21
aitimemachine/LICENSE
Normal file
21
aitimemachine/LICENSE
Normal file
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 AITimeMachine
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
988
aitimemachine/MCP.md
Normal file
988
aitimemachine/MCP.md
Normal file
@ -0,0 +1,988 @@
|
||||
Below is a **complete, copy-pasteable** technical plan + documentation for an **“AI Time Machine” MCP server**. It’s written like a README you can drop into a repo or docs site, with a working skeleton MCP server (TypeScript/stdio) and a concrete tool/resource design that matches your product goals: rewind **conversation + project folder + terminal history + capsule environment**.
|
||||
|
||||
---
|
||||
|
||||
# AI Time Machine MCP: Technical Implementation & Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
**AI Time Machine** is an event-sourced “Time Machine” for AI coding workflows. It captures and restores:
|
||||
|
||||
* **Chat context** (threads, messages, tool outputs)
|
||||
* **Workspace state** (full file tree snapshots, including untracked)
|
||||
* **Terminal history** (commands + outputs + exit codes)
|
||||
* **Capsule environment** (container image digest + run configuration)
|
||||
|
||||
This MCP server exposes those capabilities to MCP clients (Cursor/VSCode agents, Claude Desktop, ChatGPT desktop, etc.) via **tools** and **resources**.
|
||||
|
||||
### What this MCP server does (in one line)
|
||||
|
||||
It’s the standard interface for an AI client to: **record events**, **create checkpoints**, **diff**, **restore**, and **run inside a container capsule**.
|
||||
|
||||
---
|
||||
|
||||
## Goals (MVP-friendly)
|
||||
|
||||
### Must-have
|
||||
|
||||
* Append-only event log (auditability)
|
||||
* Named checkpoints
|
||||
* Workspace snapshot/restore
|
||||
* Terminal session log capture
|
||||
* Capsule mode: run commands in a pinned container image
|
||||
* Diff checkpoint ↔ checkpoint (files + chat + commands)
|
||||
|
||||
### Not in MVP
|
||||
|
||||
* True process snapshot/restore (CRIU/VM)
|
||||
* Team multi-user sync (can add later)
|
||||
* OS-wide terminal capture (only managed terminals)
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
### Components
|
||||
|
||||
1. **MCP Server (`ai-time-machine-mcp`)**
|
||||
|
||||
* Exposes tools/resources/prompts.
|
||||
* Validates inputs (Zod).
|
||||
* Writes to local store (SQLite + blob store).
|
||||
* Optionally controls containers (Docker).
|
||||
|
||||
2. **Local Store**
|
||||
|
||||
* `events.db` (SQLite): event stream + indices.
|
||||
* `blobs/` (CAS): file contents, terminal outputs, chat attachments.
|
||||
* `manifests/` (snapshot manifests): path → blob hash + metadata.
|
||||
|
||||
3. **Client Integration (Cursor/VSCode)**
|
||||
|
||||
* Captures:
|
||||
|
||||
* file changes (on save / debounce)
|
||||
* chat messages + tool outputs
|
||||
* terminal commands + output streams
|
||||
* Calls MCP tools:
|
||||
|
||||
* `tm_event_append`
|
||||
* `tm_checkpoint_create`
|
||||
* `tm_restore_checkpoint`
|
||||
* `tm_diff_checkpoints`
|
||||
|
||||
4. **Capsule Runtime (Container)**
|
||||
|
||||
* Per-project container image digest pinned per checkpoint.
|
||||
* Workspace mount uses snapshot restore (deterministic FS).
|
||||
* Commands run inside capsule; outputs streamed back as events.
|
||||
|
||||
---
|
||||
|
||||
## Data Model (Event Sourcing + Materialized Checkpoints)
|
||||
|
||||
**Everything is an event.** Checkpoints are “materialized views” referencing blobs.
|
||||
|
||||
### Event stream (high level)
|
||||
|
||||
* `chat.message`
|
||||
* `fs.change_batch`
|
||||
* `term.command`
|
||||
* `term.output_chunk`
|
||||
* `capsule.state`
|
||||
* `checkpoint.created`
|
||||
|
||||
### Why event sourcing
|
||||
|
||||
* Time-travel is trivial: replay to any point.
|
||||
* Diffs are straightforward.
|
||||
* Auditability and debugging are natural.
|
||||
|
||||
---
|
||||
|
||||
## Tooling Design (MCP)
|
||||
|
||||
### Tools (what the model can call)
|
||||
|
||||
#### 1) `tm_project_init`
|
||||
|
||||
Create or register a project.
|
||||
|
||||
**Input**
|
||||
|
||||
* `projectId` (string, stable id)
|
||||
* `rootPath` (string, absolute path)
|
||||
* `name` (string)
|
||||
|
||||
**Output**
|
||||
|
||||
* `{ projectId, createdAt }`
|
||||
|
||||
---
|
||||
|
||||
#### 2) `tm_event_append`
|
||||
|
||||
Append an event to the project timeline (chat/fs/terminal/capsule).
|
||||
|
||||
**Input**
|
||||
|
||||
* `projectId`
|
||||
* `type` (enum)
|
||||
* `timestamp` (ISO)
|
||||
* `payload` (object)
|
||||
* optional `blobs` (array of `{ mimeType, dataBase64 }` or `{ mimeType, text }`)
|
||||
|
||||
**Output**
|
||||
|
||||
* `{ eventId }`
|
||||
|
||||
> Use this from the IDE extension for *every* capture.
|
||||
|
||||
---
|
||||
|
||||
#### 3) `tm_checkpoint_create`
|
||||
|
||||
Create a named checkpoint.
|
||||
|
||||
**Input**
|
||||
|
||||
* `projectId`
|
||||
* `name`
|
||||
* `scope`: `"files" | "files+chat" | "files+chat+terminal" | "full"`
|
||||
* optional `capsule`: `{ imageRef?, workdir?, env? }`
|
||||
|
||||
**Output**
|
||||
|
||||
* `{ checkpointId, createdAt }`
|
||||
|
||||
**Behavior**
|
||||
|
||||
* Builds a workspace manifest
|
||||
* Stores any missing file blobs
|
||||
* Links checkpoint to:
|
||||
|
||||
* `workspace_manifest_ref`
|
||||
* `chat_head_event_id`
|
||||
* `terminal_head_event_id`
|
||||
* `capsule_image_digest` (if enabled)
|
||||
|
||||
---
|
||||
|
||||
#### 4) `tm_list_checkpoints`
|
||||
|
||||
List checkpoints for a project (supports timeline UI).
|
||||
|
||||
**Input**
|
||||
|
||||
* `projectId`
|
||||
* optional `limit`, `cursor`
|
||||
|
||||
**Output**
|
||||
|
||||
* array of checkpoints with metadata + “summary” fields
|
||||
|
||||
---
|
||||
|
||||
#### 5) `tm_diff_checkpoints`
|
||||
|
||||
Return diffs between two checkpoints.
|
||||
|
||||
**Input**
|
||||
|
||||
* `projectId`
|
||||
* `aCheckpointId`
|
||||
* `bCheckpointId`
|
||||
|
||||
**Output**
|
||||
|
||||
* `fileDiffs`: list of `{ path, aHash, bHash, patch? }`
|
||||
* `chatDiff`: summary of messages added/removed
|
||||
* `terminalDiff`: commands executed between
|
||||
|
||||
---
|
||||
|
||||
#### 6) `tm_restore_checkpoint`
|
||||
|
||||
Restore workspace (and optionally chat pointer) to a checkpoint.
|
||||
|
||||
**Input**
|
||||
|
||||
* `projectId`
|
||||
* `checkpointId`
|
||||
* `mode`: `"safe" | "hard"`
|
||||
* `restoreScope`: `"files" | "files+chat"`
|
||||
* optional `backupCurrent`: boolean
|
||||
|
||||
**Output**
|
||||
|
||||
* `{ restoredPaths, backupPath?, chatHeadEventId }`
|
||||
|
||||
---
|
||||
|
||||
#### 7) Capsule tools
|
||||
|
||||
##### `tm_capsule_create_or_attach`
|
||||
|
||||
Create or re-use a capsule container for a project.
|
||||
|
||||
**Input**
|
||||
|
||||
* `projectId`
|
||||
* `imageRef` (e.g. `node:20-bookworm@sha256:...`)
|
||||
* `workdir`
|
||||
* `env` (key/value)
|
||||
* optional `ports`
|
||||
|
||||
**Output**
|
||||
|
||||
* `{ capsuleId, imageDigest }`
|
||||
|
||||
##### `tm_capsule_exec`
|
||||
|
||||
Run a command inside capsule.
|
||||
|
||||
**Input**
|
||||
|
||||
* `projectId`
|
||||
* `capsuleId`
|
||||
* `command` (string)
|
||||
* `cwd` (string)
|
||||
* optional `timeoutMs`
|
||||
|
||||
**Output**
|
||||
|
||||
* `{ exitCode, stdoutRef, stderrRef }`
|
||||
|
||||
> This should also automatically emit `term.command` and streamed `term.output_chunk` events.
|
||||
|
||||
##### `tm_capsule_stop`
|
||||
|
||||
Stop capsule for a project.
|
||||
|
||||
---
|
||||
|
||||
### Resources (browseable content)
|
||||
|
||||
Resources are ideal for timeline UI and “pull into context”.
|
||||
|
||||
#### `tm://projects`
|
||||
|
||||
List projects.
|
||||
|
||||
#### `tm://projects/{projectId}/timeline?from=...&to=...`
|
||||
|
||||
Timeline slices of events.
|
||||
|
||||
#### `tm://projects/{projectId}/checkpoints`
|
||||
|
||||
Checkpoint list.
|
||||
|
||||
#### `tm://projects/{projectId}/checkpoints/{checkpointId}/manifest`
|
||||
|
||||
Workspace manifest JSON.
|
||||
|
||||
#### `tm://blobs/{hash}`
|
||||
|
||||
Fetch blob content (text/binary base64).
|
||||
|
||||
---
|
||||
|
||||
### Prompts (optional but useful)
|
||||
|
||||
* `tm_prompt_debug_regression`: “Given checkpoint A and B diff, propose minimal fix.”
|
||||
* `tm_prompt_write_postmortem`: “Generate incident report from timeline segment.”
|
||||
* `tm_prompt_generate_repro_steps`: “Turn terminal history into deterministic repro steps.”
|
||||
|
||||
---
|
||||
|
||||
## MVP Repo Template
|
||||
|
||||
```
|
||||
ai-time-machine-mcp/
|
||||
src/
|
||||
index.ts
|
||||
store/
|
||||
db.ts
|
||||
migrations.ts
|
||||
blobs.ts
|
||||
manifests.ts
|
||||
tools/
|
||||
projects.ts
|
||||
events.ts
|
||||
checkpoints.ts
|
||||
diff.ts
|
||||
restore.ts
|
||||
capsule.ts
|
||||
resources/
|
||||
resources.ts
|
||||
lib/
|
||||
schema.ts
|
||||
paths.ts
|
||||
hash.ts
|
||||
errors.ts
|
||||
blobs/ # CAS store (created at runtime)
|
||||
manifests/ # checkpoint manifests
|
||||
events.db # sqlite
|
||||
package.json
|
||||
tsconfig.json
|
||||
README.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## SQLite Schema (copy-paste)
|
||||
|
||||
### 1) `projects`
|
||||
|
||||
Stores project roots + display names.
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS projects (
|
||||
project_id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
root_path TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_projects_root_path ON projects(root_path);
|
||||
```
|
||||
|
||||
### 2) `events`
|
||||
|
||||
Append-only event log.
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
event_id TEXT PRIMARY KEY,
|
||||
project_id TEXT NOT NULL,
|
||||
ts TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL,
|
||||
prev_event_id TEXT,
|
||||
FOREIGN KEY(project_id) REFERENCES projects(project_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_events_project_ts ON events(project_id, ts);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_project_type ON events(project_id, type);
|
||||
```
|
||||
|
||||
> `prev_event_id` lets you maintain a per-project linked list head (optional). Otherwise compute heads by `MAX(ts)`.
|
||||
|
||||
### 3) `blobs`
|
||||
|
||||
Content-addressed storage index.
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS blobs (
|
||||
hash TEXT PRIMARY KEY,
|
||||
size_bytes INTEGER NOT NULL,
|
||||
mime_type TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
path_on_disk TEXT NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
### 4) `manifests`
|
||||
|
||||
A workspace snapshot manifest.
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS manifests (
|
||||
manifest_id TEXT PRIMARY KEY,
|
||||
project_id TEXT NOT NULL,
|
||||
root_path TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
manifest_blob_hash TEXT NOT NULL,
|
||||
FOREIGN KEY(project_id) REFERENCES projects(project_id),
|
||||
FOREIGN KEY(manifest_blob_hash) REFERENCES blobs(hash)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_manifests_project_created ON manifests(project_id, created_at);
|
||||
```
|
||||
|
||||
### 5) `checkpoints`
|
||||
|
||||
Materialized checkpoint pointers.
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS checkpoints (
|
||||
checkpoint_id TEXT PRIMARY KEY,
|
||||
project_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
|
||||
manifest_id TEXT NOT NULL,
|
||||
chat_head_event_id TEXT,
|
||||
terminal_head_event_id TEXT,
|
||||
|
||||
capsule_image_ref TEXT,
|
||||
capsule_image_digest TEXT,
|
||||
capsule_workdir TEXT,
|
||||
capsule_env_json TEXT,
|
||||
|
||||
FOREIGN KEY(project_id) REFERENCES projects(project_id),
|
||||
FOREIGN KEY(manifest_id) REFERENCES manifests(manifest_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_checkpoints_project_created ON checkpoints(project_id, created_at);
|
||||
```
|
||||
|
||||
### 6) Optional: `terminal_sessions`
|
||||
|
||||
If you want stable terminal session IDs.
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS terminal_sessions (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
project_id TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
label TEXT,
|
||||
FOREIGN KEY(project_id) REFERENCES projects(project_id)
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Blob Formats (CAS)
|
||||
|
||||
### Hashing
|
||||
|
||||
* `hash = sha256(content_bytes)` (hex)
|
||||
* Blob file path: `blobs/aa/bb/<hash>`
|
||||
|
||||
### Blob payloads
|
||||
|
||||
* File contents: raw bytes
|
||||
* Terminal stdout/stderr: raw bytes (UTF-8 text typically)
|
||||
* Manifests: JSON text (UTF-8)
|
||||
|
||||
### Manifest JSON (stored as blob)
|
||||
|
||||
Example (`manifest_blob_hash` points to this JSON):
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"rootPath": "/abs/path/project",
|
||||
"capturedAt": "2025-12-22T12:34:56.000Z",
|
||||
"files": [
|
||||
{
|
||||
"path": "src/index.ts",
|
||||
"hash": "sha256hex...",
|
||||
"size": 1234,
|
||||
"mode": 420,
|
||||
"mtimeMs": 1734867296000
|
||||
}
|
||||
],
|
||||
"ignore": [
|
||||
"node_modules/**",
|
||||
".git/**",
|
||||
".venv/**",
|
||||
"dist/**"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Capsule Design (exact restore without hacks)
|
||||
|
||||
“Exact restore” comes from **pinning the runtime** (image digest) and restoring the **workspace snapshot**.
|
||||
|
||||
### Rules
|
||||
|
||||
* Every checkpoint stores:
|
||||
|
||||
* `capsule_image_ref` (human-readable)
|
||||
* `capsule_image_digest` (actual pin)
|
||||
* env vars (non-secret; secrets handled separately)
|
||||
* workdir
|
||||
|
||||
### Execution model
|
||||
|
||||
* Restore checkpoint → restore workspace files on host
|
||||
* Start capsule with pinned digest
|
||||
* Mount restored workspace into capsule at `/workspace`
|
||||
* Run commands inside capsule
|
||||
* Stream outputs back as `term.output_chunk` events
|
||||
|
||||
### Why this is “exact”
|
||||
|
||||
* Same image digest means same OS + toolchain
|
||||
* Same workspace snapshot means same bytes
|
||||
* Same recorded commands means same steps
|
||||
|
||||
> If you need “running server state,” store a “runbook” (commands to start services) and rerun it after restore.
|
||||
|
||||
---
|
||||
|
||||
## Working MCP Server Skeleton (TypeScript / stdio)
|
||||
|
||||
### Install
|
||||
|
||||
```bash
|
||||
mkdir ai-time-machine-mcp
|
||||
cd ai-time-machine-mcp
|
||||
npm init -y
|
||||
npm i @modelcontextprotocol/sdk zod better-sqlite3
|
||||
npm i -D typescript ts-node @types/node
|
||||
npx tsc --init
|
||||
```
|
||||
|
||||
### `package.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "ai-time-machine-mcp",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node --loader ts-node/esm src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `src/index.ts` (minimal but real)
|
||||
|
||||
```ts
|
||||
import { z } from "zod";
|
||||
import Database from "better-sqlite3";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
|
||||
const DATA_DIR = process.env.TM_DATA_DIR ?? path.resolve(process.cwd(), ".tmdata");
|
||||
const DB_PATH = path.join(DATA_DIR, "events.db");
|
||||
const BLOBS_DIR = path.join(DATA_DIR, "blobs");
|
||||
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
fs.mkdirSync(BLOBS_DIR, { recursive: true });
|
||||
|
||||
const db = new Database(DB_PATH);
|
||||
db.pragma("journal_mode = WAL");
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS projects (
|
||||
project_id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
root_path TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
event_id TEXT PRIMARY KEY,
|
||||
project_id TEXT NOT NULL,
|
||||
ts TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL,
|
||||
prev_event_id TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_project_ts ON events(project_id, ts);
|
||||
CREATE TABLE IF NOT EXISTS blobs (
|
||||
hash TEXT PRIMARY KEY,
|
||||
size_bytes INTEGER NOT NULL,
|
||||
mime_type TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
path_on_disk TEXT NOT NULL
|
||||
);
|
||||
`);
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function sha256Hex(buf: Buffer) {
|
||||
return crypto.createHash("sha256").update(buf).digest("hex");
|
||||
}
|
||||
|
||||
function putBlob(mimeType: string, data: Buffer) {
|
||||
const hash = sha256Hex(data);
|
||||
const sub = path.join(BLOBS_DIR, hash.slice(0, 2), hash.slice(2, 4));
|
||||
const filePath = path.join(sub, hash);
|
||||
fs.mkdirSync(sub, { recursive: true });
|
||||
|
||||
if (!fs.existsSync(filePath)) fs.writeFileSync(filePath, data);
|
||||
|
||||
const stat = fs.statSync(filePath);
|
||||
const stmt = db.prepare(`
|
||||
INSERT OR IGNORE INTO blobs(hash, size_bytes, mime_type, created_at, path_on_disk)
|
||||
VALUES(?,?,?,?,?)
|
||||
`);
|
||||
stmt.run(hash, stat.size, mimeType, nowIso(), filePath);
|
||||
return { hash, sizeBytes: stat.size, mimeType };
|
||||
}
|
||||
|
||||
const server = new McpServer({ name: "ai-time-machine-mcp", version: "0.1.0" });
|
||||
|
||||
server.tool(
|
||||
"tm_project_init",
|
||||
"Create or register a project in AI Time Machine",
|
||||
{
|
||||
projectId: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
rootPath: z.string().min(1),
|
||||
},
|
||||
async ({ projectId, name, rootPath }) => {
|
||||
const stmt = db.prepare(`
|
||||
INSERT OR REPLACE INTO projects(project_id, name, root_path, created_at)
|
||||
VALUES(?,?,?,?)
|
||||
`);
|
||||
stmt.run(projectId, name, rootPath, nowIso());
|
||||
return { content: [{ type: "text", text: JSON.stringify({ projectId, createdAt: nowIso() }, null, 2) }] };
|
||||
}
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"tm_event_append",
|
||||
"Append an event to the project timeline (chat/fs/terminal/capsule)",
|
||||
{
|
||||
projectId: z.string().min(1),
|
||||
type: z.string().min(1),
|
||||
timestamp: z.string().min(1),
|
||||
payload: z.record(z.any()),
|
||||
blobs: z
|
||||
.array(
|
||||
z.union([
|
||||
z.object({ mimeType: z.string().min(1), text: z.string() }),
|
||||
z.object({ mimeType: z.string().min(1), dataBase64: z.string().min(1) }),
|
||||
])
|
||||
)
|
||||
.optional(),
|
||||
},
|
||||
async ({ projectId, type, timestamp, payload, blobs }) => {
|
||||
const eventId = crypto.randomUUID();
|
||||
|
||||
const blobRefs: Array<{ hash: string; mimeType: string; sizeBytes: number }> = [];
|
||||
if (blobs) {
|
||||
for (const b of blobs) {
|
||||
const data = "dataBase64" in b ? Buffer.from(b.dataBase64, "base64") : Buffer.from(b.text, "utf8");
|
||||
const ref = putBlob(b.mimeType, data);
|
||||
blobRefs.push(ref);
|
||||
}
|
||||
}
|
||||
|
||||
const payloadWithBlobs = { ...payload, blobRefs };
|
||||
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO events(event_id, project_id, ts, type, payload_json)
|
||||
VALUES(?,?,?,?,?)
|
||||
`);
|
||||
stmt.run(eventId, projectId, timestamp, type, JSON.stringify(payloadWithBlobs));
|
||||
|
||||
return { content: [{ type: "text", text: JSON.stringify({ eventId }, null, 2) }] };
|
||||
}
|
||||
);
|
||||
|
||||
server.resource(
|
||||
"tm_projects",
|
||||
"tm://projects",
|
||||
async () => {
|
||||
const rows = db.prepare(`SELECT project_id, name, root_path, created_at FROM projects`).all();
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: "tm://projects",
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify(rows, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
async function main() {
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Fatal MCP server error:", err);
|
||||
process.exit(1);
|
||||
});
|
||||
```
|
||||
|
||||
This already gives you:
|
||||
|
||||
* project registry
|
||||
* append-only timeline events
|
||||
* blob store
|
||||
* resource browsing
|
||||
|
||||
Next, you add:
|
||||
|
||||
* checkpoint create/list/diff/restore
|
||||
* capsule tools (Docker)
|
||||
|
||||
---
|
||||
|
||||
## Cursor/VSCode Extension Integration Plan (how the client uses MCP)
|
||||
|
||||
### What the extension should capture
|
||||
|
||||
1. **File changes**
|
||||
|
||||
* Hook `workspace.onDidSaveTextDocument`
|
||||
* Debounce into a batch event every ~2–5 seconds
|
||||
* For each changed file, either:
|
||||
|
||||
* send full content as blob, or
|
||||
* send patch (nice-to-have), plus full content at checkpoint time
|
||||
|
||||
2. **Chat messages**
|
||||
|
||||
* If your chat is a webview, forward messages to extension host and call `tm_event_append` with type `chat.message`.
|
||||
|
||||
3. **Terminal commands + outputs**
|
||||
|
||||
* Prefer managed terminals created by the extension.
|
||||
* Wrap commands via a small shim:
|
||||
|
||||
* extension calls `tm_event_append(type=term.command)`
|
||||
* run command
|
||||
* stream output chunks into `tm_event_append(type=term.output_chunk)`
|
||||
* on completion: `tm_event_append(type=term.exit)` + maybe auto-checkpoint if matches patterns
|
||||
|
||||
4. **Checkpoint UX**
|
||||
|
||||
* Command palette:
|
||||
|
||||
* “Time Machine: Create Checkpoint”
|
||||
* “Time Machine: Restore Checkpoint”
|
||||
* Side panel timeline tree view.
|
||||
|
||||
### Minimal mapping: extension → MCP calls
|
||||
|
||||
* On project open: `tm_project_init`
|
||||
* On every capture: `tm_event_append`
|
||||
* On user command: `tm_checkpoint_create`
|
||||
* On restore: `tm_restore_checkpoint`
|
||||
* For UI: read `tm://projects/...` resources and/or `tm_list_checkpoints`
|
||||
|
||||
---
|
||||
|
||||
## Security & Safety (don’t ship without this)
|
||||
|
||||
### Path allowlist
|
||||
|
||||
* Never allow reading/writing outside `project.rootPath`
|
||||
* Normalize and validate paths (`realpath` checks)
|
||||
|
||||
### Secrets
|
||||
|
||||
* Default ignore:
|
||||
|
||||
* `.env`, `**/*.pem`, `id_rsa`, `**/wallet.json`, `**/*key*`
|
||||
* Add a `tm_policy_set` tool later to configure ignore patterns
|
||||
* Optional secret scanner before blob write
|
||||
|
||||
### Size limits
|
||||
|
||||
* Per blob max (e.g., 5–25MB)
|
||||
* Per event payload max
|
||||
* Reject huge output streams or chunk them with caps
|
||||
|
||||
### Timeouts
|
||||
|
||||
* Capsule exec timeout (default 60s, configurable)
|
||||
|
||||
---
|
||||
|
||||
## Next (recommended) MCP tool additions for “real product”
|
||||
|
||||
### Checkpoint + restore
|
||||
|
||||
* `tm_checkpoint_create` (build manifest from file system)
|
||||
* `tm_list_checkpoints`
|
||||
* `tm_restore_checkpoint` (write files from manifest)
|
||||
|
||||
### Diff
|
||||
|
||||
* `tm_diff_checkpoints` returning:
|
||||
|
||||
* file patch (if text)
|
||||
* binary changed marker
|
||||
* chat and terminal segment summaries
|
||||
|
||||
### Capsule
|
||||
|
||||
* `tm_capsule_create_or_attach`
|
||||
* `tm_capsule_exec` (streams output as events)
|
||||
* `tm_capsule_stop`
|
||||
|
||||
---
|
||||
|
||||
If you want, I’ll generate the **next code drop** too (still copy-pasteable):
|
||||
|
||||
* full `tm_checkpoint_create`, `tm_list_checkpoints`, `tm_restore_checkpoint`
|
||||
* manifest builder with ignore globs
|
||||
* Docker-based capsule exec that streams output chunks into events
|
||||
|
||||
Just say whether you want **Docker required** in MVP or “capsule optional.”
|
||||
|
||||
Here’s the **full “shopping list” of libraries you’ll actually need** to build **AI Time Machine MCP** (server + VSCode/Cursor client + container capsule), with the MCP bits verified via web sources. ([npm][1])
|
||||
|
||||
---
|
||||
|
||||
## MCP server (TypeScript / Node)
|
||||
|
||||
### Required (core)
|
||||
|
||||
* **`@modelcontextprotocol/sdk`** — MCP server primitives + stdio transport. ([npm][1])
|
||||
* **`zod`** — input validation + schemas (great with MCP tool schemas)
|
||||
* **`typescript`, `ts-node`, `@types/node`** — dev/build
|
||||
|
||||
### Storage (local event store)
|
||||
|
||||
Pick **one** SQLite option:
|
||||
|
||||
**Option A (fastest to ship)**
|
||||
|
||||
* **`better-sqlite3`** — sync, fast, simple. (Common choice for local daemons)
|
||||
|
||||
**Option B (async)**
|
||||
|
||||
* **`sqlite3`** or **`@vscode/sqlite3`** — async style, more boilerplate
|
||||
|
||||
### Blob store / content addressing
|
||||
|
||||
* Node built-ins: **`crypto`**, **`fs`**, **`path`**
|
||||
* Optional compression:
|
||||
|
||||
* **`zstd-codec`** or **`@mongodb-js/zstd`** (if you want zstd blobs)
|
||||
* or just **`zlib`** (built-in gzip/deflate)
|
||||
|
||||
### Ignore patterns + file crawling
|
||||
|
||||
* **`fast-glob`** or **`globby`** — build manifests efficiently
|
||||
* **`ignore`** — gitignore-style matching
|
||||
* Optional watchers (server-side):
|
||||
|
||||
* **`chokidar`** — file system watching (if you don’t rely only on extension capture)
|
||||
|
||||
### Diffs (checkpoint ↔ checkpoint)
|
||||
|
||||
* **`diff`** (npm: `diff`) — unified patches for text files
|
||||
* Optional “git-style” polish:
|
||||
|
||||
* **`isbinaryfile`** — detect binary files before attempting text diff
|
||||
* **`mime-types`** — infer mime type
|
||||
* **`js-yaml`** — if you store policy/config as YAML
|
||||
|
||||
---
|
||||
|
||||
## VSCode / Cursor extension (client capture)
|
||||
|
||||
### Required (extension)
|
||||
|
||||
* **`vscode`** (the API typings + runtime context)
|
||||
* **`@modelcontextprotocol/sdk`** *(optional in extension)* — only if your extension talks MCP directly.
|
||||
Many setups let the host client manage MCP; but if you run MCP inside the extension, include it.
|
||||
|
||||
### Terminal capture (realistic)
|
||||
|
||||
VS Code removed the old `Terminal.onDidWriteData` and replaced it with a global event (`window.onDidWriteTerminalData`). ([Visual Studio Code][2])
|
||||
So you’ll likely use:
|
||||
|
||||
* **VS Code API**: `window.onDidWriteTerminalData` for output capture (where available) ([Visual Studio Code][2])
|
||||
* plus `Terminal.sendText()` to run commands (for managed terminals)
|
||||
|
||||
> Note: terminal data capture capabilities vary by VS Code version / environment, so for MVP it’s smart to prioritize **“managed command runner”** (run commands via Node child process or capsule exec and stream logs into a custom terminal).
|
||||
|
||||
### File capture
|
||||
|
||||
* Use VS Code workspace events:
|
||||
|
||||
* `workspace.onDidSaveTextDocument`
|
||||
* `workspace.createFileSystemWatcher`
|
||||
(no extra libs needed unless you want advanced filtering)
|
||||
|
||||
### UI
|
||||
|
||||
* Tree view timeline: built-in VS Code TreeDataProvider
|
||||
* Optional:
|
||||
|
||||
* **`@vscode/webview-ui-toolkit`** for nicer panels
|
||||
|
||||
---
|
||||
|
||||
## Capsule (container-based “exact restore”)
|
||||
|
||||
### Docker control (Node)
|
||||
|
||||
* **`dockerode`** — the standard Node Docker API client. ([npm][3])
|
||||
* Optional helper:
|
||||
|
||||
* **`tar-fs`** or **`tar-stream`** — copying workspace into containers / exporting artifacts
|
||||
* **`stream`** (built-in) + Dockerode’s stream demux patterns (stdout/stderr)
|
||||
|
||||
Dockerode supports creating containers and attaching stdout/stderr. ([npm][3])
|
||||
|
||||
### Alternative approach (CLI)
|
||||
|
||||
If you don’t want Dockerode initially:
|
||||
|
||||
* call **`docker` CLI** via `child_process.spawn`
|
||||
* parse output + exit codes
|
||||
* still pin images by **digest**
|
||||
|
||||
This is often *easier to debug* in week 1–2.
|
||||
|
||||
---
|
||||
|
||||
## Optional but very useful (quality + safety)
|
||||
|
||||
### Performance + correctness
|
||||
|
||||
* **`p-limit`** — bound concurrency for hashing / snapshotting
|
||||
* **`lru-cache`** — memoize blob existence checks
|
||||
* **`xxhashjs`** — faster non-crypto hashing for internal chunking (keep SHA-256 for CAS identity)
|
||||
|
||||
### Security
|
||||
|
||||
* **`@dqbd/tiktoken`** (optional) — token estimation for chat retention rules
|
||||
* **`trufflehog`** *(external tool)* or **`gitleaks`** *(external tool)* — secret scanning before writing blobs (run as subprocess)
|
||||
|
||||
### Logging
|
||||
|
||||
* **`pino`** — fast JSON logs
|
||||
* **`uuid`** — though Node’s `crypto.randomUUID()` is enough
|
||||
|
||||
---
|
||||
|
||||
## MCP docs / SDK version note (important)
|
||||
|
||||
The MCP TypeScript SDK has a v2 line in development (pre-alpha) and recommends v1.x for production until v2 stabilizes. ([GitHub][4])
|
||||
So for your MVP, target the current stable **`@modelcontextprotocol/sdk`** release on npm. ([npm][1])
|
||||
|
||||
---
|
||||
|
||||
## Minimal “week-1 MVP” dependency set (if you want to stay lean)
|
||||
|
||||
**MCP server**
|
||||
|
||||
* `@modelcontextprotocol/sdk` ([npm][1])
|
||||
* `zod`
|
||||
* `better-sqlite3`
|
||||
* `fast-glob`
|
||||
* `ignore`
|
||||
|
||||
**Capsule (optional week-1)**
|
||||
|
||||
* `dockerode` ([npm][3])
|
||||
|
||||
**Extension**
|
||||
|
||||
* `vscode` typings + standard API (no extra libs)
|
||||
|
||||
---
|
||||
|
||||
If you tell me whether you want **(A) Dockerode** or **(B) docker CLI spawn** for capsule MVP, I’ll lock the final dependency list and generate the exact `package.json` for both the MCP server and the VSCode/Cursor extension.
|
||||
|
||||
[1]: https://www.npmjs.com/package/%40modelcontextprotocol/sdk?utm_source=chatgpt.com "modelcontextprotocol/sdk"
|
||||
[2]: https://code.visualstudio.com/updates/v1_39?utm_source=chatgpt.com "September 2019 (version 1.39)"
|
||||
[3]: https://www.npmjs.com/package/dockerode?utm_source=chatgpt.com "dockerode"
|
||||
[4]: https://github.com/modelcontextprotocol/typescript-sdk?utm_source=chatgpt.com "modelcontextprotocol/typescript-sdk"
|
||||
254
aitimemachine/QUICKSTART.md
Normal file
254
aitimemachine/QUICKSTART.md
Normal file
@ -0,0 +1,254 @@
|
||||
# Gitgram TimeMachine - Quick Start Guide
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Install globally
|
||||
npm install -g @gitgram/timemachine
|
||||
|
||||
# Or use locally in your project
|
||||
npm install @gitgram/timemachine
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### 1. Initialize Your Project
|
||||
|
||||
```bash
|
||||
cd your-project
|
||||
aitm init
|
||||
```
|
||||
|
||||
This creates a project registration in `~/.aitimemachine/db.sqlite`.
|
||||
|
||||
### 2. Create Your First Checkpoint
|
||||
|
||||
```bash
|
||||
aitm checkpoint "Initial state"
|
||||
```
|
||||
|
||||
This captures:
|
||||
- All files in your project (excluding node_modules, .git, etc.)
|
||||
- Content stored efficiently using SHA-256 deduplication
|
||||
- Manifest stored in SQLite database
|
||||
|
||||
### 3. Make Some Changes
|
||||
|
||||
```bash
|
||||
# Edit files, add features, etc.
|
||||
# Then create another checkpoint
|
||||
aitm checkpoint "Added authentication"
|
||||
```
|
||||
|
||||
### 4. List Your Checkpoints
|
||||
|
||||
```bash
|
||||
aitm list
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
Checkpoints for "your-project":
|
||||
|
||||
1. cp_1a2b3c4d5e6f7g8h... - Added authentication
|
||||
2025-12-24T10:30:00.000Z [files]
|
||||
|
||||
2. cp_9a8b7c6d5e4f3g2h... - Initial state
|
||||
2025-12-24T10:15:00.000Z [files]
|
||||
```
|
||||
|
||||
### 5. Restore to a Previous State
|
||||
|
||||
```bash
|
||||
# Show what will change
|
||||
aitm show cp_9a8b7c6d5e4f3g2h
|
||||
|
||||
# Restore (creates backup first)
|
||||
aitm restore cp_9a8b7c6d5e4f3g2h
|
||||
|
||||
# Or use hard mode (deletes files not in checkpoint)
|
||||
aitm restore cp_9a8b7c6d5e4f3g2h --mode hard
|
||||
```
|
||||
|
||||
### 6. Search Checkpoints
|
||||
|
||||
```bash
|
||||
aitm search "authentication"
|
||||
```
|
||||
|
||||
### 7. Search Knowledge Base (Cloud)
|
||||
|
||||
```bash
|
||||
AITM_API_URL=... AITM_API_KEY=... aitm kb-search "vector index"
|
||||
```
|
||||
|
||||
## AI Tool Integration (MCP)
|
||||
|
||||
### Claude Code Setup
|
||||
|
||||
Add to `~/.claude/claude_desktop_config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"aitimemachine": {
|
||||
"command": "aitm",
|
||||
"args": ["mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Now Claude Can:
|
||||
|
||||
```
|
||||
User: "Create a checkpoint before I refactor this"
|
||||
Claude: [Uses tm_checkpoint_create tool]
|
||||
✓ Checkpoint created: cp_abc123...
|
||||
|
||||
User: "Oh that broke things, go back!"
|
||||
Claude: [Uses tm_checkpoint_restore tool]
|
||||
✓ Restored to previous state
|
||||
```
|
||||
|
||||
## Storage Location
|
||||
|
||||
All data is stored in `~/.aitimemachine/`:
|
||||
|
||||
```
|
||||
~/.aitimemachine/
|
||||
├── db.sqlite # Projects, checkpoints, events
|
||||
└── blobs/ # Deduplicated file contents
|
||||
├── aa/
|
||||
│ └── aab3c4... # Content-addressable storage
|
||||
└── ...
|
||||
```
|
||||
|
||||
Per-project metadata in `.tm_internal/`:
|
||||
|
||||
```
|
||||
your-project/.tm_internal/
|
||||
├── tmp_restore/ # Temp directory for atomic restore
|
||||
├── backups/ # Backups created during restore
|
||||
└── tmp_old/ # Old states (can be cleaned up)
|
||||
```
|
||||
|
||||
## Production Features
|
||||
|
||||
### Safety First
|
||||
- ✅ **Atomic restore** - Never leaves project in partial state
|
||||
- ✅ **Backup before restore** - Always creates backup
|
||||
- ✅ **Project locking** - Prevents concurrent operations
|
||||
- ✅ **Path validation** - Prevents directory traversal attacks
|
||||
|
||||
### Performance
|
||||
- ✅ **Content deduplication** - Only unique content stored
|
||||
- ✅ **Sharded storage** - Fast lookups with `blobs/aa/bb/aabbcc...`
|
||||
- ✅ **Incremental scanning** - Only hash changed files (future)
|
||||
|
||||
### Docker Capsules (Advanced)
|
||||
|
||||
Create deterministic execution environments:
|
||||
|
||||
```bash
|
||||
# This would use Docker capsule tools via MCP
|
||||
# (Requires Docker installed)
|
||||
```
|
||||
|
||||
MCP tools available:
|
||||
- `tm_capsule_upsert` - Create capsule with pinned image digest
|
||||
- `tm_capsule_exec` - Run commands in isolated environment
|
||||
- `tm_capsule_stop` - Stop capsule
|
||||
|
||||
## Common Workflows
|
||||
|
||||
### Before Big Refactor
|
||||
|
||||
```bash
|
||||
aitm checkpoint "Before database refactor"
|
||||
# ... make changes ...
|
||||
# If it breaks:
|
||||
aitm restore <checkpoint-id>
|
||||
```
|
||||
|
||||
### Find When Something Broke
|
||||
|
||||
```bash
|
||||
# List recent checkpoints
|
||||
aitm list
|
||||
|
||||
# Search for specific changes
|
||||
aitm search "database"
|
||||
|
||||
# Check details
|
||||
aitm show <checkpoint-id>
|
||||
|
||||
# Restore
|
||||
aitm restore <checkpoint-id>
|
||||
```
|
||||
|
||||
### Regular Backups
|
||||
|
||||
```bash
|
||||
# Create checkpoints at milestones
|
||||
aitm checkpoint "Tests passing"
|
||||
aitm checkpoint "Feature complete"
|
||||
aitm checkpoint "Ready for review"
|
||||
```
|
||||
|
||||
## MCP Tools Reference
|
||||
|
||||
### Checkpoint Management
|
||||
- `tm_checkpoint_create` - Create new checkpoint
|
||||
- `tm_checkpoint_list` - List all checkpoints
|
||||
- `tm_checkpoint_restore` - Restore to checkpoint
|
||||
- `tm_diff_checkpoints` - Compare two checkpoints
|
||||
|
||||
### Search & Discovery
|
||||
- `tm_search` - Search checkpoints by name
|
||||
- `tm_stats` - Get storage statistics
|
||||
|
||||
### Docker Capsules
|
||||
- `tm_capsule_upsert` - Create/reuse capsule
|
||||
- `tm_capsule_exec` - Execute in capsule
|
||||
- `tm_capsule_stop` - Stop capsule
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Project not initialized"
|
||||
```bash
|
||||
aitm init
|
||||
```
|
||||
|
||||
### "Checkpoint not found"
|
||||
```bash
|
||||
# List available checkpoints
|
||||
aitm list
|
||||
|
||||
# Use correct ID (at least first 8 chars)
|
||||
aitm restore cp_1a2b3c4d
|
||||
```
|
||||
|
||||
### Large project taking too long
|
||||
The initial checkpoint may take time for large projects. Subsequent checkpoints will be faster with incremental scanning (coming soon).
|
||||
|
||||
### Out of disk space
|
||||
```bash
|
||||
# Check storage usage
|
||||
aitm stats
|
||||
|
||||
# Remove old checkpoints (manual cleanup for now)
|
||||
# Future: automatic GC and retention policies
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Read [README.md](README.md) for architecture details
|
||||
- Check [API.md](API.md) for complete MCP tool reference
|
||||
- See [IMPLEMENTATION_STATUS.md](IMPLEMENTATION_STATUS.md) for roadmap
|
||||
|
||||
## Getting Help
|
||||
|
||||
- 🐛 [Report Issues](https://github.com/gitgram-ai/gitgram-ai/issues)
|
||||
- 💬 [Discussions](https://github.com/gitgram-ai/gitgram-ai/discussions)
|
||||
- 📖 [Documentation](https://github.com/gitgram-ai/gitgram-ai/wiki)
|
||||
509
aitimemachine/README.md
Normal file
509
aitimemachine/README.md
Normal file
@ -0,0 +1,509 @@
|
||||
# Gitgram TimeMachine
|
||||
|
||||
**Git versions code. We version reality.**
|
||||
|
||||
> 🕐 **Like macOS Time Machine, but for AI coding!** When AI makes a mistake, go back in time and fix it.
|
||||
|
||||
Time Machine for AI-Assisted Development - Capture and restore your complete workspace state including files, terminal commands, AI tool interactions, and runtime environments through supported integrations.
|
||||
|
||||
## Quick Start - Time Machine Experience
|
||||
|
||||
```bash
|
||||
# AI broke something? One command to fix:
|
||||
aitm undo
|
||||
|
||||
# Go back to when tests were passing:
|
||||
aitm back-to "when tests passed"
|
||||
|
||||
# Go back 30 minutes:
|
||||
aitm back-to "30 minutes ago"
|
||||
|
||||
# Find when something broke:
|
||||
aitm why "tests failing"
|
||||
|
||||
# Binary search for breaking change:
|
||||
aitm bisect --test "npm test"
|
||||
```
|
||||
|
||||
📖 **[Full Documentation →](https://timemachine.gitgram.app/docs)**
|
||||
|
||||
## The Problem
|
||||
|
||||
AI-assisted development creates a new kind of failure:
|
||||
- **AI Temporal Confusion**: AIs don't understand "when" things happened or development rhythm
|
||||
- **Lost Conceptual Context**: AIs forget what concepts are active, completed, or blocked
|
||||
- **No Causal Understanding**: AIs can't connect state changes to their causes
|
||||
- Changes include: code, context, tool outputs, environment drift, terminal operations
|
||||
- When something breaks, you need to recover the **entire state**, not just files
|
||||
- Git can't answer:
|
||||
- "What exact terminal commands were run right before it broke?"
|
||||
- "What context did the AI have at that moment?"
|
||||
- "What environment (Node/Python/Docker image) was it using?"
|
||||
- "Can we restore the full working state instantly and reproduce the break deterministically?"
|
||||
|
||||
## What We Built
|
||||
|
||||
Gitgram TimeMachine is a **stateful, event-sourced layer** that captures:
|
||||
|
||||
- **File system state** via manifest + content-addressable storage
|
||||
- **Terminal commands + outputs + exit codes** (for managed sessions)
|
||||
- **AI tool interactions** via MCP protocol integration
|
||||
- **Deterministic runtime** via Docker capsules with pinned image digests
|
||||
|
||||
Then it exposes **time travel as an API** so AI agents and developers can:
|
||||
|
||||
- ✅ Restore any checkpoint (atomic, safe, with backup)
|
||||
- ✅ Compare any two moments (diffs computed on demand)
|
||||
- ✅ Automatically bisect regressions
|
||||
- ✅ Rehydrate AI context from checkpoints
|
||||
- ✅ Run in deterministic Docker capsules
|
||||
|
||||
**NEW: AI Time & Concept Realization** - Solves AI temporal confusion:
|
||||
- ✅ AIs understand "when" things happened
|
||||
- ✅ AIs track active vs completed concepts
|
||||
- ✅ AIs get focus recommendations based on context
|
||||
- ✅ AIs learn from development workflow patterns
|
||||
|
||||
## Why It's Different Than Git
|
||||
|
||||
| Capability | Git | Gitgram TimeMachine |
|
||||
|------------|-----|---------------|
|
||||
| Captures untracked files | ❌ | ✅ |
|
||||
| Terminal command history | ❌ | ✅ (managed sessions) |
|
||||
| AI context rehydration | ❌ | ✅ |
|
||||
| Deterministic environment | ❌ | ✅ (Docker capsules) |
|
||||
| Atomic restore with backup | ❌ | ✅ |
|
||||
| Content deduplication | ❌ | ✅ |
|
||||
| MCP protocol for AI tools | ❌ | ✅ |
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install -g @gitgram/timemachine
|
||||
```
|
||||
|
||||
## Authentication
|
||||
|
||||
Gitgram TimeMachine uses API keys for authentication (like OpenAI/ChatGPT):
|
||||
|
||||
### 1. Get Your API Key
|
||||
1. Sign up at [timemachine.gitgram.app](https://timemachine.gitgram.app)
|
||||
2. Go to Dashboard → API Keys
|
||||
3. Click "Create New Key"
|
||||
4. Copy your key (shown only once!)
|
||||
|
||||
### 2. Login with CLI
|
||||
```bash
|
||||
# Login with your API key
|
||||
aitm login --api-key aitm_xxxxxxxxxxxxx
|
||||
|
||||
# Or use browser-based login
|
||||
aitm login
|
||||
|
||||
# Check your auth status
|
||||
aitm whoami
|
||||
|
||||
# Logout
|
||||
aitm logout
|
||||
```
|
||||
|
||||
### 3. Use the API Directly
|
||||
```bash
|
||||
curl -H "X-API-Key: YOUR_API_KEY" \
|
||||
https://timemachine-api.gitgram.app/api/checkpoints
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Initialize in your project
|
||||
cd your-project
|
||||
aitm init
|
||||
|
||||
# AI automatically creates checkpoints via MCP
|
||||
# (when using Claude Code, Cursor, etc.)
|
||||
|
||||
# View your timeline
|
||||
aitm timeline
|
||||
|
||||
# See where you are
|
||||
aitm where
|
||||
|
||||
# Go back in time
|
||||
aitm restore <checkpoint-id>
|
||||
# or
|
||||
aitm back "before refactor"
|
||||
```
|
||||
|
||||
## New! AI-Friendly Commands
|
||||
|
||||
### For Users (CLI)
|
||||
```bash
|
||||
aitm timeline # Visual timeline with before/after pairs
|
||||
aitm where # Show current state and recent history
|
||||
aitm back [query] # Go back (ID, description, or time)
|
||||
aitm show_changes # What changed since last checkpoint
|
||||
```
|
||||
|
||||
### For AI (MCP Tools)
|
||||
```javascript
|
||||
// AI automatically uses these:
|
||||
where_am_i() // 🧭 Show current state
|
||||
go_back({ to: "before user store" }) // ⏪ Natural language restore
|
||||
show_changes() // 📊 What changed
|
||||
undo_last() // ↩️ Quick undo
|
||||
|
||||
// NEW: AI Time & Concept Realization
|
||||
ai_realize_concepts() // 🧠 Understand conceptual context
|
||||
ai_realize_time() // ⏰ Understand temporal context
|
||||
ai_suggest_focus() // 🎯 Get focus recommendations
|
||||
ai_analyze_transitions() // 🔄 Analyze workflow patterns
|
||||
```
|
||||
|
||||
## CLI Commands
|
||||
|
||||
### Setup & Project Management
|
||||
```bash
|
||||
aitm init # Initialize project tracking (opt-in, per project)
|
||||
aitm status # Show pending changes since last checkpoint
|
||||
aitm whoami # Show authenticated user
|
||||
```
|
||||
|
||||
### Checkpoints
|
||||
```bash
|
||||
aitm checkpoint "desc" # Manual checkpoint
|
||||
aitm list # List all checkpoints (--json for tools)
|
||||
aitm show <id> # Show checkpoint details
|
||||
aitm diff <from> [to] # Compare checkpoints (--json available)
|
||||
aitm preview <id> # Preview what restore would change
|
||||
```
|
||||
|
||||
### Restore & Time Travel
|
||||
```bash
|
||||
aitm restore <id> # Restore to checkpoint (atomic, with backup)
|
||||
aitm rewind --to <id> # Restore + generate context file for AI
|
||||
aitm resume # Start Claude with restored context injection
|
||||
aitm undo # Undo last restore (from backup)
|
||||
```
|
||||
|
||||
### Natural Language Time Travel (NEW!)
|
||||
```bash
|
||||
aitm when "tests started failing" # Find when something happened
|
||||
aitm back-to "when tests passed" # Natural language restore
|
||||
aitm back-to "2 hours ago" # Time-based restore
|
||||
aitm back-to last-green # Restore to last green state
|
||||
aitm what-changed --since "1 hour ago" # Show what changed
|
||||
aitm why "tests failing" # Analyze why something broke
|
||||
```
|
||||
|
||||
### File Operations
|
||||
```bash
|
||||
aitm file-history <file> # Show checkpoint history for file
|
||||
aitm get-file <id> <file> # Get file content at checkpoint
|
||||
aitm restore-file <id> <file> # Restore single file from checkpoint
|
||||
aitm blame <file> # Show which checkpoint introduced lines
|
||||
```
|
||||
|
||||
### AI Tool Wrappers
|
||||
```bash
|
||||
aitm claude # PTY-based Claude wrapper with transcript capture
|
||||
aitm run -- <command> # Run command with auto-checkpoint (before/after)
|
||||
```
|
||||
|
||||
### Search & Discovery
|
||||
```bash
|
||||
aitm search <query> # Search checkpoint names (--natural for NL)
|
||||
aitm conversation # Show conversation history
|
||||
aitm bisect --test "npm test" # Binary search for breaking change
|
||||
aitm stats # Storage statistics
|
||||
aitm kb-search <query> # Unified knowledge base search (cloud)
|
||||
```
|
||||
|
||||
### Cloud Sync
|
||||
```bash
|
||||
aitm login # Authenticate with cloud API
|
||||
aitm logout # Clear cloud credentials
|
||||
aitm sync # Sync checkpoints to cloud
|
||||
aitm cloud # View cloud status and data
|
||||
aitm pull <checkpoint-id> # Pull checkpoint from cloud
|
||||
```
|
||||
|
||||
### MCP Server
|
||||
```bash
|
||||
aitm mcp # Run MCP server for AI tools
|
||||
```
|
||||
|
||||
### Maintenance
|
||||
```bash
|
||||
aitm gc # Garbage collection (reclaim storage)
|
||||
aitm verify <project-id> # Verify checkpoint/blob integrity
|
||||
```
|
||||
|
||||
### Docker Capsules (Deterministic Environments)
|
||||
Available via MCP tools - see API.md for details.
|
||||
|
||||
## AI Tool Integration (MCP)
|
||||
|
||||
Gitgram TimeMachine integrates with AI coding assistants via the Model Context Protocol (MCP). When an MCP-compatible tool calls our tools, we capture those interactions.
|
||||
|
||||
### Transport
|
||||
- Default: **stdio** (`aitm mcp`)
|
||||
- Optional: HTTP/SSE can be added for custom clients, but stdio is the supported v1 path.
|
||||
|
||||
### Compatibility Matrix
|
||||
|
||||
| Tool | MCP Support | Real-time Capture | Context Rehydration |
|
||||
|------|-------------|-------------------|---------------------|
|
||||
| Claude Code | ✅ Yes | ✅ Tool calls recorded | ✅ Via restore |
|
||||
| Cursor | ✅ Yes (experimental) | ✅ Tool calls recorded | ✅ Via restore |
|
||||
| Claude Desktop | ✅ Yes | ✅ Tool calls recorded | ✅ Via restore |
|
||||
| Other MCP clients | ✅ Yes | ✅ Tool calls recorded | ✅ Via restore |
|
||||
|
||||
**Note**: We capture MCP tool calls in real-time. "Chat restore" means providing historical context to the AI, not modifying the tool's internal conversation UI.
|
||||
|
||||
### Setup for Claude Code
|
||||
|
||||
```bash
|
||||
# One-line setup (recommended)
|
||||
claude mcp add --transport stdio aitm -- npx -y @gitgram/timemachine-mcp
|
||||
|
||||
# Or with user-wide scope
|
||||
claude mcp add --scope user --transport stdio aitm -- npx -y @gitgram/timemachine-mcp
|
||||
```
|
||||
|
||||
### Setup for Cursor
|
||||
|
||||
```json
|
||||
// .cursor/mcp.json
|
||||
{
|
||||
"mcpServers": {
|
||||
"aitimemachine": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@gitgram/timemachine-mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### MCP Tools Available
|
||||
|
||||
#### AI-Friendly Navigation (NEW!)
|
||||
- `where_am_i` - Show current state and recent timeline
|
||||
- `go_back` - Natural language restore ("before user store", "30 minutes ago")
|
||||
- `show_changes` - Show what changed since last checkpoint
|
||||
- `undo_last` - Quick undo to previous checkpoint
|
||||
|
||||
#### AI Time & Concept Realization (NEW!)
|
||||
- `ai_realize_concepts` - Understand current conceptual context (active/completed/blocked concepts)
|
||||
- `ai_realize_time` - Understand temporal context (time patterns, velocity, intervals)
|
||||
- `ai_suggest_focus` - Get AI-driven focus recommendations with reasoning
|
||||
- `ai_analyze_transitions` - Analyze development state transitions and patterns
|
||||
|
||||
#### Checkpoint Management
|
||||
- `before_action` - Create "before" checkpoint (auto-called by AI)
|
||||
- `after_action` - Create "after" checkpoint with change summary
|
||||
- `checkpoint` - Manual checkpoint creation
|
||||
- `list_timepoints` - List all checkpoints
|
||||
- `restore` - Restore to checkpoint
|
||||
- `preview_restore` - Preview what restore will do
|
||||
|
||||
#### File Operations
|
||||
- `tm_get_file_at` - Get file content at checkpoint
|
||||
- `tm_file_history` - Get history of a file across checkpoints
|
||||
|
||||
#### Docker Capsules (Deterministic Execution)
|
||||
- `tm_capsule_upsert` - Create/update Docker capsule with pinned digest
|
||||
- `tm_capsule_exec` - Execute command in capsule
|
||||
|
||||
#### Search & Discovery
|
||||
- `tm_search` - Search checkpoint names
|
||||
- `tm_timeline` - Get timeline of events
|
||||
- `tm_stats` - Get storage statistics
|
||||
|
||||
#### Advanced
|
||||
- `tm_rewind_to_last_green` - Auto-rewind to last passing state
|
||||
- `tm_prompt_debug_regression` - Generate debug prompt for regressions
|
||||
- `tm_prompt_postmortem` - Generate incident postmortem
|
||||
- `tm_prompt_repro_steps` - Generate reproduction steps
|
||||
|
||||
#### Production & Maintenance
|
||||
- `tm_gc_run` - Garbage collection (mark & sweep to reclaim storage)
|
||||
- `tm_integrity_check` - Verify checkpoint and blob integrity
|
||||
|
||||
## Architecture
|
||||
|
||||
### Content-Addressable Storage (CAS)
|
||||
- **SHA-256 based** - Files stored by content hash
|
||||
- **Massive deduplication** - Only unique content stored once
|
||||
- **Sharded storage** - `blobs/aa/bb/aabbcc...`
|
||||
- **Efficient** - Perfect for large projects with many similar files
|
||||
|
||||
### Manifest-Based Checkpoints
|
||||
Each checkpoint is:
|
||||
- **Manifest** - List of files with their hashes
|
||||
- **Pointers** - Chat head, terminal head, capsule digest
|
||||
- **Immutable** - Checkpoints never change
|
||||
- **Lightweight** - Only manifests stored, blobs reused
|
||||
|
||||
### Atomic Restore Process
|
||||
|
||||
To ensure safety, restore operations are atomic and always create backups:
|
||||
|
||||
1. **Acquire lock** - Prevent concurrent operations via `.tm_lock`
|
||||
2. **Build in temp** - Materialize files from CAS to `.tm_internal/tmp_restore/`
|
||||
3. **Verify integrity** - Check all blobs exist and hashes match manifest
|
||||
4. **Backup current** - Save current workspace to `.tm_internal/backups/` (timestamped)
|
||||
5. **Atomic swap** - Move files from temp to workspace (Windows-safe strategy)
|
||||
6. **Release lock** - Allow other operations
|
||||
7. **Cleanup** - Remove temp directories
|
||||
|
||||
**Safety guarantees**:
|
||||
- Never partially restore (all-or-nothing)
|
||||
- Always backup before restore
|
||||
- Windows-compatible file operations
|
||||
- Project-level locking prevents conflicts
|
||||
|
||||
### Docker Capsules (Deterministic Environments)
|
||||
|
||||
Capsules provide deterministic execution environments:
|
||||
|
||||
- **Pin image digest** (not tag) - Guarantees exact same base image
|
||||
- **Mount workspace** - Project files available inside container
|
||||
- **Capture outputs** - Store stdout/stderr as blobs
|
||||
- **Reproducible execution** - Re-run commands in identical environment
|
||||
|
||||
**Use cases**:
|
||||
- Reproduce build/test failures exactly
|
||||
- Verify behavior across different Node/Python versions
|
||||
- Isolate environment-specific issues
|
||||
|
||||
## Storage Structure
|
||||
|
||||
```
|
||||
~/.aitimemachine/
|
||||
├── blobs/ # Content-addressable storage
|
||||
│ ├── aa/ # Sharded by hash prefix (first 2 chars)
|
||||
│ │ ├── bb/ # Second level shard (chars 3-4)
|
||||
│ │ │ └── aabbcc... # File contents (SHA-256 hash)
|
||||
│ └── ...
|
||||
├── events.db # SQLite database (projects, checkpoints, events)
|
||||
└── .tm_lock # Global lock file
|
||||
|
||||
<project-root>/.tm_internal/ # Per-project metadata
|
||||
├── tmp_restore/ # Temp directory for atomic restore
|
||||
├── backups/ # Current state backups (timestamped)
|
||||
└── .tm_lock # Project-level lock file
|
||||
```
|
||||
|
||||
## Ignore Patterns
|
||||
|
||||
By default, Gitgram TimeMachine excludes common build artifacts and dependencies to optimize storage:
|
||||
|
||||
**Default exclusions**:
|
||||
- `node_modules/**`, `.venv/**`, `venv/**`
|
||||
- `.git/**`, `.svn/**`
|
||||
- `dist/**`, `build/**`, `target/**`, `.next/**`
|
||||
- `*.pyc`, `__pycache__/**`
|
||||
- `.DS_Store`, `Thumbs.db`
|
||||
|
||||
**Security**: We do NOT automatically exclude secrets. You should:
|
||||
1. Never commit `.env` files with real credentials
|
||||
2. Use `.gitignore` patterns for sensitive files
|
||||
3. Review checkpoint contents before sharing
|
||||
|
||||
To customize patterns, modify `ignoreGlobs` in the project configuration.
|
||||
|
||||
## Examples
|
||||
|
||||
### Scenario: Restore to Working State
|
||||
|
||||
```bash
|
||||
# Search for the checkpoint you want
|
||||
aitm search "before refactor"
|
||||
|
||||
# List all checkpoints
|
||||
aitm list
|
||||
|
||||
# Go back in time (creates backup automatically)
|
||||
aitm restore cp_abc123def456
|
||||
```
|
||||
|
||||
### Scenario: Using from AI Tools
|
||||
|
||||
When an AI assistant uses our MCP tools:
|
||||
1. Tool calls are automatically recorded as events
|
||||
2. File changes are captured in checkpoints
|
||||
3. On restore, we provide "context rehydration" data to the AI
|
||||
4. AI can request debug prompts, postmortems, etc.
|
||||
|
||||
**Context Rehydration**: When restoring a checkpoint, the AI receives:
|
||||
- Checkpoint metadata (name, timestamp, scope)
|
||||
- List of files at that point
|
||||
- Event timeline up to that checkpoint
|
||||
- Suggested next steps
|
||||
|
||||
This allows the AI to understand "where we are" after a restore.
|
||||
|
||||
## Production Features (Current)
|
||||
|
||||
### Safety & Integrity
|
||||
- ✅ **Project locking** - Prevents concurrent operations via `.tm_lock`
|
||||
- ✅ **Atomic operations** - Never partially restore (all-or-nothing)
|
||||
- ✅ **Backup before restore** - Always creates timestamped backup
|
||||
- ✅ **Verify blobs** - Check hashes match before restore
|
||||
- ✅ **Windows-safe operations** - Cross-platform compatibility
|
||||
|
||||
### Performance
|
||||
- ✅ **Content deduplication** - SHA-256 based CAS stores unique content once
|
||||
- ✅ **Sharded storage** - Fast lookups via aa/bb/hash directory structure
|
||||
- ✅ **SQLite WAL mode** - Concurrent reads, safe writes
|
||||
- ✅ **Indexed queries** - Fast checkpoint and event lookups
|
||||
|
||||
### Limitations
|
||||
- ⚠️ **Terminal capture** - Only managed sessions (not all system terminals)
|
||||
- ⚠️ **Chat capture** - Only via MCP tool calls (not native tool UI access)
|
||||
- ⚠️ **No auto-discovery** - Projects must be initialized with `aitm init`
|
||||
|
||||
## Completed Features (v2.0)
|
||||
|
||||
### Natural Language Time Travel (NEW!)
|
||||
- ✅ **Natural language queries** - "when tests started failing", "2 hours ago"
|
||||
- ✅ **Smart restore** - `back-to` command with natural language support
|
||||
- ✅ **Change analysis** - `what-changed` and `why` commands
|
||||
- ✅ **Git bisect for checkpoints** - `bisect` to find breaking changes
|
||||
- ✅ **File blame** - Track which checkpoint introduced each line
|
||||
|
||||
### Cloud & Collaboration
|
||||
- ✅ **Cloud sync** - Sync checkpoints, sessions, and blobs to cloud API
|
||||
- ✅ **API key authentication** - Secure API key based auth
|
||||
- ✅ **Push/pull** - Push local checkpoints to cloud, pull from cloud
|
||||
- ✅ **Webhooks** - Real-time notifications on checkpoint events
|
||||
- ✅ **SSE events** - Server-sent events for live updates
|
||||
|
||||
### Advanced Features
|
||||
- ✅ **Auto-checkpoint rules** - Create checkpoints on "tests pass", "build success"
|
||||
- ✅ **PTY Claude wrapper** - Transcript capture with session tracking
|
||||
- ✅ **Context injection** - Rewind to checkpoint and inject context for AI
|
||||
- ✅ **JSON output** - All commands support `--json` for tool integration
|
||||
|
||||
## Roadmap (Future)
|
||||
|
||||
### Phase 3 - Enhanced Features
|
||||
- 🔜 **Export/import** - Share checkpoints via compressed archives
|
||||
- 🔜 **Team sharing** - Collaborate on checkpoints
|
||||
- 🔜 **Incremental scanning** - Optimize for large monorepos
|
||||
- 🔜 **Web dashboard** - Browser-based checkpoint explorer
|
||||
|
||||
## API Documentation
|
||||
|
||||
See the [online documentation](https://timemachine.gitgram.app/docs) for complete MCP tool reference.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
## Support
|
||||
|
||||
- 📖 [Documentation](https://timemachine.gitgram.app/docs)
|
||||
- 🐛 [Issue Tracker](https://github.com/gitgram-ai/gitgram-ai/issues)
|
||||
- 💬 [Discussions](https://github.com/gitgram-ai/gitgram-ai/discussions)
|
||||
48
aitimemachine/ROADMAP.md
Normal file
48
aitimemachine/ROADMAP.md
Normal file
@ -0,0 +1,48 @@
|
||||
# AITimeMachine Roadmap
|
||||
|
||||
## Phase 1: Core Infrastructure (Current)
|
||||
- ✅ Basic snapshot/revert functionality.
|
||||
- ✅ Conversation memory.
|
||||
- ✅ MCP protocol server.
|
||||
- ✅ CLI interface.
|
||||
- ✅ Git integration.
|
||||
- ✅ Basic documentation and website.
|
||||
|
||||
## Phase 2: Enhancements (Next Priority)
|
||||
- **Testing Suite**: Comprehensive Jest tests for all components.
|
||||
- **Performance Optimization**: Handle large codebases (selective watching, efficient diffs).
|
||||
- **Advanced Diffs**: Visual diff viewer in CLI/website.
|
||||
- **Configuration**: User config for auto-snapshots, confirmations.
|
||||
- **Error Handling**: Robust error recovery and logging.
|
||||
|
||||
## Phase 3: Integrations and Ecosystem
|
||||
- **AI Tool Partnerships**: Integrate with Claude Code, Cursor, Gemini CLI.
|
||||
- **Plugin System**: Allow custom plugins for tools.
|
||||
- **MCP Extensions**: More tools (e.g., diff viewer, analytics).
|
||||
- **Web Hooks**: REST API for web integrations.
|
||||
|
||||
## Phase 4: User Experience
|
||||
- **Web UI**: Simple web interface for browsing snapshots.
|
||||
- **Mobile App**: Expo app for remote management.
|
||||
- **Notifications**: Push alerts for AI actions.
|
||||
- **Collaboration**: Shared snapshots for teams.
|
||||
|
||||
## Phase 5: Advanced Features
|
||||
- **Cloud Sync**: Optional cloud storage for multi-device.
|
||||
- **Analytics**: Insights on AI usage, revert patterns.
|
||||
- **Security**: Encryption, audit trails, compliance.
|
||||
- **AI Insights**: ML suggestions based on revert history.
|
||||
|
||||
## Phase 6: Enterprise and Scale
|
||||
- **Multi-User**: Team accounts, permissions.
|
||||
- **Enterprise Integrations**: SSO, audit logs.
|
||||
- **Performance at Scale**: Handle 100K+ files.
|
||||
- **Global Distribution**: CDN for updates.
|
||||
|
||||
## Long-Term Vision
|
||||
- Become the standard safety layer for AI coding.
|
||||
- Open-source community with 1000+ contributors.
|
||||
- Unicorn valuation through widespread adoption.
|
||||
|
||||
## Contributing to Roadmap
|
||||
Open issues for specific features. Prioritize based on user feedback and AI tool integrations.
|
||||
85
aitimemachine/a2a/.betterer.results
Normal file
85
aitimemachine/a2a/.betterer.results
Normal file
@ -0,0 +1,85 @@
|
||||
// BETTERER RESULTS V2.
|
||||
//
|
||||
// If this file contains merge conflicts, use `betterer merge` to automatically resolve them:
|
||||
// https://phenomnomnominal.github.io/betterer/docs/results-file/#merge
|
||||
//
|
||||
exports[`TypeScript Strict Mode`] = {
|
||||
value: `{
|
||||
"src/client/client.ts:1182451551": [
|
||||
[444, 45, 6, "tsc: Argument of type \'TParams | undefined\' is not assignable to parameter of type \'TParams\'.\\n \'TParams | undefined\' is assignable to the constraint of type \'TParams\', but \'TParams\' could be instantiated with a different subtype of constraint \'JsonRpcParams\'.\\n Type \'undefined\' is not assignable to type \'TParams\'.\\n \'undefined\' is assignable to the constraint of type \'TParams\', but \'TParams\' could be instantiated with a different subtype of constraint \'JsonRpcParams\'.", "1898504825"],
|
||||
[474, 4, 6, "tsc: Type \'undefined\' is not assignable to type \'JSONRPCErrorResponse\'.", "2123913871"]
|
||||
],
|
||||
"src/client/multitransport-client.ts:1457951880": [
|
||||
[82, 24, 44, "tsc: Type \'Promise<AgentCard>\' is not assignable to type \'Promise<never>\'.\\n Type \'AgentCard\' is not assignable to type \'never\'.", "1356744557"],
|
||||
[101, 6, 47, "tsc: Argument of type \'(params: MessageSendParams, options?: RequestOptions | undefined) => Promise<SendMessageResult>\' is not assignable to parameter of type \'(params: MessageSendParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<SendMessageResult>\' is not assignable to type \'Promise<never>\'.\\n Type \'SendMessageResult\' is not assignable to type \'never\'.\\n Type \'Message\' is not assignable to type \'never\'.", "2571452626"],
|
||||
[178, 6, 65, "tsc: Argument of type \'(params: TaskPushNotificationConfig, options?: RequestOptions | undefined) => Promise<TaskPushNotificationConfig>\' is not assignable to parameter of type \'(params: TaskPushNotificationConfig, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<TaskPushNotificationConfig>\' is not assignable to type \'Promise<never>\'.\\n Type \'TaskPushNotificationConfig\' is not assignable to type \'never\'.", "2789685747"],
|
||||
[197, 6, 65, "tsc: Argument of type \'(params: GetTaskPushNotificationConfigParams, options?: RequestOptions | undefined) => Promise<TaskPushNotificationConfig>\' is not assignable to parameter of type \'(params: TaskIdParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<TaskPushNotificationConfig>\' is not assignable to type \'Promise<never>\'.\\n Type \'TaskPushNotificationConfig\' is not assignable to type \'never\'.", "1581152103"],
|
||||
[216, 6, 66, "tsc: Argument of type \'(params: ListTaskPushNotificationConfigParams, options?: RequestOptions | undefined) => Promise<TaskPushNotificationConfig[]>\' is not assignable to parameter of type \'(params: ListTaskPushNotificationConfigParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<TaskPushNotificationConfig[]>\' is not assignable to type \'Promise<never>\'.\\n Type \'TaskPushNotificationConfig[]\' is not assignable to type \'never\'.", "4161961235"],
|
||||
[230, 6, 68, "tsc: Argument of type \'(params: DeleteTaskPushNotificationConfigParams, options?: RequestOptions | undefined) => Promise<void>\' is not assignable to parameter of type \'(params: DeleteTaskPushNotificationConfigParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<void>\' is not assignable to type \'Promise<never>\'.\\n Type \'void\' is not assignable to type \'never\'.", "1244975368"],
|
||||
[241, 6, 43, "tsc: Argument of type \'(params: TaskQueryParams, options?: RequestOptions | undefined) => Promise<Task>\' is not assignable to parameter of type \'(params: TaskQueryParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<Task>\' is not assignable to type \'Promise<never>\'.\\n Type \'Task\' is not assignable to type \'never\'.", "2875666270"],
|
||||
[253, 6, 46, "tsc: Argument of type \'(params: TaskIdParams, options?: RequestOptions | undefined) => Promise<Task>\' is not assignable to parameter of type \'(params: TaskIdParams, options?: RequestOptions | undefined) => Promise<never>\'.\\n Type \'Promise<Task>\' is not assignable to type \'Promise<never>\'.\\n Type \'Task\' is not assignable to type \'never\'.", "588661070"]
|
||||
],
|
||||
"src/client/transports/json_rpc_transport.ts:956778244": [
|
||||
[54, 6, 9, "tsc: Type \'undefined\' does not satisfy the constraint \'{ [key: string]: any; }\'.", "2620553983"],
|
||||
[169, 38, 16, "tsc: Type \'TExtensionParams\' does not satisfy the constraint \'{ [key: string]: any; }\'.", "3740514676"]
|
||||
],
|
||||
"src/server/events/execution_event_bus.ts:341476271": [
|
||||
[248, 15, 4, "tsc: Expected 2 arguments, but got 1.", "2087764327"],
|
||||
[271, 15, 4, "tsc: Expected 2 arguments, but got 1.", "2087764327"]
|
||||
],
|
||||
"src/server/express/rest_handler.ts:2436698925": [
|
||||
[204, 50, 17, "tsc: Argument of type \'unknown\' is not assignable to parameter of type \'Message | Task | TaskArtifactUpdateEvent | TaskStatusUpdateEvent\'.", "3749434707"]
|
||||
],
|
||||
"src/server/request_handler/default_request_handler.ts:1208203039": [
|
||||
[433, 22, 23, "tsc: Type \'Message1 | Message2 | undefined\' is not assignable to type \'Message1\'.\\n Type \'undefined\' is not assignable to type \'Message1\'.", "1479072653"],
|
||||
[433, 47, 19, "tsc: Type \'Message2 | undefined\' is not assignable to type \'Message1\'.\\n Type \'undefined\' is not assignable to type \'Message1\'.", "2682097303"],
|
||||
[619, 6, 6, "tsc: Type \'string | undefined\' is not assignable to type \'string\'.\\n Type \'undefined\' is not assignable to type \'string\'.", "1741934565"]
|
||||
],
|
||||
"src/server/transports/jsonrpc/jsonrpc_transport_handler.ts:3071717608": [
|
||||
[55, 12, 10, "tsc: Variable \'rpcRequest\' is used before being assigned.", "3927050741"]
|
||||
],
|
||||
"src/types/converters/from_proto.ts:3167572508": [
|
||||
[84, 6, 22, "tsc: Type \'PushNotificationConfig | undefined\' is not assignable to type \'PushNotificationConfig1\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationConfig1\'.", "2368778428"],
|
||||
[138, 63, 30, "tsc: Argument of type \'PushNotificationConfig | undefined\' is not assignable to parameter of type \'PushNotificationConfig\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationConfig\'.", "4185699816"],
|
||||
[153, 67, 21, "tsc: Argument of type \'AuthenticationInfo | undefined\' is not assignable to parameter of type \'AuthenticationInfo\'.\\n Type \'undefined\' is not assignable to type \'AuthenticationInfo\'.", "243589825"],
|
||||
[203, 8, 4, "tsc: Type \'undefined | { [key: string]: any; }\' is not assignable to type \'{ [k: string]: unknown; }\'.\\n Type \'undefined\' is not assignable to type \'{ [k: string]: unknown; }\'.", "2087377941"],
|
||||
[211, 6, 7, "tsc: Type \'Message | undefined\' is not assignable to type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "1236122734"],
|
||||
[211, 33, 15, "tsc: Argument of type \'Message | undefined\' is not assignable to parameter of type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "1725852363"],
|
||||
[212, 56, 21, "tsc: Argument of type \'SendMessageConfiguration | undefined\' is not assignable to parameter of type \'SendMessageConfiguration\'.\\n Type \'undefined\' is not assignable to type \'SendMessageConfiguration\'.", "2141283338"],
|
||||
[221, 6, 6, "tsc: Type \'Message | undefined\' is not assignable to type \'Message | Task\'.\\n Type \'undefined\' is not assignable to type \'Message | Task\'.", "2123913871"],
|
||||
[230, 35, 11, "tsc: Argument of type \'TaskStatus | undefined\' is not assignable to parameter of type \'TaskStatus\'.\\n Type \'undefined\' is not assignable to type \'TaskStatus\'.", "3290243250"],
|
||||
[233, 6, 7, "tsc: Type \'(Message | undefined)[]\' is not assignable to type \'Message1[]\'.\\n Type \'Message | undefined\' is not assignable to type \'Message1\'.\\n Type \'undefined\' is not assignable to type \'Message1\'.", "502375463"],
|
||||
[240, 33, 13, "tsc: Argument of type \'Message | undefined\' is not assignable to parameter of type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "586067534"],
|
||||
[286, 6, 22, "tsc: Type \'PushNotificationConfig | undefined\' is not assignable to type \'PushNotificationConfig1\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationConfig1\'.", "2368778428"],
|
||||
[286, 63, 30, "tsc: Argument of type \'PushNotificationConfig | undefined\' is not assignable to parameter of type \'PushNotificationConfig\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationConfig\'.", "1238494243"],
|
||||
[389, 38, 34, "tsc: Argument of type \'OAuthFlows | undefined\' is not assignable to parameter of type \'OAuthFlows\'.\\n Type \'undefined\' is not assignable to type \'OAuthFlows\'.", "2386187236"],
|
||||
[468, 35, 12, "tsc: Argument of type \'TaskStatus | undefined\' is not assignable to parameter of type \'TaskStatus\'.\\n Type \'undefined\' is not assignable to type \'TaskStatus\'.", "3657456819"],
|
||||
[479, 35, 14, "tsc: Argument of type \'Artifact | undefined\' is not assignable to parameter of type \'Artifact\'.\\n Type \'undefined\' is not assignable to type \'Artifact\'.", "3619116505"],
|
||||
[491, 8, 6, "tsc: Type \'Message | undefined\' is not assignable to type \'Message | Task | TaskArtifactUpdateEvent | TaskStatusUpdateEvent\'.\\n Type \'undefined\' is not assignable to type \'Message | Task | TaskArtifactUpdateEvent | TaskStatusUpdateEvent\'.", "2123913871"]
|
||||
],
|
||||
"src/types/converters/to_proto.ts:3424105456": [
|
||||
[52, 38, 18, "tsc: Argument of type \'AgentProvider | undefined\' is not assignable to parameter of type \'AgentProvider\'.\\n Type \'undefined\' is not assignable to type \'AgentProvider\'.", "1428962279"],
|
||||
[68, 6, 33, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "212802179"],
|
||||
[223, 6, 6, "tsc: Type \'undefined\' is not assignable to type \'AgentProvider\'.", "2123913871"],
|
||||
[233, 6, 9, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "4113723737"],
|
||||
[234, 6, 17, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "4249068261"],
|
||||
[263, 58, 31, "tsc: Argument of type \'string | undefined\' is not assignable to parameter of type \'string\'.\\n Type \'undefined\' is not assignable to type \'string\'.", "113348213"],
|
||||
[303, 6, 8, "tsc: Type \'string | undefined\' is not assignable to type \'string\'.\\n Type \'undefined\' is not assignable to type \'string\'.", "2373810498"],
|
||||
[309, 6, 6, "tsc: Type \'undefined\' is not assignable to type \'PushNotificationConfig\'.", "2123913871"],
|
||||
[316, 65, 21, "tsc: Argument of type \'PushNotificationAuthenticationInfo | undefined\' is not assignable to parameter of type \'PushNotificationAuthenticationInfo\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationAuthenticationInfo\'.", "243589825"],
|
||||
[339, 10, 5, "tsc: Type \'Message | undefined\' is not assignable to type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "189936718"],
|
||||
[384, 6, 6, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "1326815083"],
|
||||
[385, 6, 9, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "11251860"],
|
||||
[389, 64, 19, "tsc: Function lacks ending return statement and return type does not include \'undefined\'.", "2245381585"],
|
||||
[394, 10, 5, "tsc: Type \'Message | undefined\' is not assignable to type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "189936718"],
|
||||
[440, 6, 7, "tsc: Type \'(Message | undefined)[]\' is not assignable to type \'Message[]\'.\\n Type \'Message | undefined\' is not assignable to type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "502375463"],
|
||||
[448, 30, 14, "tsc: Argument of type \'Message2 | undefined\' is not assignable to parameter of type \'Message\'.\\n Type \'undefined\' is not assignable to type \'Message\'.", "3366941076"],
|
||||
[501, 10, 8, "tsc: Type \'string | undefined\' is not assignable to type \'string\'.\\n Type \'undefined\' is not assignable to type \'string\'.", "3750463409"],
|
||||
[506, 10, 8, "tsc: Type \'string | undefined\' is not assignable to type \'string\'.\\n Type \'undefined\' is not assignable to type \'string\'.", "3750463409"],
|
||||
[527, 43, 20, "tsc: Argument of type \'MessageSendConfiguration | undefined\' is not assignable to parameter of type \'MessageSendConfiguration\'.\\n Type \'undefined\' is not assignable to type \'MessageSendConfiguration\'.", "2639404487"],
|
||||
[534, 6, 6, "tsc: Type \'undefined\' is not assignable to type \'SendMessageConfiguration\'.", "2123913871"],
|
||||
[538, 6, 8, "tsc: Type \'boolean | undefined\' is not assignable to type \'boolean\'.\\n Type \'undefined\' is not assignable to type \'boolean\'.", "3894148428"],
|
||||
[540, 55, 36, "tsc: Argument of type \'PushNotificationConfig | undefined\' is not assignable to parameter of type \'PushNotificationConfig\'.\\n Type \'undefined\' is not assignable to type \'PushNotificationConfig\'.", "1308984194"]
|
||||
]
|
||||
}`
|
||||
};
|
||||
8
aitimemachine/a2a/.betterer.ts
Normal file
8
aitimemachine/a2a/.betterer.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { typescript } from '@betterer/typescript';
|
||||
|
||||
export default {
|
||||
'TypeScript Strict Mode': () =>
|
||||
typescript('./tsconfig.json', {
|
||||
strict: true,
|
||||
}).include('./src/**/*.ts', './tck/**/*.ts'),
|
||||
};
|
||||
15
aitimemachine/a2a/.gemini/settings.json
Normal file
15
aitimemachine/a2a/.gemini/settings.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"tools": {
|
||||
"allowed": [
|
||||
"run_shell_command(npm run build)",
|
||||
"run_shell_command(npm test)",
|
||||
"run_shell_command(npm run test)",
|
||||
"run_shell_command(npm run test:edge)",
|
||||
"run_shell_command(npm run test-build)",
|
||||
"run_shell_command(npm run coverage)",
|
||||
"run_shell_command(npm run lint)",
|
||||
"run_shell_command(npm run lint:ci)",
|
||||
"run_shell_command(npm run format:readme)"
|
||||
]
|
||||
}
|
||||
}
|
||||
7
aitimemachine/a2a/.github/CODEOWNERS
vendored
Normal file
7
aitimemachine/a2a/.github/CODEOWNERS
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
# Code owners file.
|
||||
# This file controls who is tagged for review for any given pull request.
|
||||
#
|
||||
# For syntax help see:
|
||||
# https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax
|
||||
|
||||
* @a2aproject/google-a2a-js
|
||||
33
aitimemachine/a2a/.github/ISSUE_TEMPLATE/bug-report.yml
vendored
Normal file
33
aitimemachine/a2a/.github/ISSUE_TEMPLATE/bug-report.yml
vendored
Normal file
@ -0,0 +1,33 @@
|
||||
name: 🐞 Bug Report
|
||||
description: File a bug report
|
||||
title: "[Bug]: "
|
||||
type: "Bug"
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for stopping by to let us know something could be better!
|
||||
Private Feedback? Please use this [Google form](https://goo.gle/a2a-feedback)
|
||||
- type: textarea
|
||||
id: what-happened
|
||||
attributes:
|
||||
label: What happened?
|
||||
description: Also tell us what you expected to happen and how to reproduce the issue.
|
||||
placeholder: Tell us what you see!
|
||||
value: "A bug happened!"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Relevant log output
|
||||
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
|
||||
render: shell
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Code of Conduct
|
||||
description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/google-a2a/A2A?tab=coc-ov-file#readme)
|
||||
options:
|
||||
- label: I agree to follow this project's Code of Conduct
|
||||
required: true
|
||||
41
aitimemachine/a2a/.github/ISSUE_TEMPLATE/feature-request.yml
vendored
Normal file
41
aitimemachine/a2a/.github/ISSUE_TEMPLATE/feature-request.yml
vendored
Normal file
@ -0,0 +1,41 @@
|
||||
name: 💡 Feature Request
|
||||
description: Suggest an idea for this repository
|
||||
title: "[Feat]: "
|
||||
type: "Feature"
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for stopping by to let us know something could be better!
|
||||
Private Feedback? Please use this [Google form](https://goo.gle/a2a-feedback)
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Is your feature request related to a problem? Please describe.
|
||||
description: A clear and concise description of what the problem is.
|
||||
placeholder: Ex. I'm always frustrated when [...]
|
||||
- type: textarea
|
||||
id: describe
|
||||
attributes:
|
||||
label: Describe the solution you'd like
|
||||
description: A clear and concise description of what you want to happen.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Describe alternatives you've considered
|
||||
description: A clear and concise description of any alternative solutions or features you've considered.
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Add any other context or screenshots about the feature request here.
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Code of Conduct
|
||||
description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/google-a2a/A2A?tab=coc-ov-file#readme)
|
||||
options:
|
||||
- label: I agree to follow this project's Code of Conduct
|
||||
required: true
|
||||
15
aitimemachine/a2a/.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
15
aitimemachine/a2a/.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
# Description
|
||||
|
||||
Thank you for opening a Pull Request!
|
||||
Before submitting your PR, there are a few things you can do to make sure it goes smoothly:
|
||||
|
||||
- [ ] Follow the [`CONTRIBUTING` Guide](https://github.com/google-a2a/a2a-js/blob/main/CONTRIBUTING.md).
|
||||
- [ ] Make your Pull Request title in the <https://www.conventionalcommits.org/> specification.
|
||||
- Important Prefixes for [release-please](https://github.com/googleapis/release-please):
|
||||
- `fix:` which represents bug fixes, and correlates to a [SemVer](https://semver.org/) patch.
|
||||
- `feat:` represents a new feature, and correlates to a SemVer minor.
|
||||
- `feat!:`, or `fix!:`, `refactor!:`, etc., which represent a breaking change (indicated by the `!`) and will result in a SemVer major.
|
||||
- [ ] Ensure the tests and linter pass
|
||||
- [ ] Appropriate docs were updated (if necessary)
|
||||
|
||||
Fixes #<issue_number_goes_here> 🦕
|
||||
30
aitimemachine/a2a/.github/workflows/build-tests.yml
vendored
Normal file
30
aitimemachine/a2a/.github/workflows/build-tests.yml
vendored
Normal file
@ -0,0 +1,30 @@
|
||||
# Ensures no accidential Node.js API usage in browser and Edge compatible entrypoints.
|
||||
|
||||
name: Run Build Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
- '.github/CODEOWNERS'
|
||||
- 'test/**'
|
||||
|
||||
jobs:
|
||||
test:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- run: npm run test-build
|
||||
26
aitimemachine/a2a/.github/workflows/conventional-commits.yml
vendored
Normal file
26
aitimemachine/a2a/.github/workflows/conventional-commits.yml
vendored
Normal file
@ -0,0 +1,26 @@
|
||||
name: "Conventional Commits"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types:
|
||||
- opened
|
||||
- edited
|
||||
- synchronize
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
main:
|
||||
permissions:
|
||||
pull-requests: read
|
||||
statuses: write
|
||||
name: Validate PR Title
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: semantic-pull-request
|
||||
uses: amannn/action-semantic-pull-request@v5.5.3
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
validateSingleCommit: false
|
||||
164
aitimemachine/a2a/.github/workflows/coverage-comment.yml
vendored
Normal file
164
aitimemachine/a2a/.github/workflows/coverage-comment.yml
vendored
Normal file
@ -0,0 +1,164 @@
|
||||
name: Post Coverage Comment
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["Run Unit Tests"]
|
||||
types:
|
||||
- completed
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
actions: read
|
||||
|
||||
jobs:
|
||||
comment:
|
||||
runs-on: ubuntu-latest
|
||||
if: >
|
||||
github.event.workflow_run.event == 'pull_request' &&
|
||||
github.event.workflow_run.conclusion == 'success'
|
||||
steps:
|
||||
- name: Download Coverage Artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
name: coverage-data
|
||||
|
||||
- name: Upload Coverage Report
|
||||
id: upload-report
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: coverage-report
|
||||
path: coverage/
|
||||
retention-days: 14
|
||||
|
||||
- name: Post Comment
|
||||
uses: actions/github-script@v6
|
||||
env:
|
||||
ARTIFACT_URL: ${{ steps.upload-report.outputs.artifact-url }}
|
||||
with:
|
||||
script: |
|
||||
const fs = require('fs');
|
||||
|
||||
const { owner, repo } = context.repo;
|
||||
const headSha = context.payload.workflow_run.head_commit.id;
|
||||
|
||||
const loadSummary = (path) => {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(path, 'utf8'));
|
||||
} catch (e) {
|
||||
console.log(`Could not read ${path}: ${e}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const baseSummary = loadSummary('./coverage-base-summary.json');
|
||||
const prSummary = loadSummary('./coverage-pr-summary.json');
|
||||
|
||||
if (!baseSummary || !prSummary) {
|
||||
console.log("Missing coverage data, skipping comment.");
|
||||
return;
|
||||
}
|
||||
|
||||
let markdown = `### 🧪 Code Coverage\n\n`;
|
||||
|
||||
markdown += `[⬇️ **Download Full Report**](${process.env.ARTIFACT_URL})\n\n`;
|
||||
|
||||
const metric = 'statements';
|
||||
const getPct = (summaryItem, m) => summaryItem && summaryItem[m] ? summaryItem[m].pct : 0;
|
||||
|
||||
const formatDiff = (oldPct, newPct) => {
|
||||
const diff = (newPct - oldPct).toFixed(2);
|
||||
|
||||
let icon = '';
|
||||
if (diff > 0) icon = '🟢';
|
||||
else if (diff < 0) icon = '🔴';
|
||||
else icon = '⚪️';
|
||||
|
||||
const diffStr = diff > 0 ? `+${diff}%` : `${diff}%`;
|
||||
return `${icon} ${diffStr}`;
|
||||
};
|
||||
|
||||
const fileUrl = (path) => `https://github.com/${owner}/${repo}/blob/${headSha}/${path}`;
|
||||
|
||||
const allFiles = new Set([...Object.keys(baseSummary), ...Object.keys(prSummary)]);
|
||||
allFiles.delete('total');
|
||||
const workspacePath = process.env.GITHUB_WORKSPACE ? process.env.GITHUB_WORKSPACE + '/' : '';
|
||||
|
||||
let changedRows = [];
|
||||
let newRows = [];
|
||||
|
||||
for (const file of allFiles) {
|
||||
const baseFile = baseSummary[file];
|
||||
const prFile = prSummary[file];
|
||||
|
||||
if (!prFile) continue;
|
||||
|
||||
const oldPct = getPct(baseFile, metric);
|
||||
const newPct = getPct(prFile, metric);
|
||||
|
||||
const relativeFilePath = file.replace(workspacePath, '');
|
||||
const linkedPath = `[${relativeFilePath}](${fileUrl(relativeFilePath)})`;
|
||||
|
||||
if (!baseFile && prFile) {
|
||||
newRows.push(`| ${linkedPath} (**new**) | — | ${newPct}% | — |\n`);
|
||||
} else if (oldPct !== newPct) {
|
||||
changedRows.push(`| ${linkedPath} | ${oldPct}% | ${newPct}% | ${formatDiff(oldPct, newPct)} |\n`);
|
||||
}
|
||||
}
|
||||
|
||||
if (changedRows.length === 0 && newRows.length === 0) {
|
||||
markdown += `\n_No coverage changes._\n`;
|
||||
} else {
|
||||
markdown += `| | Base | PR | Delta |\n`;
|
||||
markdown += `| :--- | :---: | :---: | :---: |\n`;
|
||||
|
||||
if (changedRows.length > 0) {
|
||||
markdown += changedRows.sort().join('');
|
||||
}
|
||||
if (newRows.length > 0) {
|
||||
markdown += newRows.sort().join('');
|
||||
}
|
||||
|
||||
const oldTotalPct = getPct(baseSummary.total, metric);
|
||||
const newTotalPct = getPct(prSummary.total, metric);
|
||||
if (oldTotalPct !== newTotalPct) {
|
||||
markdown += `| **Total** | ${oldTotalPct}% | ${newTotalPct}% | ${formatDiff(oldTotalPct, newTotalPct)} |\n`;
|
||||
}
|
||||
}
|
||||
|
||||
markdown += `\n\n_Generated by [coverage-comment.yml](https://github.com/a2aproject/a2a-js/actions/workflows/coverage-comment.yml)_`;
|
||||
|
||||
const prNumber = fs.readFileSync('./PR_NUMBER', 'utf8').trim();
|
||||
|
||||
if (!prNumber) {
|
||||
console.log("No PR number found.");
|
||||
return;
|
||||
}
|
||||
|
||||
const comments = await github.rest.issues.listComments({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: prNumber,
|
||||
});
|
||||
|
||||
const existingComment = comments.data.find(c =>
|
||||
c.body.includes('Generated by [coverage-comment.yml]') &&
|
||||
c.user.type === 'Bot'
|
||||
);
|
||||
|
||||
if (existingComment) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: existingComment.id,
|
||||
body: markdown
|
||||
});
|
||||
} else {
|
||||
await github.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: prNumber,
|
||||
body: markdown
|
||||
});
|
||||
}
|
||||
29
aitimemachine/a2a/.github/workflows/lint.yml
vendored
Normal file
29
aitimemachine/a2a/.github/workflows/lint.yml
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
name: Run Linter & Formatter
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
- '.github/CODEOWNERS'
|
||||
|
||||
jobs:
|
||||
eslint:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: |
|
||||
package-lock.json
|
||||
src/samples/package-lock.json
|
||||
- run: npm ci && (cd src/samples && npm ci)
|
||||
- run: npm run lint:ci
|
||||
40
aitimemachine/a2a/.github/workflows/npm-publish.yml
vendored
Normal file
40
aitimemachine/a2a/.github/workflows/npm-publish.yml
vendored
Normal file
@ -0,0 +1,40 @@
|
||||
# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
|
||||
# For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
|
||||
|
||||
name: Publish to NPM
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [created]
|
||||
|
||||
jobs:
|
||||
publish-npm:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
|
||||
# Now configure with the publish service for install.
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 18
|
||||
registry-url: 'https://wombat-dressing-room.appspot.com/'
|
||||
|
||||
- name: Publish to NPM
|
||||
run: |
|
||||
if [ "${{ github.event.release.prerelease }}" = "true" ]; then
|
||||
npm publish --provenance --access public --tag next
|
||||
else
|
||||
npm publish --provenance --access public
|
||||
fi
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
||||
19
aitimemachine/a2a/.github/workflows/release-please.yml
vendored
Normal file
19
aitimemachine/a2a/.github/workflows/release-please.yml
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
name: release-please
|
||||
|
||||
jobs:
|
||||
release-please:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: googleapis/release-please-action@v4
|
||||
with:
|
||||
token: ${{ secrets.A2A_BOT_PAT }}
|
||||
release-type: node
|
||||
121
aitimemachine/a2a/.github/workflows/run-tck.yaml
vendored
Normal file
121
aitimemachine/a2a/.github/workflows/run-tck.yaml
vendored
Normal file
@ -0,0 +1,121 @@
|
||||
name: Run TCK
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
- '.github/CODEOWNERS'
|
||||
- 'test/**'
|
||||
- 'src/samples/**'
|
||||
|
||||
|
||||
env:
|
||||
# Tag of the TCK
|
||||
TCK_VERSION: 0.3.0.beta3
|
||||
# Tells uv to not need a venv, and instead use system
|
||||
UV_SYSTEM_PYTHON: 1
|
||||
# Base URL for the SUT agent
|
||||
SUT_BASE_URL: http://localhost:41241
|
||||
# Base URL for the SUT agent JSON-RPC transport
|
||||
SUT_JSONRPC_URL: http://localhost:41241/a2a/jsonrpc
|
||||
# Slow system on CI
|
||||
TCK_STREAMING_TIMEOUT: 5.0
|
||||
|
||||
# Only run the latest job
|
||||
concurrency:
|
||||
group: '${{ github.workflow }} @ ${{ github.head_ref || github.ref }}'
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
tck-test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20, 22, 24]
|
||||
steps:
|
||||
- name: Checkout a2a-js
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: |
|
||||
npm ci
|
||||
npm run build
|
||||
- name: Checkout a2a-tck
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: a2aproject/a2a-tck
|
||||
path: tck/a2a-tck
|
||||
ref: ${{ env.TCK_VERSION }}
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version-file: "tck/a2a-tck/pyproject.toml"
|
||||
- name: Install uv and Python dependencies
|
||||
run: |
|
||||
pip install uv
|
||||
uv pip install -e .
|
||||
working-directory: tck/a2a-tck
|
||||
- name: Start SUT
|
||||
run: |
|
||||
cd tck
|
||||
npm run tck:sut-agent &
|
||||
- name: Wait for SUT to start
|
||||
run: |
|
||||
URL="${{ env.SUT_BASE_URL }}/.well-known/agent-card.json"
|
||||
EXPECTED_STATUS=200
|
||||
TIMEOUT=120
|
||||
RETRY_INTERVAL=2
|
||||
START_TIME=$(date +%s)
|
||||
|
||||
while true; do
|
||||
# Calculate elapsed time
|
||||
CURRENT_TIME=$(date +%s)
|
||||
ELAPSED_TIME=$((CURRENT_TIME - START_TIME))
|
||||
|
||||
# Check for timeout
|
||||
if [ "$ELAPSED_TIME" -ge "$TIMEOUT" ]; then
|
||||
echo "❌ Timeout: Server did not respond with status $EXPECTED_STATUS within $TIMEOUT seconds."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get HTTP status code. || true is to reporting a failure to connect as an error
|
||||
HTTP_STATUS=$(curl --output /dev/null --silent --write-out "%{http_code}" "$URL") || true
|
||||
echo "STATUS: ${HTTP_STATUS}"
|
||||
|
||||
# Check if we got the correct status code
|
||||
if [ "$HTTP_STATUS" -eq "$EXPECTED_STATUS" ]; then
|
||||
echo "✅ Server is up! Received status $HTTP_STATUS after $ELAPSED_TIME seconds."
|
||||
break;
|
||||
fi
|
||||
|
||||
# Wait before retrying
|
||||
echo "⏳ Server not ready (status: $HTTP_STATUS). Retrying in $RETRY_INTERVAL seconds..."
|
||||
sleep "$RETRY_INTERVAL"
|
||||
done
|
||||
|
||||
- name: Run TCK (mandatory)
|
||||
id: run-tck-mandatory
|
||||
timeout-minutes: 5
|
||||
run: |
|
||||
./run_tck.py --sut-url ${{ env.SUT_JSONRPC_URL }} --category mandatory --transports jsonrpc,rest,grpc
|
||||
working-directory: tck/a2a-tck
|
||||
- name: Run TCK (capabilities)
|
||||
id: run-tck-capabilities
|
||||
timeout-minutes: 5
|
||||
run: |
|
||||
./run_tck.py --sut-url ${{ env.SUT_JSONRPC_URL }} --category capabilities --transports jsonrpc,rest,grpc
|
||||
working-directory: tck/a2a-tck
|
||||
- name: Stop SUT
|
||||
if: always()
|
||||
run: |
|
||||
# Find and kill the SUT process
|
||||
pkill -f "npm run tck:sut-agent" || true
|
||||
sleep 2
|
||||
112
aitimemachine/a2a/.github/workflows/unit-tests.yml
vendored
Normal file
112
aitimemachine/a2a/.github/workflows/unit-tests.yml
vendored
Normal file
@ -0,0 +1,112 @@
|
||||
# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
|
||||
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
|
||||
|
||||
name: Run Unit Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main", "epic/**" ]
|
||||
pull_request:
|
||||
branches: [ "main", "epic/**" ]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
- '.github/CODEOWNERS'
|
||||
- 'src/samples/**'
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20, 22, 24]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
|
||||
# Edge runtime tests use @edge-runtime/vm to emulate Cloudflare Workers,
|
||||
# Vercel Edge Functions, and similar environments. This ensures the SDK
|
||||
# works correctly in non-Node.js server environments.
|
||||
test-edge:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm run test:edge
|
||||
|
||||
# The vitest 4.0.x test coverage integration doesn't support Node 18,
|
||||
# Node 18 has reached EOL already, however for compatibility we're still going to run tests
|
||||
# for Node 18 until the next major release (see https://github.com/a2aproject/a2a-js/pull/256).
|
||||
# Run coverage only once on a modern node to generate a report to avoid downgrading vitest.
|
||||
coverage:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Base Branch
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.base.ref || 'main' }}
|
||||
clean: true
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install & Test (Base Branch)
|
||||
timeout-minutes: 10
|
||||
run: |
|
||||
npm ci
|
||||
npm run coverage
|
||||
mv coverage/coverage-summary.json ${{ runner.temp }}/coverage-base-summary.json
|
||||
|
||||
- name: Upload Artifact (base)
|
||||
uses: actions/upload-artifact@v4
|
||||
if: github.event_name != 'pull_request'
|
||||
with:
|
||||
name: coverage-report
|
||||
path: coverage
|
||||
retention-days: 14
|
||||
|
||||
- name: Checkout PR Branch
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
clean: true
|
||||
|
||||
- name: Install & Test (PR)
|
||||
if: github.event_name == 'pull_request'
|
||||
timeout-minutes: 10
|
||||
run: |
|
||||
npm ci
|
||||
npm run coverage
|
||||
mv coverage/coverage-summary.json coverage-pr-summary.json
|
||||
mv ${{ runner.temp }}/coverage-base-summary.json coverage-base-summary.json
|
||||
|
||||
- name: Save PR number
|
||||
run: |
|
||||
echo ${{ github.event.number }} > ./PR_NUMBER
|
||||
|
||||
- name: Upload Coverage Artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
if: github.event_name == 'pull_request'
|
||||
with:
|
||||
name: coverage-data
|
||||
path: |
|
||||
coverage-base-summary.json
|
||||
coverage-pr-summary.json
|
||||
coverage/
|
||||
PR_NUMBER
|
||||
retention-days: 1
|
||||
182
aitimemachine/a2a/.gitignore
vendored
Normal file
182
aitimemachine/a2a/.gitignore
vendored
Normal file
@ -0,0 +1,182 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.pyc
|
||||
*$py.class
|
||||
**/dist
|
||||
/tmp
|
||||
/out-tsc
|
||||
/bazel-out
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
pip-wheel-metadata/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
Pipfile.lock
|
||||
Pipfile
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
.venv*
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
|
||||
# PyCharm
|
||||
.idea
|
||||
|
||||
# User-specific files
|
||||
language/examples/prompt-design/train.csv
|
||||
README-TOC*.md
|
||||
|
||||
# Terraform
|
||||
terraform.tfstate**
|
||||
.terraform*
|
||||
.Terraform*
|
||||
|
||||
tmp*
|
||||
|
||||
# Node
|
||||
**/node_modules
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
|
||||
# IDEs and editors
|
||||
.idea/
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# Miscellaneous
|
||||
**/.angular/*
|
||||
/.angular/cache
|
||||
.sass-cache/
|
||||
/connect.lock
|
||||
/coverage
|
||||
/libpeerconnection.log
|
||||
testem.log
|
||||
/typings
|
||||
|
||||
# System files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.nyc_output/
|
||||
7
aitimemachine/a2a/.prettierrc.json
Normal file
7
aitimemachine/a2a/.prettierrc.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"trailingComma": "es5",
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2
|
||||
}
|
||||
74
aitimemachine/a2a/AGENTS.md
Normal file
74
aitimemachine/a2a/AGENTS.md
Normal file
@ -0,0 +1,74 @@
|
||||
# @a2a-js/sdk
|
||||
|
||||
## Project Overview
|
||||
|
||||
`@a2a-js/sdk` is the official TypeScript/JavaScript SDK for the **Agent2Agent (A2A) Protocol**. It enables developers to build both:
|
||||
|
||||
1. **A2A Clients**: Applications that can discover, connect to, and interact with A2A agents.
|
||||
2. **A2A Servers**: Agents that expose their capabilities via the A2A protocol (JSON-RPC or HTTP+JSON/REST).
|
||||
|
||||
The SDK implements the **A2A Protocol Specification v0.3.0**.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
* **Language**: TypeScript (Node.js >= 18)
|
||||
* **Build System**: `tsup` (Outputs ESM and CJS)
|
||||
* **Testing Framework**: `vitest`
|
||||
* **Linting/Formatting**: `eslint`, `prettier`
|
||||
* **Peer Dependencies**: `express` (for server-side Express integration)
|
||||
|
||||
## Architecture & Key Components
|
||||
|
||||
The project is structured into modular entry points to allow tree-shaking and separation of concerns.
|
||||
|
||||
### 1. Common (`src/index.ts`)
|
||||
* **Types**: Core protocol types (`Message`, `Task`, `AgentCard`).
|
||||
* **Constants**: Protocol constants like `AGENT_CARD_PATH`.
|
||||
* **Errors**: Common error classes (`A2AError`).
|
||||
|
||||
### 2. Client (`src/client/index.ts`)
|
||||
* **`ClientFactory`**: The main entry point for creating clients. Can create clients from a base URL or an `AgentCard`.
|
||||
* **`A2AClient`**: The interface for sending messages and streams.
|
||||
* **Transports**:
|
||||
* `JsonRpcTransport`: Uses JSON-RPC over HTTP.
|
||||
* `RestTransport`: Uses standard HTTP+JSON REST patterns.
|
||||
* **Interceptors**: `CallInterceptor` for modifying requests/responses (e.g., adding auth headers).
|
||||
* **Auth**: `AuthenticationHandler` and `createAuthenticatingFetchWithRetry` for handling token refresh logic.
|
||||
|
||||
### 3. Server (`src/server/index.ts`)
|
||||
* **`AgentExecutor`**: The core interface you implement to define your agent's logic (`execute`, `cancelTask`).
|
||||
* **`DefaultRequestHandler`**: Orchestrates request processing, task management, and event dispatching.
|
||||
* **`ExecutionEventBus`**: Used within `AgentExecutor` to publish `Message`, `Task`, and `Artifact` updates.
|
||||
* **`InMemoryTaskStore`**: Default in-memory storage for task state.
|
||||
* **Push Notifications**: `PushNotificationSender` and `InMemoryPushNotificationStore` for async updates.
|
||||
|
||||
### 4. Server Express Integration (`src/server/express/index.ts`)
|
||||
* **Handlers**: `agentCardHandler`, `jsonRpcHandler`, `restHandler` to easily mount A2A endpoints in an Express app.
|
||||
* **`UserBuilder`**: Middleware for extracting user identity from requests.
|
||||
|
||||
## Building and Running
|
||||
|
||||
### Key Commands
|
||||
| Command | Description |
|
||||
| :--- | :--- |
|
||||
| `npm run build` | Builds the SDK using `tsup` into `dist/`. |
|
||||
| `npm test` | Runs unit tests using `vitest`. |
|
||||
| `npm run lint` | Runs all linting checks and applies automatic fixes (ESLint + Prettier + betterer). |
|
||||
| `npm run lint:ci` | Runs all linting checks without applying fixes. Fails if any issues are found. |
|
||||
| `npm run format:readme` | Formats the README file. |
|
||||
|
||||
## Samples
|
||||
|
||||
The `src/samples` directory contains practical examples:
|
||||
|
||||
* **`agents/`**:
|
||||
* `movie-agent/`: A sample agent that queries movie data from TMDB.
|
||||
* `sample-agent/`: A basic reference agent implementation.
|
||||
* **`authentication/`**: Examples of how to implement authentication middleware and user building.
|
||||
* **`extensions/`**: Examples of using protocol extensions.
|
||||
* **`cli.ts`**: A CLI tool example for interacting with agents.
|
||||
|
||||
## Development Conventions
|
||||
|
||||
* **Testing**: All new features should have accompanying unit tests in `test/` or alongside source files.
|
||||
* **Exports**: The project uses specific export paths in `package.json` (`.`, `./client`, `./server`, `./server/express`). Ensure new components are exported from the correct entry point.
|
||||
248
aitimemachine/a2a/CHANGELOG.md
Normal file
248
aitimemachine/a2a/CHANGELOG.md
Normal file
@ -0,0 +1,248 @@
|
||||
# Changelog
|
||||
|
||||
## [0.3.13](https://github.com/a2aproject/a2a-js/compare/v0.3.12...v0.3.13) (2026-03-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* properly parse ProtoJSON body for POST pushNotificationConfigs ([#352](https://github.com/a2aproject/a2a-js/issues/352)) ([57696a8](https://github.com/a2aproject/a2a-js/commit/57696a8001416ae2c5c592406c1f46b3e9209eca)), closes [#336](https://github.com/a2aproject/a2a-js/issues/336)
|
||||
|
||||
## [0.3.12](https://github.com/a2aproject/a2a-js/compare/v0.3.11...v0.3.12) (2026-03-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Fixing missing push configuration after normalization for rest transport ([#346](https://github.com/a2aproject/a2a-js/issues/346)) ([54ac8c4](https://github.com/a2aproject/a2a-js/commit/54ac8c41cacc54fb0d80526b79c87ba3aede14af))
|
||||
|
||||
## [0.3.11](https://github.com/a2aproject/a2a-js/compare/v0.3.10...v0.3.11) (2026-03-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* support proto-based AgentCard in AgentCardResolver ([#344](https://github.com/a2aproject/a2a-js/issues/344)) ([e71221c](https://github.com/a2aproject/a2a-js/commit/e71221cbc87b54acd96fbb4e7a46439a33ccbed6))
|
||||
* throw on JSON-RPC response id mismatch ([#318](https://github.com/a2aproject/a2a-js/issues/318)) ([5ea1c94](https://github.com/a2aproject/a2a-js/commit/5ea1c94acaf2cae5aa1bc10ea5816f5400a62423))
|
||||
|
||||
## [0.3.10](https://github.com/a2aproject/a2a-js/compare/v0.3.9...v0.3.10) (2026-01-27)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* do not use ReadableStream async iterator in SSE stream parsing ([#311](https://github.com/a2aproject/a2a-js/issues/311)) ([5359fa8](https://github.com/a2aproject/a2a-js/commit/5359fa802fc3a3dcf35438f3cee18f7ab9bc3ca3))
|
||||
* preserve typed error as cause in SSE errors ([#315](https://github.com/a2aproject/a2a-js/issues/315)) ([d39544e](https://github.com/a2aproject/a2a-js/commit/d39544ea4ba0db004fcca15b9fac870a97725e5c))
|
||||
|
||||
## [0.3.9](https://github.com/a2aproject/a2a-js/compare/v0.3.8...v0.3.9) (2026-01-21)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* implement gRPC client ([#299](https://github.com/a2aproject/a2a-js/issues/299)) ([dbdb96e](https://github.com/a2aproject/a2a-js/commit/dbdb96eeb14a710ad612f36f371d848fc7cce186))
|
||||
* implement gRPC server ([#279](https://github.com/a2aproject/a2a-js/issues/279)) ([bd4caa2](https://github.com/a2aproject/a2a-js/commit/bd4caa22a09480ba8cebec755528b67b80a95323))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* use proto default values in generated a2a_types.ts ([#303](https://github.com/a2aproject/a2a-js/issues/303)) ([0215d42](https://github.com/a2aproject/a2a-js/commit/0215d4232654c356c5d48e93cb94da46093576dd))
|
||||
|
||||
## [0.3.8](https://github.com/a2aproject/a2a-js/compare/v0.3.7...v0.3.8) (2026-01-15)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* use ProtoJSON for REST transport ([#292](https://github.com/a2aproject/a2a-js/issues/292))
|
||||
|
||||
### Features
|
||||
|
||||
* use case-insensitive transport protocol name comparison in ClientFactory ([5246067](https://github.com/a2aproject/a2a-js/commit/5246067f5fc1ca3aa7b1aef7176aab5b0f164acb))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add typesVersions to support legacy module resolution ([#288](https://github.com/a2aproject/a2a-js/issues/288)) ([6499e29](https://github.com/a2aproject/a2a-js/commit/6499e290f6e5a932eb7a6946c3b708cdea367165))
|
||||
* use ProtoJSON for REST transport ([#292](https://github.com/a2aproject/a2a-js/issues/292)) ([d2efc4c](https://github.com/a2aproject/a2a-js/commit/d2efc4cf343860d25b05f064f507ef4da7bba06b))
|
||||
|
||||
## [0.3.7](https://github.com/a2aproject/a2a-js/compare/v0.3.6...v0.3.7) (2025-12-17)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add rest client ([#258](https://github.com/a2aproject/a2a-js/issues/258)) ([96be3a1](https://github.com/a2aproject/a2a-js/commit/96be3a1d6caa3f55673e0c0e77859fe064beab2d))
|
||||
* remove EventEmitter dependency to support Edge Runtime ([#219](https://github.com/a2aproject/a2a-js/issues/219)) ([6c76fef](https://github.com/a2aproject/a2a-js/commit/6c76fef26473d8b15d729040b6c474de2794c7fe)), closes [#218](https://github.com/a2aproject/a2a-js/issues/218)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* export transport agnostic errors from client ([#272](https://github.com/a2aproject/a2a-js/issues/272)) ([23cd42e](https://github.com/a2aproject/a2a-js/commit/23cd42e83d6510b54b013df2efd762017f47d2a1))
|
||||
* pass ServerCallContext to getAuthenticatedExtendedAgentCard for REST ([#274](https://github.com/a2aproject/a2a-js/issues/274)) ([89b141b](https://github.com/a2aproject/a2a-js/commit/89b141b5ba915c53c04b2ffb1632e673b3adaace)), closes [#137](https://github.com/a2aproject/a2a-js/issues/137)
|
||||
|
||||
## [0.3.6](https://github.com/a2aproject/a2a-js/compare/v0.3.5...v0.3.6) (2025-12-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add support for extendedAgentCard on client side ([#234](https://github.com/a2aproject/a2a-js/issues/234)) ([3073376](https://github.com/a2aproject/a2a-js/commit/3073376f7c311f0c13c51c129d7065249735517a))
|
||||
* Add support for extension headers on client side ([#227](https://github.com/a2aproject/a2a-js/issues/227)) ([8c57002](https://github.com/a2aproject/a2a-js/commit/8c57002add3b25387da899df7a610098b0f4e01b))
|
||||
* implement client interceptors ([#223](https://github.com/a2aproject/a2a-js/issues/223)) ([5694c22](https://github.com/a2aproject/a2a-js/commit/5694c22e3bccba87137c5b4ad1b3011f9e30dcd0))
|
||||
* Implement extended card support on server side ([#197](https://github.com/a2aproject/a2a-js/issues/197)) ([45014ac](https://github.com/a2aproject/a2a-js/commit/45014ac4a192ad3c6120849577530d1d63eb27b8))
|
||||
* implement server http+json ([#142](https://github.com/a2aproject/a2a-js/issues/142)) ([f20e662](https://github.com/a2aproject/a2a-js/commit/f20e66247d3c962144d77e98e7720d6041537533))
|
||||
* introduce AgentCardResolver ([#225](https://github.com/a2aproject/a2a-js/issues/225)) ([ddaf7de](https://github.com/a2aproject/a2a-js/commit/ddaf7ded169ccc285051eeb63088dc697e6ae93e))
|
||||
* introduce transport agnostic client ([#198](https://github.com/a2aproject/a2a-js/issues/198)) ([94a9848](https://github.com/a2aproject/a2a-js/commit/94a98483998a62669140de9bfbdde483787fa065))
|
||||
* server side support for extensions ([5ef7396](https://github.com/a2aproject/a2a-js/commit/5ef73960758b78ed2a52356a10cb35cadeb440bd))
|
||||
* support authentication on server side ([#195](https://github.com/a2aproject/a2a-js/issues/195)) ([9872d93](https://github.com/a2aproject/a2a-js/commit/9872d93622e12efb7369d7e658cec7ab4fd8590c))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* handle errors occurred in non-blocking sendMessage ([#187](https://github.com/a2aproject/a2a-js/issues/187)) ([e55c0f4](https://github.com/a2aproject/a2a-js/commit/e55c0f4791b556cc42e256073cf9018d1ec18cca))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* set version to 0.3.6 ([#191](https://github.com/a2aproject/a2a-js/issues/191)) ([3f8cea0](https://github.com/a2aproject/a2a-js/commit/3f8cea066efa59ae38ac405801884b9b5037841b))
|
||||
|
||||
## [0.3.5](https://github.com/a2aproject/a2a-js/compare/v0.3.4...v0.3.5) (2025-11-05)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* cancel/task now returns the expected 'cancelled' task status ([#158](https://github.com/a2aproject/a2a-js/issues/158)) ([3eec0bd](https://github.com/a2aproject/a2a-js/commit/3eec0bd98ab02f8d76c4b01dc8ea8351bc8f1a07))
|
||||
* correct the default value in the agentCardPath comment ([#130](https://github.com/a2aproject/a2a-js/issues/130)) ([3279c7b](https://github.com/a2aproject/a2a-js/commit/3279c7bf4de088950c81aaeccb1cfaca5ee26284))
|
||||
* enable follow up task issue on non blocking request ([#160](https://github.com/a2aproject/a2a-js/issues/160)) ([352dc05](https://github.com/a2aproject/a2a-js/commit/352dc0585122db341da93b5fbd2f8cf7acf7fcca))
|
||||
* ensure push notifications order ([#141](https://github.com/a2aproject/a2a-js/issues/141)) ([22360e6](https://github.com/a2aproject/a2a-js/commit/22360e6ba735b10c611b5881ea8f98c898622117))
|
||||
* ensure user messages are added to existing tasks ([#138](https://github.com/a2aproject/a2a-js/issues/138)) ([00fb916](https://github.com/a2aproject/a2a-js/commit/00fb916ca4b877b11b3153d67593027e508c3d64))
|
||||
* validate JSON-RPC params ([#155](https://github.com/a2aproject/a2a-js/issues/155)) ([5b39f4d](https://github.com/a2aproject/a2a-js/commit/5b39f4dd96b619e1683c0f2226279d20572f2a27))
|
||||
* validate JSON-RPC request id according to the spec ([#152](https://github.com/a2aproject/a2a-js/issues/152)) ([9558c36](https://github.com/a2aproject/a2a-js/commit/9558c3613a0e5c8c48743412b0c47f9480345666))
|
||||
|
||||
## [0.3.4](https://github.com/a2aproject/a2a-js/compare/v0.3.3...v0.3.4) (2025-09-04)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add list and delete task push notification config rpc method and custom rpc methods for extensions ([#119](https://github.com/a2aproject/a2a-js/issues/119)) ([26c4e7d](https://github.com/a2aproject/a2a-js/commit/26c4e7df48e0cd1088a9340ddc34bfbed320664c))
|
||||
* Added push notifications support ([#108](https://github.com/a2aproject/a2a-js/issues/108)) ([45a211a](https://github.com/a2aproject/a2a-js/commit/45a211a738ea7770ec5ee8b10a1238060ba7a471))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* release 0.3.4 ([#128](https://github.com/a2aproject/a2a-js/issues/128)) ([41791d9](https://github.com/a2aproject/a2a-js/commit/41791d99a4c7776ac3ee183d3e834df31a2020ac))
|
||||
|
||||
## [0.3.3](https://github.com/a2aproject/a2a-js/compare/v0.3.2...v0.3.3) (2025-08-27)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* Update A2AClient constructor to initialize with full agentCardUrl ([#121](https://github.com/a2aproject/a2a-js/issues/121))
|
||||
|
||||
### Features
|
||||
|
||||
* Update A2AClient constructor to initialize with full agentCardUrl ([#121](https://github.com/a2aproject/a2a-js/issues/121)) ([755044c](https://github.com/a2aproject/a2a-js/commit/755044c6c610991b5c86747da72b24e1fff9ade3))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Improve fetch implementation handling ([#117](https://github.com/a2aproject/a2a-js/issues/117)) ([09adbd3](https://github.com/a2aproject/a2a-js/commit/09adbd31d1ef7a73e4c8c87045af84bb1280226f))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* release 0.3.3 ([#124](https://github.com/a2aproject/a2a-js/issues/124)) ([ea59193](https://github.com/a2aproject/a2a-js/commit/ea591932901742af76afb5aeee4cf8d27cc9a6c2))
|
||||
|
||||
## [0.3.2](https://github.com/a2aproject/a2a-js/compare/v0.3.1...v0.3.2) (2025-08-17)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Added generic client hooks for HTTP based authentication, and improved agent.json resolution ([#33](https://github.com/a2aproject/a2a-js/issues/33)) ([a9826ac](https://github.com/a2aproject/a2a-js/commit/a9826acde3bb1f741153407e6179fd21f2e7a4bb))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* fix Incorrect Well-Known Path for Agent Card ([#102](https://github.com/a2aproject/a2a-js/issues/102)) ([3a0f1d0](https://github.com/a2aproject/a2a-js/commit/3a0f1d07843b725c9beaf1078bc43418ff2871ed))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* release 0.3.2 ([#111](https://github.com/a2aproject/a2a-js/issues/111)) ([03f35e0](https://github.com/a2aproject/a2a-js/commit/03f35e0ed29d2b24df7eddb2a7fe21d0690f503e))
|
||||
|
||||
## [0.3.1](https://github.com/a2aproject/a2a-js/compare/v0.3.0...v0.3.1) (2025-08-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add missing express entrypoint to tsup config ([#96](https://github.com/a2aproject/a2a-js/issues/96)) ([8e990e4](https://github.com/a2aproject/a2a-js/commit/8e990e497927e3554699f8ebb005829b170d9bc3))
|
||||
|
||||
## [0.3.0](https://github.com/a2aproject/a2a-js/compare/v0.2.5...v0.3.0) (2025-08-05)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* upgrade to a2a 0.3.0 spec version ([#87](https://github.com/a2aproject/a2a-js/issues/87))
|
||||
* make Express dependency optional
|
||||
|
||||
### Features
|
||||
|
||||
* make Express dependency optional ([60899c5](https://github.com/a2aproject/a2a-js/commit/60899c51e2910570402d1207f6b50952bed8862f))
|
||||
* upgrade to a2a 0.3.0 spec version ([#87](https://github.com/a2aproject/a2a-js/issues/87)) ([ae53da1](https://github.com/a2aproject/a2a-js/commit/ae53da1e36ff58912e01fefa854c5b3174edf7d8))
|
||||
|
||||
## [0.2.5](https://github.com/a2aproject/a2a-js/compare/v0.2.4...v0.2.5) (2025-07-30)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add support for custom agent card url. resolves [#68](https://github.com/a2aproject/a2a-js/issues/68) ([#79](https://github.com/a2aproject/a2a-js/issues/79)) ([dc92d32](https://github.com/a2aproject/a2a-js/commit/dc92d321ac7c142ff5232cdca0db8a24b4d76da0))
|
||||
* Export ExecutionEventQueue in server ([#61](https://github.com/a2aproject/a2a-js/issues/61)) ([530c0b9](https://github.com/a2aproject/a2a-js/commit/530c0b9f1fd50fafd991f640c119837860ae8c3f))
|
||||
* Export type AgentExecutionEvent ([#66](https://github.com/a2aproject/a2a-js/issues/66)) ([f4c81f4](https://github.com/a2aproject/a2a-js/commit/f4c81f41866c24d83823b5db7d24b5fdb56b37b4))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* correct the example code ([#64](https://github.com/a2aproject/a2a-js/issues/64)) ([126eee4](https://github.com/a2aproject/a2a-js/commit/126eee4e3b79e9475a5af5cbebb0e98b68f286fa))
|
||||
* setting context id in _createRequestContext ([#49](https://github.com/a2aproject/a2a-js/issues/49)) ([1abc8a1](https://github.com/a2aproject/a2a-js/commit/1abc8a1f3590f78647d94c5a1e31444203e1131f))
|
||||
|
||||
## [0.2.4](https://github.com/a2aproject/a2a-js/compare/v0.2.3...v0.2.4) (2025-07-14)
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* fix empty npm publish by version-bump ([#56](https://github.com/a2aproject/a2a-js/issues/56)) ([b12e033](https://github.com/a2aproject/a2a-js/commit/b12e033ed8ffc823672d68d749344247ee0914ee))
|
||||
|
||||
## [0.2.3](https://github.com/a2aproject/a2a-js/compare/v0.2.2...v0.2.3) (2025-07-14)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* separate entrypoints for client, server & common
|
||||
|
||||
### Features
|
||||
|
||||
* add CommonJS support alongside ESM ([#27](https://github.com/a2aproject/a2a-js/issues/27)) ([1b3e516](https://github.com/a2aproject/a2a-js/commit/1b3e516e2ba6058eddd84943b07616cf5b74f5b0))
|
||||
* Allow adding middlewares in server ([#51](https://github.com/a2aproject/a2a-js/issues/51)) ([b4fc323](https://github.com/a2aproject/a2a-js/commit/b4fc323c1f607622ee7841c95c1e401cf79df186))
|
||||
* separate entrypoints for client, server & common ([e8dd025](https://github.com/a2aproject/a2a-js/commit/e8dd0250847c1e628a1c932f1ba4cc5c57064714))
|
||||
|
||||
## [0.2.2](https://github.com/google-a2a/a2a-js/compare/v0.2.1...v0.2.2) (2025-06-20)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add action to publish to npm ([e4ab96e](https://github.com/google-a2a/a2a-js/commit/e4ab96ed4f875cc3079534637fbf88f9adad7f74))
|
||||
* add sample agent ([#19](https://github.com/google-a2a/a2a-js/issues/19)) ([1f21a0a](https://github.com/google-a2a/a2a-js/commit/1f21a0a8662550547c1703d33e71f5cf7bd28d6b))
|
||||
* add test coverage ([#20](https://github.com/google-a2a/a2a-js/issues/20)) ([7bde9cd](https://github.com/google-a2a/a2a-js/commit/7bde9cd839c015e270719d312df18ddc0c6f34b0))
|
||||
* generate types from spec & use unknown in types ([#17](https://github.com/google-a2a/a2a-js/issues/17)) ([748f928](https://github.com/google-a2a/a2a-js/commit/748f9283a8e93d6104e29309f27d83fb2f9193e0))
|
||||
* reject sendMessage for tasks in terminal states ([#29](https://github.com/google-a2a/a2a-js/issues/29)) ([9f86195](https://github.com/google-a2a/a2a-js/commit/9f86195d01fada7f041df0199cf93bcff2da8b80))
|
||||
* Supply taskId & contextId in requestContext ([#22](https://github.com/google-a2a/a2a-js/issues/22)) ([79db7f4](https://github.com/google-a2a/a2a-js/commit/79db7f48cac482b176f2297ca374e1e937eda1d0))
|
||||
* support non-blocking message send ([#28](https://github.com/google-a2a/a2a-js/issues/28)) ([6984dbb](https://github.com/google-a2a/a2a-js/commit/6984dbb3655a71bb540e6c14cb2f4792a4556fad))
|
||||
* use string union instead of enums ([#24](https://github.com/google-a2a/a2a-js/issues/24)) ([bcc1f7e](https://github.com/google-a2a/a2a-js/commit/bcc1f7e0e14065163dacf3f60e74c7bb501f243e))
|
||||
|
||||
## 0.2.1 (2025-06-06)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Add cancelTask to executor & finished to eventBus ([831c393](https://github.com/google-a2a/a2a-js/commit/831c3937ba59e0b4c2fdfd9577f506921929034a))
|
||||
* Add sdk files for client & server ([00fe8cd](https://github.com/google-a2a/a2a-js/commit/00fe8cd33db4d5464a320dc2d16fd483b5a2fbbf))
|
||||
* add sdk/tests for client & server ([a921c98](https://github.com/google-a2a/a2a-js/commit/a921c98946ba4e0636d9d6d320918e1fcb3ba5aa))
|
||||
* add tests for all APIs ([e6281ca](https://github.com/google-a2a/a2a-js/commit/e6281caa131ebcc247cf750f597ead2ea28f2c3d))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* library should released as 0.2.1 ([#8](https://github.com/google-a2a/a2a-js/issues/8)) ([0335732](https://github.com/google-a2a/a2a-js/commit/033573295e0ab8115d2fcd0c64a0bd5df1537b67))
|
||||
96
aitimemachine/a2a/CODE_OF_CONDUCT.md
Normal file
96
aitimemachine/a2a/CODE_OF_CONDUCT.md
Normal file
@ -0,0 +1,96 @@
|
||||
# Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, gender identity and expression, level of
|
||||
experience, education, socio-economic status, nationality, personal appearance,
|
||||
race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, or to ban temporarily or permanently any
|
||||
contributor for other behaviors that they deem inappropriate, threatening,
|
||||
offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
This Code of Conduct also applies outside the project spaces when the Project
|
||||
Steward has a reasonable belief that an individual's behavior may have a
|
||||
negative impact on the project or its community.
|
||||
|
||||
## Conflict Resolution
|
||||
|
||||
We do not believe that all conflict is bad; healthy debate and disagreement
|
||||
often yield positive results. However, it is never okay to be disrespectful or
|
||||
to engage in behavior that violates the project’s code of conduct.
|
||||
|
||||
If you see someone violating the code of conduct, you are encouraged to address
|
||||
the behavior directly with those involved. Many issues can be resolved quickly
|
||||
and easily, and this gives people more control over the outcome of their
|
||||
dispute. If you are unable to resolve the matter for any reason, or if the
|
||||
behavior is threatening or harassing, report it. We are dedicated to providing
|
||||
an environment where participants feel welcome and safe.
|
||||
|
||||
Reports should be directed to *[PROJECT STEWARD NAME(s) AND EMAIL(s)]*, the
|
||||
Project Steward(s) for *[PROJECT NAME]*. It is the Project Steward’s duty to
|
||||
receive and address reported violations of the code of conduct. They will then
|
||||
work with a committee consisting of representatives from the Open Source
|
||||
Programs Office and the Google Open Source Strategy team. If for any reason you
|
||||
are uncomfortable reaching out to the Project Steward, please email
|
||||
opensource@google.com.
|
||||
|
||||
We will investigate every complaint, but you may not receive a direct response.
|
||||
We will use our discretion in determining when and how to follow up on reported
|
||||
incidents, which may range from not taking action to permanent expulsion from
|
||||
the project and project-sponsored spaces. We will notify the accused of the
|
||||
report and provide them an opportunity to discuss it before any action is taken.
|
||||
The identity of the reporter will be omitted from the details of the report
|
||||
supplied to the accused. In potentially harmful situations, such as ongoing
|
||||
harassment or threats to anyone's safety, we may take action without notice.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the Contributor Covenant, version 1.4,
|
||||
available at
|
||||
https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
Note: A version of this file is also available in the
|
||||
[New Project repo](https://github.com/google/new-project/blob/master/docs/code-of-conduct.md).
|
||||
28
aitimemachine/a2a/CONTRIBUTING.md
Normal file
28
aitimemachine/a2a/CONTRIBUTING.md
Normal file
@ -0,0 +1,28 @@
|
||||
# How to contribute
|
||||
|
||||
We'd love to accept your patches and contributions to this project.
|
||||
|
||||
## Contribution process
|
||||
|
||||
### Code reviews
|
||||
|
||||
All submissions, including submissions by project members, require review. We
|
||||
use GitHub pull requests for this purpose. Consult
|
||||
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
|
||||
information on using pull requests.
|
||||
|
||||
### Contributor Guide
|
||||
|
||||
You may follow these steps to contribute:
|
||||
|
||||
1. **Fork the official repository.** This will create a copy of the official repository in your own account.
|
||||
2. **Sync the branches.** This will ensure that your copy of the repository is up-to-date with the latest changes from the official repository.
|
||||
3. **Work on your forked repository's feature branch.** This is where you will make your changes to the code.
|
||||
4. **Commit your updates on your forked repository's feature branch.** This will save your changes to your copy of the repository.
|
||||
5. **Submit a pull request to the official repository's main branch.** This will request that your changes be merged into the official repository.
|
||||
6. **Resolve any linting errors.** This will ensure that your changes are formatted correctly.
|
||||
|
||||
Here are some additional things to keep in mind during the process:
|
||||
|
||||
- **Test your changes.** Before you submit a pull request, make sure that your changes work as expected.
|
||||
- **Be patient.** It may take some time for your pull request to be reviewed and merged.
|
||||
202
aitimemachine/a2a/LICENSE
Normal file
202
aitimemachine/a2a/LICENSE
Normal file
@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
792
aitimemachine/a2a/README.md
Normal file
792
aitimemachine/a2a/README.md
Normal file
@ -0,0 +1,792 @@
|
||||
# A2A JavaScript SDK
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
<!-- markdownlint-disable no-inline-html -->
|
||||
|
||||
<html>
|
||||
<h2 align="center">
|
||||
<img src="https://raw.githubusercontent.com/google-a2a/A2A/refs/heads/main/docs/assets/a2a-logo-black.svg" width="256" alt="A2A Logo"/>
|
||||
</h2>
|
||||
<h3 align="center">A JavaScript library that helps run agentic applications as A2AServers following the <a href="https://google-a2a.github.io/A2A">Agent2Agent (A2A) Protocol</a>.</h3>
|
||||
</html>
|
||||
|
||||
<!-- markdownlint-enable no-inline-html -->
|
||||
|
||||
## Installation
|
||||
|
||||
You can install the A2A SDK using `npm`.
|
||||
|
||||
```bash
|
||||
npm install @a2a-js/sdk
|
||||
```
|
||||
|
||||
### For Server Usage
|
||||
|
||||
If you plan to use the Express integration (imports from `@a2a-js/sdk/server/express`) for A2A server, you'll also need to install Express as it's a peer dependency:
|
||||
|
||||
```bash
|
||||
npm install express
|
||||
```
|
||||
|
||||
### For gRPC Usage
|
||||
|
||||
If you plan to use the GRPC transport (imports from `@a2a-js/sdk/server/grpc` or `@a2a-js/sdk/client/grpc`), you must install the required peer dependencies:
|
||||
|
||||
```bash
|
||||
npm install @grpc/grpc-js @bufbuild/protobuf
|
||||
```
|
||||
|
||||
You can also find some samples [here](https://github.com/a2aproject/a2a-js/tree/main/src/samples).
|
||||
|
||||
---
|
||||
|
||||
## Compatibility
|
||||
|
||||
This SDK implements the A2A Protocol Specification [`v0.3`](https://a2a-protocol.org/v0.3.0/specification).
|
||||
|
||||
> [!IMPORTANT]
|
||||
> There is an [**alpha version**](https://github.com/a2aproject/a2a-js/releases?q=%22v1.0.0-alpha%22&expanded=true) available with support for [`v1.0`](https://a2a-protocol.org/v1.0.0/specification/) version. Development for this version is taking place in the [`epic/1.0_breaking_changes`](https://github.com/a2aproject/a2a-js/tree/epic/1.0_breaking_changes) branch. The work to add backward compatibility with the [`v0.3`](https://a2a-protocol.org/v0.3.0/specification) version is tracked in [issue #452](https://github.com/a2aproject/a2a-js/issues/452).
|
||||
> You can install the latest alpha version using:
|
||||
> ```bash
|
||||
> npm install @a2a-js/sdk@next
|
||||
> ```
|
||||
|
||||
| Transport | Client | Server |
|
||||
| :--- | :---: | :---: |
|
||||
| **JSON-RPC** | ✅ | ✅ |
|
||||
| **HTTP+JSON/REST** | ✅ | ✅ |
|
||||
| **GRPC** (Node.js only) | ✅ | ✅ |
|
||||
|
||||
## Quickstart
|
||||
|
||||
This example shows how to create a simple "Hello World" agent server and a client to interact with it.
|
||||
|
||||
### Server: Hello World Agent
|
||||
|
||||
The core of an A2A server is the `AgentExecutor`, which contains your agent's logic.
|
||||
|
||||
```typescript
|
||||
// server.ts
|
||||
import express from 'express';
|
||||
import { Server, ServerCredentials } from '@grpc/grpc-js';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { AgentCard, Message, AGENT_CARD_PATH } from '@a2a-js/sdk';
|
||||
import {
|
||||
AgentExecutor,
|
||||
RequestContext,
|
||||
ExecutionEventBus,
|
||||
DefaultRequestHandler,
|
||||
InMemoryTaskStore,
|
||||
} from '@a2a-js/sdk/server';
|
||||
import { agentCardHandler, jsonRpcHandler, restHandler, UserBuilder } from '@a2a-js/sdk/server/express';
|
||||
import { grpcService, A2AService } from '@a2a-js/sdk/server/grpc';
|
||||
|
||||
// 1. Define your agent's identity card.
|
||||
const helloAgentCard: AgentCard = {
|
||||
name: 'Hello Agent',
|
||||
description: 'A simple agent that says hello.',
|
||||
protocolVersion: '0.3.0',
|
||||
version: '0.1.0',
|
||||
url: 'http://localhost:4000/a2a/jsonrpc', // The public URL of your agent server
|
||||
skills: [{ id: 'chat', name: 'Chat', description: 'Say hello', tags: ['chat'] }],
|
||||
capabilities: {
|
||||
pushNotifications: false,
|
||||
},
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text'],
|
||||
additionalInterfaces: [
|
||||
{ url: 'http://localhost:4000/a2a/jsonrpc', transport: 'JSONRPC' }, // Default JSON-RPC transport
|
||||
{ url: 'http://localhost:4000/a2a/rest', transport: 'HTTP+JSON' }, // HTTP+JSON/REST transport
|
||||
{ url: 'localhost:4001', transport: 'GRPC' }, // GRPC transport
|
||||
],
|
||||
};
|
||||
|
||||
// 2. Implement the agent's logic.
|
||||
class HelloExecutor implements AgentExecutor {
|
||||
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
// Create a direct message response.
|
||||
const responseMessage: Message = {
|
||||
kind: 'message',
|
||||
messageId: uuidv4(),
|
||||
role: 'agent',
|
||||
parts: [{ kind: 'text', text: 'Hello, world!' }],
|
||||
// Associate the response with the incoming request's context.
|
||||
contextId: requestContext.contextId,
|
||||
};
|
||||
|
||||
// Publish the message and signal that the interaction is finished.
|
||||
eventBus.publish(responseMessage);
|
||||
eventBus.finished();
|
||||
}
|
||||
|
||||
// cancelTask is not needed for this simple, non-stateful agent.
|
||||
cancelTask = async (): Promise<void> => {};
|
||||
}
|
||||
|
||||
// 3. Set up and run the server.
|
||||
const agentExecutor = new HelloExecutor();
|
||||
const requestHandler = new DefaultRequestHandler(
|
||||
helloAgentCard,
|
||||
new InMemoryTaskStore(),
|
||||
agentExecutor
|
||||
);
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
|
||||
app.use('/a2a/jsonrpc', jsonRpcHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
|
||||
app.use('/a2a/rest', restHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
|
||||
|
||||
app.listen(4000, () => {
|
||||
console.log(`🚀 Server started on http://localhost:4000`);
|
||||
});
|
||||
|
||||
const server = new Server();
|
||||
server.addService(A2AService, grpcService({
|
||||
requestHandler,
|
||||
userBuilder: UserBuilder.noAuthentication,
|
||||
}));
|
||||
server.bindAsync(`localhost:4001`, ServerCredentials.createInsecure(), () => {
|
||||
console.log(`🚀 Server started on localhost:4001`);
|
||||
});
|
||||
```
|
||||
|
||||
### Client: Sending a Message
|
||||
|
||||
The [`ClientFactory`](src/client/factory.ts) makes it easy to communicate with any A2A-compliant agent.
|
||||
|
||||
```typescript
|
||||
// client.ts
|
||||
import { ClientFactory } from '@a2a-js/sdk/client';
|
||||
import { Message, MessageSendParams, SendMessageSuccessResponse } from '@a2a-js/sdk';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
async function run() {
|
||||
const factory = new ClientFactory();
|
||||
|
||||
// createFromUrl accepts baseUrl and optional path,
|
||||
// (the default path is /.well-known/agent-card.json)
|
||||
const client = await factory.createFromUrl('http://localhost:4000');
|
||||
|
||||
const sendParams: MessageSendParams = {
|
||||
message: {
|
||||
messageId: uuidv4(),
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text: 'Hi there!' }],
|
||||
kind: 'message',
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await client.sendMessage(sendParams);
|
||||
const result = response as Message;
|
||||
console.log('Agent response:', result.parts[0].text); // "Hello, world!"
|
||||
} catch(e) {
|
||||
console.error('Error:', e);
|
||||
}
|
||||
}
|
||||
|
||||
await run();
|
||||
```
|
||||
|
||||
### gRPC Client: Sending a Message
|
||||
|
||||
The [`ClientFactory`](src/client/factory.ts) has to be created explicitly passing the [`GrpcTransportFactory`](src/client/transports/grpc/grpc_transport.ts).
|
||||
|
||||
```typescript
|
||||
// client.ts
|
||||
import { ClientFactory, ClientFactoryOptions } from '@a2a-js/sdk/client';
|
||||
import { GrpcTransportFactory } from '@a2a-js/sdk/client/grpc';
|
||||
import { Message, MessageSendParams, SendMessageSuccessResponse } from '@a2a-js/sdk';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
async function run() {
|
||||
const factory = new ClientFactory({
|
||||
transports: [new GrpcTransportFactory()]
|
||||
});
|
||||
|
||||
// createFromUrl accepts baseUrl and optional path,
|
||||
// (the default path is /.well-known/agent-card.json)
|
||||
const client = await factory.createFromUrl('http://localhost:4000');
|
||||
|
||||
const sendParams: MessageSendParams = {
|
||||
message: {
|
||||
messageId: uuidv4(),
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text: 'Hi there!' }],
|
||||
kind: 'message',
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await client.sendMessage(sendParams);
|
||||
const result = response as Message;
|
||||
console.log('Agent response:', result.parts[0].text); // "Hello, world!"
|
||||
} catch(e) {
|
||||
console.error('Error:', e);
|
||||
}
|
||||
}
|
||||
|
||||
await run();
|
||||
```
|
||||
---
|
||||
|
||||
## A2A `Task` Support
|
||||
|
||||
For operations that are stateful or long-running, agents create a `Task`. A task has a state (e.g., `working`, `completed`) and can produce `Artifacts` (e.g., files, data).
|
||||
|
||||
### Server: Creating a Task
|
||||
|
||||
This agent creates a task, attaches a file artifact to it, and marks it as complete.
|
||||
|
||||
```typescript
|
||||
// server.ts
|
||||
import { Task, TaskArtifactUpdateEvent, TaskStatusUpdateEvent } from '@a2a-js/sdk';
|
||||
// ... other imports from the quickstart server ...
|
||||
|
||||
class TaskExecutor implements AgentExecutor {
|
||||
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
const { taskId, contextId, userMessage, task } = requestContext;
|
||||
|
||||
// 1. Create and publish the initial task object if it doesn't exist.
|
||||
if (!task) {
|
||||
const initialTask: Task = {
|
||||
kind: 'task',
|
||||
id: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'submitted',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
history: [userMessage],
|
||||
};
|
||||
eventBus.publish(initialTask);
|
||||
}
|
||||
|
||||
// 2. Create and publish an artifact.
|
||||
const artifactUpdate: TaskArtifactUpdateEvent = {
|
||||
kind: 'artifact-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
artifact: {
|
||||
artifactId: 'report-1',
|
||||
name: 'analysis_report.txt',
|
||||
parts: [{ kind: 'text', text: `This is the analysis for task ${taskId}.` }],
|
||||
},
|
||||
};
|
||||
eventBus.publish(artifactUpdate);
|
||||
|
||||
// 3. Publish the final status and mark the event as 'final'.
|
||||
const finalUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: { state: 'completed', timestamp: new Date().toISOString() },
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(finalUpdate);
|
||||
eventBus.finished();
|
||||
}
|
||||
|
||||
cancelTask = async (): Promise<void> => {};
|
||||
}
|
||||
```
|
||||
|
||||
### Client: Receiving a Task
|
||||
|
||||
The client sends a message and receives a `Task` object as the result.
|
||||
|
||||
```typescript
|
||||
// client.ts
|
||||
import { ClientFactory } from '@a2a-js/sdk/client';
|
||||
import { Message, MessageSendParams, SendMessageSuccessResponse, Task } from '@a2a-js/sdk';
|
||||
// ... other imports ...
|
||||
|
||||
const factory = new ClientFactory();
|
||||
|
||||
// createFromUrl accepts baseUrl and optional path,
|
||||
// (the default path is /.well-known/agent-card.json)
|
||||
const client = await factory.createFromUrl('http://localhost:4000');
|
||||
|
||||
try {
|
||||
const result = await client.sendMessage({
|
||||
message: {
|
||||
messageId: uuidv4(),
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text: 'Do something.' }],
|
||||
kind: 'message',
|
||||
},
|
||||
});
|
||||
|
||||
// Check if the agent's response is a Task or a direct Message.
|
||||
if (result.kind === 'task') {
|
||||
const task = result as Task;
|
||||
console.log(`Task [${task.id}] completed with status: ${task.status.state}`);
|
||||
|
||||
if (task.artifacts && task.artifacts.length > 0) {
|
||||
console.log(`Artifact found: ${task.artifacts[0].name}`);
|
||||
console.log(`Content: ${task.artifacts[0].parts[0].text}`);
|
||||
}
|
||||
} else {
|
||||
const message = result as Message;
|
||||
console.log('Received direct message:', message.parts[0].text);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error:', e);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Client Customization
|
||||
|
||||
Client can be customized via [`CallInterceptor`'s](src/client/interceptors.ts) which is a recommended way as it's transport-agnostic.
|
||||
|
||||
Common use cases include:
|
||||
|
||||
- **Request Interception**: Log outgoing requests or collect metrics.
|
||||
- **Header Injection**: Add custom headers for authentication, tracing, or routing.
|
||||
- **A2A Extensions**: Modifying payloads to include protocol extension data.
|
||||
|
||||
### Example: Injecting a Custom Header
|
||||
|
||||
This example defines a `CallInterceptor` to update `serviceParameters` which are passed as HTTP headers.
|
||||
|
||||
```typescript
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { AfterArgs, BeforeArgs, CallInterceptor, ClientFactory, ClientFactoryOptions } from '@a2a-js/sdk/client';
|
||||
|
||||
// 1. Define an interceptor
|
||||
class RequestIdInterceptor implements CallInterceptor {
|
||||
before(args: BeforeArgs): Promise<void> {
|
||||
args.options = {
|
||||
...args.options,
|
||||
serviceParameters: {
|
||||
...args.options.serviceParameters,
|
||||
['X-Request-ID']: uuidv4(),
|
||||
},
|
||||
};
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
after(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Register the interceptor in the client factory
|
||||
const factory = new ClientFactory(ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
|
||||
clientConfig: {
|
||||
interceptors: [new RequestIdInterceptor()]
|
||||
}
|
||||
}))
|
||||
const client = await factory.createFromAgentCardUrl('http://localhost:4000');
|
||||
|
||||
// Now, all requests made by clients created by this factory will include the X-Request-ID header.
|
||||
await client.sendMessage({
|
||||
message: {
|
||||
messageId: uuidv4(),
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text: 'A message requiring custom headers.' }],
|
||||
kind: 'message',
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Example: Specifying a Timeout
|
||||
|
||||
Each client method can be configured with an optional `signal` field.
|
||||
|
||||
```typescript
|
||||
import { ClientFactory } from '@a2a-js/sdk/client';
|
||||
|
||||
const factory = new ClientFactory();
|
||||
|
||||
// createFromUrl accepts baseUrl and optional path,
|
||||
// (the default path is /.well-known/agent-card.json)
|
||||
const client = await factory.createFromUrl('http://localhost:4000');
|
||||
|
||||
await client.sendMessage(
|
||||
{
|
||||
message: {
|
||||
messageId: uuidv4(),
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text: 'A long-running message.' }],
|
||||
kind: 'message',
|
||||
},
|
||||
},
|
||||
{
|
||||
signal: AbortSignal.timeout(5000), // 5 seconds timeout
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### Customizing Transports: Using the Provided `AuthenticationHandler`
|
||||
|
||||
For advanced authentication scenarios, the SDK includes a higher-order function `createAuthenticatingFetchWithRetry` and an `AuthenticationHandler` interface. This utility automatically adds authorization headers and can retry requests that fail with authentication errors (e.g., 401 Unauthorized).
|
||||
|
||||
Here's how to use it to manage a Bearer token:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
ClientFactory,
|
||||
ClientFactoryOptions,
|
||||
JsonRpcTransportFactory,
|
||||
AuthenticationHandler,
|
||||
createAuthenticatingFetchWithRetry,
|
||||
} from '@a2a-js/sdk/client';
|
||||
|
||||
// A simple token provider that simulates fetching a new token.
|
||||
const tokenProvider = {
|
||||
token: 'initial-stale-token',
|
||||
getNewToken: async () => {
|
||||
console.log('Refreshing auth token...');
|
||||
tokenProvider.token = `new-token-${Date.now()}`;
|
||||
return tokenProvider.token;
|
||||
},
|
||||
};
|
||||
|
||||
// 1. Implement the AuthenticationHandler interface.
|
||||
const handler: AuthenticationHandler = {
|
||||
// headers() is called on every request to get the current auth headers.
|
||||
headers: async () => ({
|
||||
Authorization: `Bearer ${tokenProvider.token}`,
|
||||
}),
|
||||
|
||||
// shouldRetryWithHeaders() is called after a request fails.
|
||||
// It decides if a retry is needed and provides new headers.
|
||||
shouldRetryWithHeaders: async (req: RequestInit, res: Response) => {
|
||||
if (res.status === 401) {
|
||||
// Unauthorized
|
||||
const newToken = await tokenProvider.getNewToken();
|
||||
// Return new headers to trigger a single retry.
|
||||
return { Authorization: `Bearer ${newToken}` };
|
||||
}
|
||||
|
||||
// Return undefined to not retry for other errors.
|
||||
return undefined;
|
||||
},
|
||||
};
|
||||
|
||||
// 2. Create the authenticated fetch function.
|
||||
const authFetch = createAuthenticatingFetchWithRetry(fetch, handler);
|
||||
|
||||
// 3. Inject new fetch implementation into a client factory.
|
||||
const factory = new ClientFactory(ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
|
||||
transports: [
|
||||
new JsonRpcTransportFactory({ fetchImpl: authFetch })
|
||||
]
|
||||
}))
|
||||
|
||||
// 4. Clients created from the factory are going to have custom fetch attached.
|
||||
const client = await factory.createFromUrl('http://localhost:4000');
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Streaming
|
||||
|
||||
For real-time updates, A2A supports streaming responses over Server-Sent Events (SSE).
|
||||
|
||||
### Server: Streaming Task Updates
|
||||
|
||||
The agent publishes events as it works on the task. The client receives these events in real-time.
|
||||
|
||||
```typescript
|
||||
// server.ts
|
||||
// ... imports ...
|
||||
|
||||
class StreamingExecutor implements AgentExecutor {
|
||||
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
const { taskId, contextId, userMessage, task } = requestContext;
|
||||
|
||||
// 1. Create and publish the initial task object if it doesn't exist.
|
||||
if (!task) {
|
||||
const initialTask: Task = {
|
||||
kind: 'task',
|
||||
id: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'submitted',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
history: [userMessage],
|
||||
};
|
||||
eventBus.publish(initialTask);
|
||||
}
|
||||
|
||||
// 2. Publish 'working' state.
|
||||
eventBus.publish({
|
||||
kind: 'status-update',
|
||||
taskId,
|
||||
contextId,
|
||||
status: { state: 'working', timestamp: new Date().toISOString() },
|
||||
final: false,
|
||||
});
|
||||
|
||||
// 3. Simulate work and publish an artifact.
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
eventBus.publish({
|
||||
kind: 'artifact-update',
|
||||
taskId,
|
||||
contextId,
|
||||
artifact: { artifactId: 'result.txt', parts: [{ kind: 'text', text: 'First result.' }] },
|
||||
});
|
||||
|
||||
// 4. Publish final 'completed' state.
|
||||
eventBus.publish({
|
||||
kind: 'status-update',
|
||||
taskId,
|
||||
contextId,
|
||||
status: { state: 'completed', timestamp: new Date().toISOString() },
|
||||
final: true,
|
||||
});
|
||||
eventBus.finished();
|
||||
}
|
||||
cancelTask = async (): Promise<void> => {};
|
||||
}
|
||||
```
|
||||
|
||||
### Client: Consuming a Stream
|
||||
|
||||
The `sendMessageStream` method returns an `AsyncGenerator` that yields events as they arrive from the server.
|
||||
|
||||
```typescript
|
||||
// client.ts
|
||||
import { ClientFactory } from '@a2a-js/sdk/client';
|
||||
import { MessageSendParams } from '@a2a-js/sdk';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
// ... other imports ...
|
||||
|
||||
const factory = new ClientFactory();
|
||||
|
||||
// createFromUrl accepts baseUrl and optional path,
|
||||
// (the default path is /.well-known/agent-card.json)
|
||||
const client = await factory.createFromUrl('http://localhost:4000');
|
||||
|
||||
async function streamTask() {
|
||||
const streamParams: MessageSendParams = {
|
||||
message: {
|
||||
messageId: uuidv4(),
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text: 'Stream me some updates!' }],
|
||||
kind: 'message',
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const stream = client.sendMessageStream(streamParams);
|
||||
|
||||
for await (const event of stream) {
|
||||
if (event.kind === 'task') {
|
||||
console.log(`[${event.id}] Task created. Status: ${event.status.state}`);
|
||||
} else if (event.kind === 'status-update') {
|
||||
console.log(`[${event.taskId}] Status Updated: ${event.status.state}`);
|
||||
} else if (event.kind === 'artifact-update') {
|
||||
console.log(`[${event.taskId}] Artifact Received: ${event.artifact.artifactId}`);
|
||||
}
|
||||
}
|
||||
console.log('--- Stream finished ---');
|
||||
} catch (error) {
|
||||
console.error('Error during streaming:', error);
|
||||
}
|
||||
}
|
||||
|
||||
await streamTask();
|
||||
```
|
||||
|
||||
## Handling Task Cancellation
|
||||
|
||||
To support user-initiated cancellations, you must implement the `cancelTask` method in your **`AgentExecutor`**. The executor is responsible for gracefully stopping the ongoing work and publishing a final `canceled` status event.
|
||||
|
||||
A straightforward way to manage this is by maintaining an in-memory set of canceled task IDs. The `execute` method can then periodically check this set to see if it should terminate its process.
|
||||
|
||||
### Server: Implementing a Cancellable Executor
|
||||
|
||||
This example demonstrates an agent that simulates a multi-step process. In each step of its work, it checks if a cancellation has been requested. If so, it stops the work and updates the task's state accordingly.
|
||||
|
||||
```typescript
|
||||
// server.ts
|
||||
import {
|
||||
AgentExecutor,
|
||||
RequestContext,
|
||||
ExecutionEventBus,
|
||||
TaskStatusUpdateEvent,
|
||||
} from '@a2a-js/sdk/server';
|
||||
// ... other imports ...
|
||||
|
||||
class CancellableExecutor implements AgentExecutor {
|
||||
// Use a Set to track the IDs of tasks that have been requested to be canceled.
|
||||
private cancelledTasks = new Set<string>();
|
||||
|
||||
/**
|
||||
* When a cancellation is requested, add the taskId to our tracking set.
|
||||
* The `execute` loop will handle the rest.
|
||||
*/
|
||||
public async cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise<void> {
|
||||
console.log(`[Executor] Received cancellation request for task: ${taskId}`);
|
||||
this.cancelledTasks.add(taskId);
|
||||
}
|
||||
|
||||
public async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
const { taskId, contextId } = requestContext;
|
||||
|
||||
// Start the task
|
||||
eventBus.publish({
|
||||
kind: 'status-update',
|
||||
taskId,
|
||||
contextId,
|
||||
status: { state: 'working', timestamp: new Date().toISOString() },
|
||||
final: false,
|
||||
});
|
||||
|
||||
// Simulate a multi-step, long-running process
|
||||
for (let i = 0; i < 5; i++) {
|
||||
// **Cancellation Checkpoint**
|
||||
// Before each step, check if the task has been canceled.
|
||||
if (this.cancelledTasks.has(taskId)) {
|
||||
console.log(`[Executor] Aborting task ${taskId} due to cancellation.`);
|
||||
|
||||
// Publish the final 'canceled' status.
|
||||
const cancelledUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: { state: 'canceled', timestamp: new Date().toISOString() },
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(cancelledUpdate);
|
||||
eventBus.finished();
|
||||
|
||||
// Clean up and exit.
|
||||
this.cancelledTasks.delete(taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Simulate one step of work.
|
||||
console.log(`[Executor] Working on step ${i + 1} for task ${taskId}...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
|
||||
console.log(`[Executor] Task ${taskId} finished all steps without cancellation.`);
|
||||
|
||||
// If not canceled, finish the work and publish the completed state.
|
||||
const finalUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId,
|
||||
contextId,
|
||||
status: { state: 'completed', timestamp: new Date().toISOString() },
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(finalUpdate);
|
||||
eventBus.finished();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## A2A Push Notifications
|
||||
|
||||
For very long-running tasks (e.g., lasting minutes, hours, or even days) or when clients cannot or prefer not to maintain persistent connections (like mobile clients or serverless functions), A2A supports asynchronous updates via push notifications. This mechanism allows the A2A Server to actively notify a client-provided webhook when a significant task update occurs.
|
||||
|
||||
### Server-Side Configuration
|
||||
|
||||
To enable push notifications, your agent card must declare support:
|
||||
|
||||
```typescript
|
||||
const movieAgentCard: AgentCard = {
|
||||
// ... other properties
|
||||
capabilities: {
|
||||
streaming: true,
|
||||
pushNotifications: true, // Enable push notifications
|
||||
stateTransitionHistory: true,
|
||||
},
|
||||
// ... rest of agent card
|
||||
};
|
||||
```
|
||||
|
||||
When creating the `DefaultRequestHandler`, you can optionally provide custom push notification components:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
DefaultRequestHandler,
|
||||
InMemoryPushNotificationStore,
|
||||
DefaultPushNotificationSender,
|
||||
} from '@a2a-js/sdk/server';
|
||||
|
||||
// Optional: Custom push notification store and sender
|
||||
const pushNotificationStore = new InMemoryPushNotificationStore();
|
||||
const pushNotificationSender = new DefaultPushNotificationSender(pushNotificationStore, {
|
||||
timeout: 5000, // 5 second timeout
|
||||
tokenHeaderName: 'X-A2A-Notification-Token', // Custom header name
|
||||
});
|
||||
|
||||
const requestHandler = new DefaultRequestHandler(
|
||||
movieAgentCard,
|
||||
taskStore,
|
||||
agentExecutor,
|
||||
undefined, // eventBusManager (optional)
|
||||
pushNotificationStore, // custom store
|
||||
pushNotificationSender, // custom sender
|
||||
undefined // extendedAgentCard (optional)
|
||||
);
|
||||
```
|
||||
|
||||
### Client-Side Usage
|
||||
|
||||
Configure push notifications when sending messages:
|
||||
|
||||
```typescript
|
||||
// Configure push notification for a message
|
||||
const pushConfig: PushNotificationConfig = {
|
||||
id: 'my-notification-config', // Optional, defaults to task ID
|
||||
url: 'https://my-app.com/webhook/task-updates',
|
||||
token: 'your-auth-token', // Optional authentication token
|
||||
};
|
||||
|
||||
const sendParams: MessageSendParams = {
|
||||
message: {
|
||||
messageId: uuidv4(),
|
||||
role: 'user',
|
||||
parts: [{ kind: 'text', text: 'Hello, agent!' }],
|
||||
kind: 'message',
|
||||
},
|
||||
configuration: {
|
||||
blocking: true,
|
||||
acceptedOutputModes: ['text/plain'],
|
||||
pushNotificationConfig: pushConfig, // Add push notification config
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Webhook Endpoint Implementation
|
||||
|
||||
Your webhook endpoint should expect POST requests with the task data:
|
||||
|
||||
```typescript
|
||||
// Example Express.js webhook endpoint
|
||||
app.post('/webhook/task-updates', (req, res) => {
|
||||
const task = req.body; // The complete task object
|
||||
|
||||
// Verify the token if provided
|
||||
const token = req.headers['x-a2a-notification-token'];
|
||||
if (token !== 'your-auth-token') {
|
||||
return res.status(401).json({ error: 'Unauthorized' });
|
||||
}
|
||||
|
||||
console.log(`Task ${task.id} status: ${task.status.state}`);
|
||||
|
||||
// Process the task update
|
||||
// ...
|
||||
|
||||
res.status(200).json({ received: true });
|
||||
});
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the terms of the [Apache 2.0 License](https://raw.githubusercontent.com/google-a2a/a2a-python/refs/heads/main/LICENSE).
|
||||
|
||||
## Contributing
|
||||
|
||||
See [CONTRIBUTING.md](https://github.com/google-a2a/a2a-js/blob/main/CONTRIBUTING.md) for contribution guidelines.
|
||||
7
aitimemachine/a2a/SECURITY.md
Normal file
7
aitimemachine/a2a/SECURITY.md
Normal file
@ -0,0 +1,7 @@
|
||||
# Security Policy
|
||||
|
||||
To report a security issue, please use [g.co/vulnz](https://g.co/vulnz).
|
||||
|
||||
The Google Security Team will respond within 5 working days of your report on g.co/vulnz.
|
||||
|
||||
We use g.co/vulnz for our intake, and do coordination and disclosure here using GitHub Security Advisory to privately discuss and fix the issue.
|
||||
43
aitimemachine/a2a/eslint.config.mjs
Normal file
43
aitimemachine/a2a/eslint.config.mjs
Normal file
@ -0,0 +1,43 @@
|
||||
// @ts-check
|
||||
|
||||
import eslint from '@eslint/js';
|
||||
import { defineConfig } from 'eslint/config';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import eslintPluginPrettier from 'eslint-plugin-prettier/recommended';
|
||||
import globals from 'globals';
|
||||
|
||||
export default defineConfig(
|
||||
eslint.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
eslintPluginPrettier, // Automatically disables eslint formatting rules and enables `prettier`
|
||||
{
|
||||
ignores: ['dist/', 'node_modules/', 'src/types.ts', 'build/'],
|
||||
},
|
||||
{
|
||||
rules: {
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{
|
||||
// Ignore error for unused args and caught errors if with '_' prefix
|
||||
argsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['test/**/*.ts', 'src/samples/**/*.ts'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off', // Allow the usage of `any` in the test files and in samples
|
||||
'@typescript-eslint/no-unused-expressions': 'off', // Allow unused expressions in test files, for compatibility with 'chai'
|
||||
},
|
||||
},
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
// Define global variables for Node.js environment
|
||||
...globals.node,
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
8604
aitimemachine/a2a/package-lock.json
generated
Normal file
8604
aitimemachine/a2a/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
128
aitimemachine/a2a/package.json
Normal file
128
aitimemachine/a2a/package.json
Normal file
@ -0,0 +1,128 @@
|
||||
{
|
||||
"name": "@a2a-js/sdk",
|
||||
"version": "0.3.13",
|
||||
"description": "Server & Client SDK for Agent2Agent protocol",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/a2aproject/a2a-js.git"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"type": "module",
|
||||
"typesVersions": {
|
||||
"*": {
|
||||
"server": [
|
||||
"./dist/server/index.d.ts"
|
||||
],
|
||||
"server/express": [
|
||||
"./dist/server/express/index.d.ts"
|
||||
],
|
||||
"server/grpc": [
|
||||
"./dist/server/grpc/index.d.ts"
|
||||
],
|
||||
"client": [
|
||||
"./dist/client/index.d.ts"
|
||||
],
|
||||
"client/grpc": [
|
||||
"./dist/client/transports/grpc/index.d.ts"
|
||||
]
|
||||
}
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js",
|
||||
"require": "./dist/index.cjs"
|
||||
},
|
||||
"./server": {
|
||||
"types": "./dist/server/index.d.ts",
|
||||
"import": "./dist/server/index.js",
|
||||
"require": "./dist/server/index.cjs"
|
||||
},
|
||||
"./server/express": {
|
||||
"types": "./dist/server/express/index.d.ts",
|
||||
"import": "./dist/server/express/index.js",
|
||||
"require": "./dist/server/express/index.cjs"
|
||||
},
|
||||
"./server/grpc": {
|
||||
"types": "./dist/server/grpc/index.d.ts",
|
||||
"import": "./dist/server/grpc/index.js",
|
||||
"require": "./dist/server/grpc/index.cjs"
|
||||
},
|
||||
"./client": {
|
||||
"types": "./dist/client/index.d.ts",
|
||||
"import": "./dist/client/index.js",
|
||||
"require": "./dist/client/index.cjs"
|
||||
},
|
||||
"./client/grpc": {
|
||||
"types": "./dist/client/transports/grpc/index.d.ts",
|
||||
"import": "./dist/client/transports/grpc/index.js",
|
||||
"require": "./dist/client/transports/grpc/index.cjs"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"!dist/**/*.map",
|
||||
"README.md"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@betterer/cli": "^6.0.0-alpha.1",
|
||||
"@betterer/typescript": "^6.0.0-alpha.1",
|
||||
"@bufbuild/buf": "^1.61.0",
|
||||
"@bufbuild/protobuf": "^2.10.2",
|
||||
"@cloudflare/vitest-pool-workers": "^0.12.5",
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@grpc/grpc-js": "^1.11.0",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/node": "^22.13.14",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"esbuild": "^0.27.0",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-prettier": "^5.5.4",
|
||||
"express": "^5.1.0",
|
||||
"json-schema-to-typescript": "^15.0.4",
|
||||
"prettier": "^3.6.2",
|
||||
"supertest": "^7.1.4",
|
||||
"tsup": "^8.5.0",
|
||||
"tsx": "^4.19.3",
|
||||
"typescript": "^5.9.3",
|
||||
"typescript-eslint": "^8.46.4",
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"test": "vitest run",
|
||||
"test:edge": "vitest run --config vitest.edge.config.ts",
|
||||
"lint": "tsc --noEmit && npx eslint . --fix && betterer precommit",
|
||||
"lint:ci": "tsc --noEmit && npx eslint . && betterer ci",
|
||||
"format:readme": "prettier --write ./README.md",
|
||||
"coverage": "vitest run --coverage",
|
||||
"generate": "curl https://raw.githubusercontent.com/google-a2a/A2A/refs/heads/main/specification/json/a2a.json > spec.json && node scripts/generateTypes.js && rm spec.json",
|
||||
"test-build": "esbuild ./dist/client/index.js ./dist/server/index.js ./dist/index.js --bundle --platform=neutral --outdir=dist/tmp-checks --outbase=./dist"
|
||||
},
|
||||
"dependencies": {
|
||||
"uuid": "^11.1.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@bufbuild/protobuf": "^2.10.2",
|
||||
"@grpc/grpc-js": "^1.11.0",
|
||||
"express": "^4.21.2 || ^5.1.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"express": {
|
||||
"optional": true
|
||||
},
|
||||
"@grpc/grpc-js": {
|
||||
"optional": true
|
||||
},
|
||||
"@bufbuild/protobuf": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
13
aitimemachine/a2a/scripts/generateTypes.js
Normal file
13
aitimemachine/a2a/scripts/generateTypes.js
Normal file
@ -0,0 +1,13 @@
|
||||
import { compile } from 'json-schema-to-typescript';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const typeSchemaContents = fs.readFileSync(path.join(process.cwd(), 'spec.json'), 'utf8');
|
||||
const typeSchema = JSON.parse(typeSchemaContents.toString());
|
||||
|
||||
compile(typeSchema, 'MySchema', {
|
||||
additionalProperties: false,
|
||||
enableConstEnums: false,
|
||||
unreachableDefinitions: true,
|
||||
unknownAny: true,
|
||||
}).then((ts) => fs.writeFileSync('src/types.ts', ts));
|
||||
27
aitimemachine/a2a/src/a2a_response.ts
Normal file
27
aitimemachine/a2a/src/a2a_response.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import {
|
||||
SendMessageResponse,
|
||||
SendStreamingMessageResponse,
|
||||
GetTaskResponse,
|
||||
CancelTaskResponse,
|
||||
SetTaskPushNotificationConfigResponse,
|
||||
GetTaskPushNotificationConfigResponse,
|
||||
JSONRPCErrorResponse,
|
||||
ListTaskPushNotificationConfigSuccessResponse,
|
||||
DeleteTaskPushNotificationConfigSuccessResponse,
|
||||
GetAuthenticatedExtendedCardSuccessResponse,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* Represents any valid JSON-RPC response defined in the A2A protocol.
|
||||
*/
|
||||
export type A2AResponse =
|
||||
| SendMessageResponse
|
||||
| SendStreamingMessageResponse
|
||||
| GetTaskResponse
|
||||
| CancelTaskResponse
|
||||
| SetTaskPushNotificationConfigResponse
|
||||
| GetTaskPushNotificationConfigResponse
|
||||
| ListTaskPushNotificationConfigSuccessResponse
|
||||
| DeleteTaskPushNotificationConfigSuccessResponse
|
||||
| GetAuthenticatedExtendedCardSuccessResponse
|
||||
| JSONRPCErrorResponse; // Catch-all for other error responses
|
||||
116
aitimemachine/a2a/src/client/auth-handler.ts
Normal file
116
aitimemachine/a2a/src/client/auth-handler.ts
Normal file
@ -0,0 +1,116 @@
|
||||
export interface HttpHeaders {
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic interface for handling authentication for HTTP requests.
|
||||
*
|
||||
* - For each HTTP request, this handler is called to provide additional headers to the request through
|
||||
* the headers() function.
|
||||
* - After the server returns a response, the shouldRetryWithHeaders() function is called. Usually this
|
||||
* function responds to a 401 or 403 response or JSON-RPC codes, but can respond to any other signal -
|
||||
* that is an implementation detail of the AuthenticationHandler.
|
||||
* - If the shouldRetryWithHeaders() function returns new headers, then the request should retried with the provided
|
||||
* revised headers. These provisional headers may, or may not, be optimistically stored for subsequent requests -
|
||||
* that is an implementation detail of the AuthenticationHandler.
|
||||
* - If the request is successful and the onSuccessfulRetry() is defined, then the onSuccessfulRetry() function is
|
||||
* called with the headers that were used to successfully complete the request. This callback provides an
|
||||
* opportunity to save the headers for subsequent requests if they were not already saved.
|
||||
*
|
||||
*/
|
||||
export interface AuthenticationHandler {
|
||||
/**
|
||||
* Provides additional HTTP request headers.
|
||||
* @returns HTTP headers which may include Authorization if available.
|
||||
*/
|
||||
headers: () => Promise<HttpHeaders>;
|
||||
|
||||
/**
|
||||
* For every HTTP response (even 200s) the shouldRetryWithHeaders() method is called.
|
||||
* This method is supposed to check if the request needs to be retried and if, yes,
|
||||
* return a set of headers. An A2A server might indicate auth failures in its response
|
||||
* by JSON-rpc codes, HTTP codes like 401, 403 or headers like WWW-Authenticate.
|
||||
*
|
||||
* @param req The RequestInit object used to invoke fetch()
|
||||
* @param res The fetch Response object
|
||||
* @returns If the HTTP request should be retried then returns the HTTP headers to use,
|
||||
* or returns undefined if no retry should be made.
|
||||
*/
|
||||
shouldRetryWithHeaders: (req: RequestInit, res: Response) => Promise<HttpHeaders | undefined>;
|
||||
|
||||
/**
|
||||
* If the last HTTP request using the headers from shouldRetryWithHeaders() was successful, and
|
||||
* this function is implemented, then it will be called with the headers provided from
|
||||
* shouldRetryWithHeaders().
|
||||
*
|
||||
* This callback allows transient headers to be saved for subsequent requests only when they
|
||||
* are validated by the server.
|
||||
*/
|
||||
onSuccessfulRetry?: (headers: HttpHeaders) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Higher-order function that wraps fetch with authentication handling logic.
|
||||
* Returns a new fetch function that automatically handles authentication retries for 401/403 responses.
|
||||
*
|
||||
* @param fetchImpl The underlying fetch implementation to wrap
|
||||
* @param authHandler Authentication handler for managing auth headers and retries
|
||||
* @returns A new fetch function with authentication handling capabilities
|
||||
*
|
||||
* Usage examples:
|
||||
* - const authFetch = createAuthHandlingFetch(fetch, authHandler);
|
||||
* - const response = await authFetch(url, options);
|
||||
* - const response = await authFetch(url); // Direct function call
|
||||
*/
|
||||
export function createAuthenticatingFetchWithRetry(
|
||||
fetchImpl: typeof fetch,
|
||||
authHandler: AuthenticationHandler
|
||||
): typeof fetch {
|
||||
/**
|
||||
* Executes a fetch request with authentication handling.
|
||||
* If the auth handler provides new headers for the shouldRetryWithHeaders() function,
|
||||
* then the request is retried.
|
||||
* @param url The URL to fetch
|
||||
* @param init The fetch request options
|
||||
* @returns A Promise that resolves to the Response
|
||||
*/
|
||||
async function authFetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
// Merge auth headers with provided headers
|
||||
const authHeaders = (await authHandler.headers()) || {};
|
||||
const mergedInit: RequestInit = {
|
||||
...(init || {}),
|
||||
headers: {
|
||||
...authHeaders,
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
};
|
||||
|
||||
let response = await fetchImpl(url, mergedInit);
|
||||
|
||||
// Check if the auth handler wants to retry the request with new headers
|
||||
const updatedHeaders = await authHandler.shouldRetryWithHeaders(mergedInit, response);
|
||||
if (updatedHeaders) {
|
||||
// Retry request with revised headers
|
||||
const retryInit: RequestInit = {
|
||||
...(init || {}),
|
||||
headers: {
|
||||
...updatedHeaders,
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
};
|
||||
response = await fetchImpl(url, retryInit);
|
||||
|
||||
if (response.ok && authHandler.onSuccessfulRetry) {
|
||||
await authHandler.onSuccessfulRetry(updatedHeaders); // Remember headers that worked
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// Copy fetch properties to maintain compatibility
|
||||
Object.setPrototypeOf(authFetch, Object.getPrototypeOf(fetchImpl));
|
||||
Object.defineProperties(authFetch, Object.getOwnPropertyDescriptors(fetchImpl));
|
||||
|
||||
return authFetch;
|
||||
}
|
||||
108
aitimemachine/a2a/src/client/card-resolver.ts
Normal file
108
aitimemachine/a2a/src/client/card-resolver.ts
Normal file
@ -0,0 +1,108 @@
|
||||
import { AGENT_CARD_PATH } from '../constants.js';
|
||||
import { AgentCard } from '../types.js';
|
||||
import { AgentCard as PBAgentCard } from '../types/pb/a2a_types.js';
|
||||
import { FromProto } from '../types/converters/from_proto.js';
|
||||
|
||||
export interface AgentCardResolverOptions {
|
||||
path?: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
export interface AgentCardResolver {
|
||||
/**
|
||||
* Fetches the agent card based on provided base URL and path,
|
||||
*/
|
||||
resolve(baseUrl: string, path?: string): Promise<AgentCard>;
|
||||
}
|
||||
|
||||
export class DefaultAgentCardResolver implements AgentCardResolver {
|
||||
constructor(public readonly options?: AgentCardResolverOptions) {}
|
||||
|
||||
/**
|
||||
* Fetches the agent card based on provided base URL and path.
|
||||
* Path is selected in the following order:
|
||||
* 1) path parameter
|
||||
* 2) path from options
|
||||
* 3) .well-known/agent-card.json
|
||||
*/
|
||||
async resolve(baseUrl: string, path?: string): Promise<AgentCard> {
|
||||
const agentCardUrl = new URL(path ?? this.options?.path ?? AGENT_CARD_PATH, baseUrl);
|
||||
const response = await this.fetchImpl(agentCardUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status}`);
|
||||
}
|
||||
const rawCard = await response.json();
|
||||
return this.normalizeAgentCard(rawCard);
|
||||
}
|
||||
|
||||
private fetchImpl(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
|
||||
if (this.options?.fetchImpl) {
|
||||
return this.options.fetchImpl(...args);
|
||||
}
|
||||
return fetch(...args);
|
||||
}
|
||||
|
||||
/*
|
||||
* In the v0.3.0 specification, there was a structural drift between the JSON Schema data model
|
||||
* and the Protobuf-based data model for AgentCards.
|
||||
* The JSON Schema format uses a `"type"` discriminator (e.g., `{"type": "openIdConnect"}`),
|
||||
* while the Protobuf JSON representation uses the `oneof` field name as the discriminator
|
||||
* (e.g., `{"openIdConnectSecurityScheme": {...}}`).
|
||||
*
|
||||
* The A2A SDK internal logic expects the JSON Schema-based format. This fallback detection
|
||||
* allows us to parse cards served by endpoints returning the Protobuf JSON structure by
|
||||
* identifying the lack of the "type" field in security schemes or the presence of the
|
||||
* "schemes" wrapper in security entries, and normalizing it before use.
|
||||
*/
|
||||
private normalizeAgentCard(card: unknown): AgentCard {
|
||||
if (this.isProtoAgentCard(card)) {
|
||||
const parsedProto = PBAgentCard.fromJSON(card);
|
||||
return FromProto.agentCard(parsedProto);
|
||||
}
|
||||
return card as AgentCard;
|
||||
}
|
||||
|
||||
private isProtoAgentCard(card: unknown): boolean {
|
||||
if (!card || typeof card !== 'object') return false;
|
||||
const c = card as Record<string, unknown>;
|
||||
|
||||
if (this.hasProtoSecurity(c.security)) return true;
|
||||
|
||||
if (this.hasProtoSecuritySchemes(c.securitySchemes)) return true;
|
||||
|
||||
if (Array.isArray(c.skills)) {
|
||||
return c.skills.some(
|
||||
(skill) =>
|
||||
skill &&
|
||||
typeof skill === 'object' &&
|
||||
this.hasProtoSecurity((skill as Record<string, unknown>).security)
|
||||
);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private hasProtoSecurity(securityArray: unknown): boolean {
|
||||
if (Array.isArray(securityArray) && securityArray.length > 0) {
|
||||
const first = securityArray[0];
|
||||
return first && typeof first === 'object' && 'schemes' in first;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private hasProtoSecuritySchemes(securitySchemes: unknown): boolean {
|
||||
if (securitySchemes && typeof securitySchemes === 'object') {
|
||||
const schemes = Object.values(securitySchemes);
|
||||
if (schemes.length > 0) {
|
||||
const first = schemes[0];
|
||||
// Proto JSON maps use the oneof field name directly rather than a "type" property
|
||||
return first && typeof first === 'object' && !('type' in first);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const AgentCardResolver = {
|
||||
default: new DefaultAgentCardResolver(),
|
||||
};
|
||||
487
aitimemachine/a2a/src/client/client.ts
Normal file
487
aitimemachine/a2a/src/client/client.ts
Normal file
@ -0,0 +1,487 @@
|
||||
import {
|
||||
AgentCard,
|
||||
JSONRPCResponse,
|
||||
MessageSendParams,
|
||||
SendMessageResponse,
|
||||
TaskQueryParams,
|
||||
GetTaskResponse,
|
||||
TaskIdParams,
|
||||
CancelTaskResponse,
|
||||
TaskPushNotificationConfig, // Renamed from PushNotificationConfigParams for direct schema alignment
|
||||
SetTaskPushNotificationConfigResponse,
|
||||
GetTaskPushNotificationConfigResponse,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigResponse,
|
||||
DeleteTaskPushNotificationConfigResponse,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
Message,
|
||||
Task,
|
||||
TaskArtifactUpdateEvent,
|
||||
TaskStatusUpdateEvent,
|
||||
A2ARequest,
|
||||
JSONRPCErrorResponse,
|
||||
} from '../types.js'; // Assuming schema.ts is in the same directory or appropriately pathed
|
||||
import { AGENT_CARD_PATH } from '../constants.js';
|
||||
import { JsonRpcTransport } from './transports/json_rpc_transport.js';
|
||||
import { RequestOptions } from './multitransport-client.js';
|
||||
|
||||
export type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
|
||||
|
||||
export type SendMessageResult = Message | Task;
|
||||
|
||||
export interface A2AClientOptions {
|
||||
agentCardPath?: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
/**
|
||||
* A2AClient is a TypeScript HTTP client for interacting with A2A-compliant agents.
|
||||
* Only JSON-RPC transport is supported.
|
||||
* @deprecated Use {@link ClientFactory}
|
||||
*/
|
||||
export class A2AClient {
|
||||
private static emptyOptions?: RequestOptions = undefined;
|
||||
|
||||
private readonly agentCardPromise: Promise<AgentCard>;
|
||||
private readonly customFetchImpl?: typeof fetch;
|
||||
private serviceEndpointUrl?: string; // To be populated from AgentCard after fetchin
|
||||
|
||||
// A2AClient is built around JSON-RPC types, so it will only support JSON-RPC transport, new client with transport agnostic interface is going to be created for multi-transport.
|
||||
// New transport abstraction isn't going to expose individual transport specific fields, so to keep returning JSON-RPC IDs here for compatibility,
|
||||
// keep counter here and pass it to JsonRpcTransport via an optional idOverride parameter (which is not visible via transport-agnostic A2ATransport interface).
|
||||
private transport?: JsonRpcTransport;
|
||||
private requestIdCounter: number = 1;
|
||||
|
||||
/**
|
||||
* Constructs an A2AClient instance from an AgentCard.
|
||||
* @param agentCard The AgentCard object.
|
||||
* @param options Optional. The options for the A2AClient including the fetch/auth implementation.
|
||||
*/
|
||||
constructor(agentCard: AgentCard | string, options?: A2AClientOptions) {
|
||||
this.customFetchImpl = options?.fetchImpl;
|
||||
if (typeof agentCard === 'string') {
|
||||
console.warn(
|
||||
'Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead.'
|
||||
);
|
||||
this.agentCardPromise = this._fetchAndCacheAgentCard(agentCard, options?.agentCardPath);
|
||||
} else {
|
||||
if (!agentCard.url) {
|
||||
throw new Error(
|
||||
"Provided Agent Card does not contain a valid 'url' for the service endpoint."
|
||||
);
|
||||
}
|
||||
this.serviceEndpointUrl = agentCard.url;
|
||||
this.agentCardPromise = Promise.resolve(agentCard);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamically resolves the fetch implementation to use for requests.
|
||||
* Prefers a custom implementation if provided, otherwise falls back to the global fetch.
|
||||
* @returns The fetch implementation.
|
||||
* @param args Arguments to pass to the fetch implementation.
|
||||
* @throws If no fetch implementation is available.
|
||||
*/
|
||||
private _fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
|
||||
if (this.customFetchImpl) {
|
||||
return this.customFetchImpl(...args);
|
||||
}
|
||||
if (typeof fetch === 'function') {
|
||||
return fetch(...args);
|
||||
}
|
||||
throw new Error(
|
||||
'A `fetch` implementation was not provided and is not available in the global scope. ' +
|
||||
'Please provide a `fetchImpl` in the A2AClientOptions. ' +
|
||||
'For earlier Node.js versions (pre-v18), you can use a library like `node-fetch`.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an A2AClient instance by fetching the AgentCard from a URL then constructing the A2AClient.
|
||||
* @param agentCardUrl The URL of the agent card.
|
||||
* @param options Optional. The options for the A2AClient including the fetch/auth implementation.
|
||||
* @returns A Promise that resolves to a new A2AClient instance.
|
||||
*/
|
||||
public static async fromCardUrl(
|
||||
agentCardUrl: string,
|
||||
options?: A2AClientOptions
|
||||
): Promise<A2AClient> {
|
||||
const fetchImpl = options?.fetchImpl;
|
||||
const requestInit = {
|
||||
headers: { Accept: 'application/json' },
|
||||
};
|
||||
|
||||
let response: Response;
|
||||
if (fetchImpl) {
|
||||
response = await fetchImpl(agentCardUrl, requestInit);
|
||||
} else if (typeof fetch === 'function') {
|
||||
// Use the global fetch implementation if no custom one is provided.
|
||||
response = await fetch(agentCardUrl, requestInit);
|
||||
} else {
|
||||
throw new Error(
|
||||
'A `fetch` implementation was not provided and is not available in the global scope. ' +
|
||||
'Please provide a `fetchImpl` in the A2AClientOptions. ' +
|
||||
'For earlier Node.js versions (pre-v18), you can use a library like `node-fetch`.'
|
||||
);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
|
||||
let agentCard: AgentCard;
|
||||
try {
|
||||
agentCard = await response.json();
|
||||
} catch (error) {
|
||||
console.error('Failed to parse Agent Card JSON:', error);
|
||||
throw new Error(
|
||||
`Failed to parse Agent Card JSON from ${agentCardUrl}. Original error: ${(error as Error).message}`
|
||||
);
|
||||
}
|
||||
|
||||
return new A2AClient(agentCard, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to the agent.
|
||||
* The behavior (blocking/non-blocking) and push notification configuration
|
||||
* are specified within the `params.configuration` object.
|
||||
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
|
||||
* @param params The parameters for sending the message, including the message content and configuration.
|
||||
* @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
|
||||
*/
|
||||
public async sendMessage(params: MessageSendParams): Promise<SendMessageResponse> {
|
||||
return await this.invokeJsonRpc<MessageSendParams, SendMessageResponse>(
|
||||
(t, p, id) => t.sendMessage(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
|
||||
* Push notification configuration can be specified in `params.configuration`.
|
||||
* Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
|
||||
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
|
||||
* @param params The parameters for sending the message.
|
||||
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
|
||||
* The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
|
||||
*/
|
||||
public async *sendMessageStream(
|
||||
params: MessageSendParams
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const agentCard = await this.agentCardPromise; // Ensure agent card is fetched
|
||||
if (!agentCard.capabilities?.streaming) {
|
||||
throw new Error(
|
||||
'Agent does not support streaming (AgentCard.capabilities.streaming is not true).'
|
||||
);
|
||||
}
|
||||
|
||||
const transport = await this._getOrCreateTransport();
|
||||
yield* transport.sendMessageStream(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets or updates the push notification configuration for a given task.
|
||||
* Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
|
||||
* @param params Parameters containing the taskId and the TaskPushNotificationConfig.
|
||||
* @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig
|
||||
): Promise<SetTaskPushNotificationConfigResponse> {
|
||||
const agentCard = await this.agentCardPromise;
|
||||
if (!agentCard.capabilities?.pushNotifications) {
|
||||
throw new Error(
|
||||
'Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true).'
|
||||
);
|
||||
}
|
||||
return await this.invokeJsonRpc<
|
||||
TaskPushNotificationConfig,
|
||||
SetTaskPushNotificationConfigResponse
|
||||
>((t, p, id) => t.setTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the push notification configuration for a given task.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async getTaskPushNotificationConfig(
|
||||
params: TaskIdParams
|
||||
): Promise<GetTaskPushNotificationConfigResponse> {
|
||||
return await this.invokeJsonRpc<TaskIdParams, GetTaskPushNotificationConfigResponse>(
|
||||
(t, p, id) => t.getTaskPushNotificationConfig(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the push notification configurations for a given task.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to ListTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams
|
||||
): Promise<ListTaskPushNotificationConfigResponse> {
|
||||
return await this.invokeJsonRpc<
|
||||
ListTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigResponse
|
||||
>((t, p, id) => t.listTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the push notification configuration for a given task.
|
||||
* @param params Parameters containing the taskId and push notification configuration ID.
|
||||
* @returns A Promise resolving to DeleteTaskPushNotificationConfigResponse.
|
||||
*/
|
||||
public async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams
|
||||
): Promise<DeleteTaskPushNotificationConfigResponse> {
|
||||
return await this.invokeJsonRpc<
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigResponse
|
||||
>((t, p, id) => t.deleteTaskPushNotificationConfig(p, A2AClient.emptyOptions, id), params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a task by its ID.
|
||||
* @param params Parameters containing the taskId and optional historyLength.
|
||||
* @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
|
||||
*/
|
||||
public async getTask(params: TaskQueryParams): Promise<GetTaskResponse> {
|
||||
return await this.invokeJsonRpc<TaskQueryParams, GetTaskResponse>(
|
||||
(t, p, id) => t.getTask(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels a task by its ID.
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
|
||||
*/
|
||||
public async cancelTask(params: TaskIdParams): Promise<CancelTaskResponse> {
|
||||
return await this.invokeJsonRpc<TaskIdParams, CancelTaskResponse>(
|
||||
(t, p, id) => t.cancelTask(p, A2AClient.emptyOptions, id),
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @template TExtensionParams The type of parameters for the custom extension method.
|
||||
* @template TExtensionResponse The type of response expected from the custom extension method.
|
||||
* This should extend JSONRPCResponse. This ensures the extension response is still a valid A2A response.
|
||||
* @param method Custom JSON-RPC method defined in the AgentCard's extensions.
|
||||
* @param params Extension paramters defined in the AgentCard's extensions.
|
||||
* @returns A Promise that resolves to the RPC response.
|
||||
*/
|
||||
public async callExtensionMethod<TExtensionParams, TExtensionResponse extends JSONRPCResponse>(
|
||||
method: string,
|
||||
params: TExtensionParams
|
||||
) {
|
||||
const transport = await this._getOrCreateTransport();
|
||||
try {
|
||||
return await transport.callExtensionMethod<TExtensionParams, TExtensionResponse>(
|
||||
method,
|
||||
params,
|
||||
this.requestIdCounter++
|
||||
);
|
||||
} catch (e) {
|
||||
// For compatibility, return JSON-RPC errors as errors instead of throwing transport-agnostic errors
|
||||
// produced by JsonRpcTransport.
|
||||
const errorResponse = extractJSONRPCError(e);
|
||||
if (errorResponse) {
|
||||
return errorResponse as TExtensionResponse;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resubscribes to a task's event stream using Server-Sent Events (SSE).
|
||||
* This is used if a previous SSE connection for an active task was broken.
|
||||
* Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
|
||||
* @param params Parameters containing the taskId.
|
||||
* @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
|
||||
*/
|
||||
public async *resubscribeTask(
|
||||
params: TaskIdParams
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const agentCard = await this.agentCardPromise;
|
||||
if (!agentCard.capabilities?.streaming) {
|
||||
throw new Error('Agent does not support streaming (required for tasks/resubscribe).');
|
||||
}
|
||||
|
||||
const transport = await this._getOrCreateTransport();
|
||||
yield* transport.resubscribeTask(params);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Functions used to support old A2AClient Constructor to be deprecated soon
|
||||
// TODOs:
|
||||
// * remove `agentCardPromise`, and just use agentCard initialized
|
||||
// * _getServiceEndpoint can be made synchronous or deleted and accessed via
|
||||
// agentCard.url
|
||||
// * getAgentCard changed to this.agentCard
|
||||
// * delete resolveAgentCardUrl(), _fetchAndCacheAgentCard(),
|
||||
// agentCardPath from A2AClientOptions
|
||||
// * delete _getOrCreateTransport
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private async _getOrCreateTransport(): Promise<JsonRpcTransport> {
|
||||
if (this.transport) {
|
||||
return this.transport;
|
||||
}
|
||||
|
||||
const endpoint = await this._getServiceEndpoint();
|
||||
this.transport = new JsonRpcTransport({ fetchImpl: this.customFetchImpl, endpoint: endpoint });
|
||||
return this.transport;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
|
||||
* This method is called by the constructor.
|
||||
* @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com)
|
||||
* @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
|
||||
* @returns A Promise that resolves to the AgentCard.
|
||||
*/
|
||||
private async _fetchAndCacheAgentCard(
|
||||
agentBaseUrl: string,
|
||||
agentCardPath?: string
|
||||
): Promise<AgentCard> {
|
||||
try {
|
||||
const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
|
||||
const response = await this._fetch(agentCardUrl, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
const agentCard: AgentCard = await response.json();
|
||||
if (!agentCard.url) {
|
||||
throw new Error(
|
||||
"Fetched Agent Card does not contain a valid 'url' for the service endpoint."
|
||||
);
|
||||
}
|
||||
this.serviceEndpointUrl = agentCard.url; // Cache the service endpoint URL from the agent card
|
||||
return agentCard;
|
||||
} catch (error) {
|
||||
console.error('Error fetching or parsing Agent Card:', error);
|
||||
// Allow the promise to reject so users of agentCardPromise can handle it.
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the Agent Card.
|
||||
* If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
|
||||
* Otherwise, it returns the card fetched and cached during client construction.
|
||||
* @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
|
||||
* @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
|
||||
* If provided, this will fetch a new card, not use the cached one from the constructor's URL.
|
||||
* @returns A Promise that resolves to the AgentCard.
|
||||
*/
|
||||
public async getAgentCard(agentBaseUrl?: string, agentCardPath?: string): Promise<AgentCard> {
|
||||
if (agentBaseUrl) {
|
||||
const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
|
||||
|
||||
const response = await this._fetch(agentCardUrl, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
return (await response.json()) as AgentCard;
|
||||
}
|
||||
// If no specific URL is given, return the promise for the initially configured agent's card.
|
||||
return this.agentCardPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the agent card URL based on the agent URL.
|
||||
* @param agentBaseUrl The agent URL.
|
||||
* @param agentCardPath Optional relative path to the agent card, defaults to .well-known/agent-card.json
|
||||
*/
|
||||
private resolveAgentCardUrl(
|
||||
agentBaseUrl: string,
|
||||
agentCardPath: string = AGENT_CARD_PATH
|
||||
): string {
|
||||
return `${agentBaseUrl.replace(/\/$/, '')}/${agentCardPath.replace(/^\//, '')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the RPC service endpoint URL. Ensures the agent card has been fetched first.
|
||||
* @returns A Promise that resolves to the service endpoint URL string.
|
||||
*/
|
||||
private async _getServiceEndpoint(): Promise<string> {
|
||||
if (this.serviceEndpointUrl) {
|
||||
return this.serviceEndpointUrl;
|
||||
}
|
||||
// If serviceEndpointUrl is not set, it means the agent card fetch is pending or failed.
|
||||
// Awaiting agentCardPromise will either resolve it or throw if fetching failed.
|
||||
await this.agentCardPromise;
|
||||
if (!this.serviceEndpointUrl) {
|
||||
// This case should ideally be covered by the error handling in _fetchAndCacheAgentCard
|
||||
throw new Error(
|
||||
'Agent Card URL for RPC endpoint is not available. Fetching might have failed.'
|
||||
);
|
||||
}
|
||||
return this.serviceEndpointUrl;
|
||||
}
|
||||
|
||||
private async invokeJsonRpc<TParams extends JsonRpcParams, TResponse extends JSONRPCResponse>(
|
||||
caller: JsonRpcCaller<TParams, TResponse>,
|
||||
params?: TParams
|
||||
): Promise<TResponse> {
|
||||
const transport = await this._getOrCreateTransport();
|
||||
const requestId = this.requestIdCounter++;
|
||||
try {
|
||||
const result = await caller(transport, params, requestId);
|
||||
return {
|
||||
id: requestId,
|
||||
jsonrpc: '2.0',
|
||||
result: result ?? null, // JSON-RPC requires result property on success, it will be null for "void" methods.
|
||||
} as TResponse;
|
||||
} catch (e) {
|
||||
// For compatibility, return JSON-RPC errors as response objects instead of throwing transport-agnostic errors
|
||||
// produced by JsonRpcTransport.
|
||||
const errorResponse = extractJSONRPCError(e);
|
||||
if (errorResponse) {
|
||||
return errorResponse as TResponse;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function extractJSONRPCError(error: unknown): JSONRPCErrorResponse {
|
||||
if (
|
||||
error instanceof Object &&
|
||||
'errorResponse' in error &&
|
||||
error.errorResponse instanceof Object &&
|
||||
'jsonrpc' in error.errorResponse &&
|
||||
error.errorResponse.jsonrpc === '2.0' &&
|
||||
'error' in error.errorResponse &&
|
||||
error.errorResponse.error !== null
|
||||
) {
|
||||
return error.errorResponse as JSONRPCErrorResponse;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Utility unexported types to properly factor out common "compatibility" logic via invokeJsonRpc.
|
||||
type ParamsOf<T> = T extends { params: unknown } ? T['params'] : undefined;
|
||||
type ResultOf<T> = T extends { result: unknown } ? T['result'] : void;
|
||||
type JsonRpcParams = ParamsOf<A2ARequest>;
|
||||
type JsonRpcCaller<TParams extends JsonRpcParams, TResponse extends JSONRPCResponse> = (
|
||||
transport: JsonRpcTransport,
|
||||
params: TParams,
|
||||
idOverride: number
|
||||
) => Promise<ResultOf<TResponse>>;
|
||||
62
aitimemachine/a2a/src/client/context.ts
Normal file
62
aitimemachine/a2a/src/client/context.ts
Normal file
@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Opaque context object to carry per-call context data.
|
||||
* Use {@link ClientCallContextKey} to create typed keys for storing and retrieving values.
|
||||
*/
|
||||
export type ClientCallContext = Record<symbol, unknown>;
|
||||
|
||||
/**
|
||||
* Function that applies an update to a {@link ClientCallContext}.
|
||||
*/
|
||||
export type ContextUpdate = (context: ClientCallContext) => void;
|
||||
|
||||
export const ClientCallContext = {
|
||||
/**
|
||||
* Create a new {@link ClientCallContext} with optional updates applied.
|
||||
*/
|
||||
create: (...updates: ContextUpdate[]): ClientCallContext => {
|
||||
return ClientCallContext.createFrom(undefined, ...updates);
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new {@link ClientCallContext} based on an existing one with updates applied.
|
||||
*/
|
||||
createFrom: (
|
||||
context: ClientCallContext | undefined,
|
||||
...updates: ContextUpdate[]
|
||||
): ClientCallContext => {
|
||||
const result = context ? { ...context } : {};
|
||||
for (const update of updates) {
|
||||
update(result);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Each instance represents a unique key for storing
|
||||
* and retrieving typed values in a {@link ClientCallContext}.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const key = new ClientCallContextKey<string>('My key');
|
||||
* const context = ClientCallContext.create(key.set('example-value'));
|
||||
* const value = key.get(context); // 'example-value'
|
||||
* ```
|
||||
*/
|
||||
export class ClientCallContextKey<T> {
|
||||
public readonly symbol: symbol;
|
||||
|
||||
constructor(description: string) {
|
||||
this.symbol = Symbol(description);
|
||||
}
|
||||
|
||||
set(value: T): ContextUpdate {
|
||||
return (context) => {
|
||||
context[this.symbol] = value;
|
||||
};
|
||||
}
|
||||
|
||||
get(context: ClientCallContext): T | undefined {
|
||||
return context[this.symbol] as T | undefined;
|
||||
}
|
||||
}
|
||||
213
aitimemachine/a2a/src/client/factory.ts
Normal file
213
aitimemachine/a2a/src/client/factory.ts
Normal file
@ -0,0 +1,213 @@
|
||||
import { TransportProtocolName } from '../core.js';
|
||||
import { AgentCard } from '../types.js';
|
||||
import { AgentCardResolver } from './card-resolver.js';
|
||||
import { Client, ClientConfig } from './multitransport-client.js';
|
||||
import { JsonRpcTransportFactory } from './transports/json_rpc_transport.js';
|
||||
import { RestTransportFactory } from './transports/rest_transport.js';
|
||||
import { TransportFactory } from './transports/transport.js';
|
||||
|
||||
export interface ClientFactoryOptions {
|
||||
/**
|
||||
* Transport factories to use.
|
||||
* Effectively defines transports supported by this client factory.
|
||||
*/
|
||||
transports: TransportFactory[];
|
||||
|
||||
/**
|
||||
* Client config to be used for clients created by this factory.
|
||||
*/
|
||||
clientConfig?: ClientConfig;
|
||||
|
||||
/**
|
||||
* Transport preferences to override ones defined by the agent card.
|
||||
* If no matches are found among preferred transports, agent card values are used next.
|
||||
*/
|
||||
preferredTransports?: TransportProtocolName[];
|
||||
|
||||
/**
|
||||
* Used for createFromAgentCardUrl to download agent card.
|
||||
*/
|
||||
cardResolver?: AgentCardResolver;
|
||||
}
|
||||
|
||||
export const ClientFactoryOptions = {
|
||||
/**
|
||||
* SDK default options for {@link ClientFactory}.
|
||||
*/
|
||||
default: {
|
||||
transports: [new JsonRpcTransportFactory(), new RestTransportFactory()],
|
||||
} as Readonly<ClientFactoryOptions>,
|
||||
|
||||
/**
|
||||
* Creates new options by merging an original and an override object.
|
||||
* Transports are merged based on `TransportFactory.protocolName`,
|
||||
* interceptors are concatenated, other fields are overriden.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const options = ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
|
||||
* transports: [new MyCustomTransportFactory()], // adds a custom transport
|
||||
* clientConfig: { interceptors: [new MyInterceptor()] }, // adds a custom interceptor
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
createFrom(
|
||||
original: ClientFactoryOptions,
|
||||
overrides: Partial<ClientFactoryOptions>
|
||||
): ClientFactoryOptions {
|
||||
return {
|
||||
...original,
|
||||
...overrides,
|
||||
transports: mergeTransports(original.transports, overrides.transports),
|
||||
clientConfig: {
|
||||
...(original.clientConfig ?? {}),
|
||||
...(overrides.clientConfig ?? {}),
|
||||
interceptors: mergeArrays(
|
||||
original.clientConfig?.interceptors,
|
||||
overrides.clientConfig?.interceptors
|
||||
),
|
||||
acceptedOutputModes:
|
||||
overrides.clientConfig?.acceptedOutputModes ?? original.clientConfig?.acceptedOutputModes,
|
||||
},
|
||||
preferredTransports: overrides.preferredTransports ?? original.preferredTransports,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export class ClientFactory {
|
||||
private readonly transportsByName: CaseInsensitiveMap<TransportFactory>;
|
||||
private readonly agentCardResolver: AgentCardResolver;
|
||||
|
||||
constructor(public readonly options: ClientFactoryOptions = ClientFactoryOptions.default) {
|
||||
if (!options.transports || options.transports.length === 0) {
|
||||
throw new Error('No transports provided');
|
||||
}
|
||||
this.transportsByName = transportsByName(options.transports);
|
||||
for (const transport of options.preferredTransports ?? []) {
|
||||
if (!this.transportsByName.has(transport)) {
|
||||
throw new Error(
|
||||
`Unknown preferred transport: ${transport}, available transports: ${[...this.transportsByName.keys()].join()}`
|
||||
);
|
||||
}
|
||||
}
|
||||
this.agentCardResolver = options.cardResolver ?? AgentCardResolver.default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new client from the provided agent card.
|
||||
*/
|
||||
async createFromAgentCard(agentCard: AgentCard): Promise<Client> {
|
||||
const agentCardPreferred = agentCard.preferredTransport ?? JsonRpcTransportFactory.name;
|
||||
const additionalInterfaces = agentCard.additionalInterfaces ?? [];
|
||||
const urlsPerAgentTransports = new CaseInsensitiveMap<string>([
|
||||
[agentCardPreferred, agentCard.url],
|
||||
...additionalInterfaces.map<[string, string]>((i) => [i.transport, i.url]),
|
||||
]);
|
||||
const transportsByPreference = [
|
||||
...(this.options.preferredTransports ?? []),
|
||||
agentCardPreferred,
|
||||
...additionalInterfaces.map((i) => i.transport),
|
||||
];
|
||||
for (const transport of transportsByPreference) {
|
||||
const url = urlsPerAgentTransports.get(transport);
|
||||
const factory = this.transportsByName.get(transport);
|
||||
if (factory && url) {
|
||||
return new Client(
|
||||
await factory.create(url, agentCard),
|
||||
agentCard,
|
||||
this.options.clientConfig
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
'No compatible transport found, available transports: ' +
|
||||
[...this.transportsByName.keys()].join()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads agent card using AgentCardResolver from options
|
||||
* and creates a new client from the downloaded card.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const factory = new ClientFactory(); // use default options and default {@link AgentCardResolver}.
|
||||
* const client1 = await factory.createFromUrl('https://example.com'); // /.well-known/agent-card.json is used by default
|
||||
* const client2 = await factory.createFromUrl('https://example.com', '/my-agent-card.json'); // specify custom path
|
||||
* const client3 = await factory.createFromUrl('https://example.com/my-agent-card.json', ''); // specify full URL and set path to empty
|
||||
* ```
|
||||
*/
|
||||
async createFromUrl(baseUrl: string, path?: string): Promise<Client> {
|
||||
const agentCard = await this.agentCardResolver.resolve(baseUrl, path);
|
||||
return this.createFromAgentCard(agentCard);
|
||||
}
|
||||
}
|
||||
|
||||
function mergeTransports(
|
||||
original: TransportFactory[],
|
||||
overrides: TransportFactory[] | undefined
|
||||
): TransportFactory[] {
|
||||
if (!overrides) {
|
||||
return original;
|
||||
}
|
||||
|
||||
const result = transportsByName(original);
|
||||
const overridesByName = transportsByName(overrides);
|
||||
for (const [name, factory] of overridesByName) {
|
||||
result.set(name, factory);
|
||||
}
|
||||
return Array.from(result.values());
|
||||
}
|
||||
|
||||
function transportsByName(
|
||||
transports: ReadonlyArray<TransportFactory> | undefined
|
||||
): CaseInsensitiveMap<TransportFactory> {
|
||||
const result = new CaseInsensitiveMap<TransportFactory>();
|
||||
if (!transports) {
|
||||
return result;
|
||||
}
|
||||
for (const t of transports) {
|
||||
if (result.has(t.protocolName)) {
|
||||
throw new Error(`Duplicate protocol name: ${t.protocolName}`);
|
||||
}
|
||||
result.set(t.protocolName, t);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function mergeArrays<T>(
|
||||
a1: ReadonlyArray<T> | undefined,
|
||||
a2: ReadonlyArray<T> | undefined
|
||||
): T[] | undefined {
|
||||
if (!a1 && !a2) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return [...(a1 ?? []), ...(a2 ?? [])];
|
||||
}
|
||||
|
||||
/**
|
||||
* A Map that normalizes string keys to uppercase for case-insensitive lookups.
|
||||
* This prevents errors from inconsistent casing in protocol names.
|
||||
*/
|
||||
class CaseInsensitiveMap<T> extends Map<string, T> {
|
||||
private normalizeKey(key: string): string {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
|
||||
override set(key: string, value: T): this {
|
||||
return super.set(this.normalizeKey(key), value);
|
||||
}
|
||||
|
||||
override get(key: string): T | undefined {
|
||||
return super.get(this.normalizeKey(key));
|
||||
}
|
||||
|
||||
override has(key: string): boolean {
|
||||
return super.has(this.normalizeKey(key));
|
||||
}
|
||||
|
||||
override delete(key: string): boolean {
|
||||
return super.delete(this.normalizeKey(key));
|
||||
}
|
||||
}
|
||||
47
aitimemachine/a2a/src/client/index.ts
Normal file
47
aitimemachine/a2a/src/client/index.ts
Normal file
@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Client entry point for the A2A Server V2 library.
|
||||
*/
|
||||
|
||||
export { A2AClient } from './client.js';
|
||||
export type { A2AClientOptions } from './client.js';
|
||||
export * from './auth-handler.js';
|
||||
export {
|
||||
AgentCardResolver,
|
||||
type AgentCardResolverOptions,
|
||||
DefaultAgentCardResolver,
|
||||
} from './card-resolver.js';
|
||||
export { Client, type ClientConfig, type RequestOptions } from './multitransport-client.js';
|
||||
export type { Transport, TransportFactory } from './transports/transport.js';
|
||||
export { ClientFactory, ClientFactoryOptions } from './factory.js';
|
||||
export {
|
||||
JsonRpcTransport,
|
||||
JsonRpcTransportFactory,
|
||||
type JsonRpcTransportOptions,
|
||||
} from './transports/json_rpc_transport.js';
|
||||
export {
|
||||
RestTransport,
|
||||
RestTransportFactory,
|
||||
type RestTransportOptions,
|
||||
} from './transports/rest_transport.js';
|
||||
export type {
|
||||
CallInterceptor,
|
||||
BeforeArgs,
|
||||
AfterArgs,
|
||||
ClientCallInput,
|
||||
ClientCallResult,
|
||||
} from './interceptors.js';
|
||||
export {
|
||||
ServiceParameters,
|
||||
type ServiceParametersUpdate,
|
||||
withA2AExtensions,
|
||||
} from './service-parameters.js';
|
||||
export { ClientCallContext, type ContextUpdate, ClientCallContextKey } from './context.js';
|
||||
export {
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
ContentTypeNotSupportedError,
|
||||
InvalidAgentResponseError,
|
||||
PushNotificationNotSupportedError,
|
||||
TaskNotCancelableError,
|
||||
TaskNotFoundError,
|
||||
UnsupportedOperationError,
|
||||
} from '../errors.js';
|
||||
134
aitimemachine/a2a/src/client/interceptors.ts
Normal file
134
aitimemachine/a2a/src/client/interceptors.ts
Normal file
@ -0,0 +1,134 @@
|
||||
import { AgentCard } from '../types.js';
|
||||
import { A2AStreamEventData } from './client.js';
|
||||
import { Client } from './multitransport-client.js';
|
||||
import { RequestOptions } from './multitransport-client.js';
|
||||
|
||||
export interface CallInterceptor {
|
||||
/**
|
||||
* Invoked before transport method.
|
||||
*/
|
||||
before(args: BeforeArgs): Promise<void>;
|
||||
|
||||
/**
|
||||
* Invoked after transport method.
|
||||
*/
|
||||
after(args: AfterArgs): Promise<void>;
|
||||
}
|
||||
|
||||
export interface BeforeArgs<K extends keyof Client = keyof Client> {
|
||||
/**
|
||||
* Identifies the client method invoked and its payload.
|
||||
* Payload inside the input object can be modified.
|
||||
*/
|
||||
readonly input: ClientCallInput<K>;
|
||||
|
||||
/**
|
||||
* Identifies the agent card cached on the client
|
||||
*/
|
||||
readonly agentCard: AgentCard;
|
||||
|
||||
/**
|
||||
* If set by the interceptor, stops execution, invokes "after"
|
||||
* for executed interceptors and returns the result. Transport is not called.
|
||||
*/
|
||||
earlyReturn?: ClientCallResult<K>;
|
||||
|
||||
/**
|
||||
* Options passed to the client.
|
||||
*/
|
||||
options?: RequestOptions;
|
||||
}
|
||||
|
||||
export interface AfterArgs<K extends keyof Client = keyof Client> {
|
||||
/**
|
||||
* Identifies the client method invoked and its result.
|
||||
* Payload inside the result object can be modified.
|
||||
*/
|
||||
readonly result: ClientCallResult<K>;
|
||||
|
||||
/**
|
||||
* Identifies the agent card cached on the client
|
||||
*/
|
||||
readonly agentCard: AgentCard;
|
||||
|
||||
/**
|
||||
* If set by the interceptor, stops execution and returns result value,
|
||||
* remaining interceptors are not executed.
|
||||
*/
|
||||
earlyReturn?: boolean;
|
||||
|
||||
/**
|
||||
* Options passed to the client.
|
||||
*/
|
||||
options?: RequestOptions;
|
||||
}
|
||||
|
||||
export type ClientCallInput<K extends keyof Client = keyof Client> = MethodInput<Client, K>;
|
||||
export type ClientCallResult<K extends keyof Client = keyof Client> = MethodResult<
|
||||
Client,
|
||||
K,
|
||||
ResultsOverrides
|
||||
>;
|
||||
|
||||
// Types below are helper types and are not exported to allow simplifying it without affecting
|
||||
// public API if necessary. They are exported via type aliases ClientXxx which can be replaced with explicit union if necessary.
|
||||
|
||||
/**
|
||||
* For
|
||||
*
|
||||
* interface Foo {
|
||||
* f1(arg: string): Promise<Result1>;
|
||||
* f2(arg: number): Promise<Result2>;
|
||||
* }
|
||||
*
|
||||
* MethodInputs<Foo> resolves to
|
||||
*
|
||||
* {
|
||||
* readonly method: "f1";
|
||||
* value: string;
|
||||
* } | {
|
||||
* readonly method: "f2";
|
||||
* value: number;
|
||||
* }
|
||||
*/
|
||||
type MethodInput<T, TMembers extends keyof T = keyof T> = {
|
||||
[M in TMembers]: T[M] extends (options: RequestOptions | undefined) => unknown
|
||||
? { readonly method: M; value?: never }
|
||||
: T[M] extends (payload: infer P) => unknown
|
||||
? { readonly method: M; value: P }
|
||||
: never;
|
||||
}[TMembers];
|
||||
|
||||
/**
|
||||
* For
|
||||
*
|
||||
* interface Foo {
|
||||
* f1(): Promise<Result1>;
|
||||
* f2(): Promise<Result2>;
|
||||
* }
|
||||
*
|
||||
* MethodsResults<Foo> resolves to
|
||||
*
|
||||
* {
|
||||
* readonly method: "f1";
|
||||
* value: Result1;
|
||||
* } | {
|
||||
* readonly method: "f2";
|
||||
* value: Result2;
|
||||
* }
|
||||
*/
|
||||
type MethodResult<T, TMembers extends keyof T = keyof T, TOverrides = object> = {
|
||||
[M in TMembers]: M extends keyof TOverrides // If there is an override, use it directly.
|
||||
? { readonly method: M; value: TOverrides[M] }
|
||||
: // Infer result, unwrap it from Promise and pack with method name.
|
||||
T[M] extends (payload: unknown) => infer R
|
||||
? { readonly method: M; value: Awaited<R> }
|
||||
: never;
|
||||
}[TMembers];
|
||||
|
||||
interface ResultsOverrides {
|
||||
// sendMessageStream and resubscribeTask return async iterators and are intercepted on each item,
|
||||
// which requires custom handling.
|
||||
sendMessageStream: A2AStreamEventData;
|
||||
resubscribeTask: A2AStreamEventData;
|
||||
}
|
||||
393
aitimemachine/a2a/src/client/multitransport-client.ts
Normal file
393
aitimemachine/a2a/src/client/multitransport-client.ts
Normal file
@ -0,0 +1,393 @@
|
||||
import { PushNotificationNotSupportedError } from '../errors.js';
|
||||
import {
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
Task,
|
||||
TaskIdParams,
|
||||
TaskQueryParams,
|
||||
PushNotificationConfig,
|
||||
AgentCard,
|
||||
} from '../types.js';
|
||||
import { A2AStreamEventData, SendMessageResult } from './client.js';
|
||||
import { ClientCallContext } from './context.js';
|
||||
import {
|
||||
CallInterceptor,
|
||||
BeforeArgs,
|
||||
AfterArgs,
|
||||
ClientCallResult,
|
||||
ClientCallInput,
|
||||
} from './interceptors.js';
|
||||
import { ServiceParameters } from './service-parameters.js';
|
||||
import { Transport } from './transports/transport.js';
|
||||
|
||||
export interface ClientConfig {
|
||||
/**
|
||||
* Whether client prefers to poll for task updates instead of blocking until a terminal state is reached.
|
||||
* If set to true, non-streaming send message result might be a Message or a Task in any (including non-terminal) state.
|
||||
* Callers are responsible for running the polling loop. This configuration does not apply to streaming requests.
|
||||
*/
|
||||
polling?: boolean;
|
||||
|
||||
/**
|
||||
* Specifies the default list of accepted media types to apply for all "send message" calls.
|
||||
*/
|
||||
acceptedOutputModes?: string[];
|
||||
|
||||
/**
|
||||
* Specifies the default push notification configuration to apply for every Task.
|
||||
*/
|
||||
pushNotificationConfig?: PushNotificationConfig;
|
||||
|
||||
/**
|
||||
* Interceptors invoked for each request.
|
||||
*/
|
||||
interceptors?: CallInterceptor[];
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
/**
|
||||
* Signal to abort request execution.
|
||||
*/
|
||||
signal?: AbortSignal;
|
||||
|
||||
/**
|
||||
* A key-value map for passing horizontally applicable context or parameters.
|
||||
* All parameters are passed to the server via underlying transports (e.g. In JsonRPC via Headers).
|
||||
*/
|
||||
serviceParameters?: ServiceParameters;
|
||||
|
||||
/**
|
||||
* Arbitrary data available to interceptors and transport implementation.
|
||||
*/
|
||||
context?: ClientCallContext;
|
||||
}
|
||||
|
||||
export class Client {
|
||||
constructor(
|
||||
public readonly transport: Transport,
|
||||
private agentCard: AgentCard,
|
||||
public readonly config?: ClientConfig
|
||||
) {}
|
||||
|
||||
/**
|
||||
* If the current agent card supports the extended feature, it will try to fetch the extended agent card from the server,
|
||||
* Otherwise it will return the current agent card value.
|
||||
*/
|
||||
async getAgentCard(options?: RequestOptions): Promise<AgentCard> {
|
||||
if (this.agentCard.supportsAuthenticatedExtendedCard) {
|
||||
this.agentCard = await this.executeWithInterceptors(
|
||||
{ method: 'getAgentCard' },
|
||||
options,
|
||||
(_, options) => this.transport.getExtendedAgentCard(options)
|
||||
);
|
||||
}
|
||||
return this.agentCard;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to an agent to initiate a new interaction or to continue an existing one.
|
||||
* Uses blocking mode by default.
|
||||
*/
|
||||
sendMessage(params: MessageSendParams, options?: RequestOptions): Promise<SendMessageResult> {
|
||||
params = this.applyClientConfig({
|
||||
params,
|
||||
blocking: !(this.config?.polling ?? false),
|
||||
});
|
||||
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'sendMessage', value: params },
|
||||
options,
|
||||
this.transport.sendMessage.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to an agent to initiate/continue a task AND subscribes the client to real-time updates for that task.
|
||||
* Performs fallback to non-streaming if not supported by the agent.
|
||||
*/
|
||||
async *sendMessageStream(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const method = 'sendMessageStream';
|
||||
|
||||
params = this.applyClientConfig({ params, blocking: true });
|
||||
const beforeArgs: BeforeArgs<'sendMessageStream'> = {
|
||||
input: { method, value: params },
|
||||
agentCard: this.agentCard,
|
||||
options,
|
||||
};
|
||||
const beforeResult = await this.interceptBefore(beforeArgs);
|
||||
|
||||
if (beforeResult) {
|
||||
const earlyReturn = beforeResult.earlyReturn.value;
|
||||
const afterArgs: AfterArgs<'sendMessageStream'> = {
|
||||
result: { method, value: earlyReturn },
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs, beforeResult.executed);
|
||||
yield afterArgs.result.value;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.agentCard.capabilities.streaming) {
|
||||
const result = await this.transport.sendMessage(beforeArgs.input.value, beforeArgs.options);
|
||||
const afterArgs: AfterArgs<'sendMessageStream'> = {
|
||||
result: { method, value: result },
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs);
|
||||
yield afterArgs.result.value;
|
||||
return;
|
||||
}
|
||||
for await (const event of this.transport.sendMessageStream(
|
||||
beforeArgs.input.value,
|
||||
beforeArgs.options
|
||||
)) {
|
||||
const afterArgs: AfterArgs<'sendMessageStream'> = {
|
||||
result: { method, value: event },
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs);
|
||||
yield afterArgs.result.value;
|
||||
if (afterArgs.earlyReturn) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets or updates the push notification configuration for a specified task.
|
||||
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
||||
*/
|
||||
setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
}
|
||||
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'setTaskPushNotificationConfig', value: params },
|
||||
options,
|
||||
this.transport.setTaskPushNotificationConfig.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the current push notification configuration for a specified task.
|
||||
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
||||
*/
|
||||
getTaskPushNotificationConfig(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
}
|
||||
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'getTaskPushNotificationConfig', value: params },
|
||||
options,
|
||||
this.transport.getTaskPushNotificationConfig.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the associated push notification configurations for a specified task.
|
||||
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
||||
*/
|
||||
listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
if (!this.agentCard.capabilities.pushNotifications) {
|
||||
throw new PushNotificationNotSupportedError();
|
||||
}
|
||||
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'listTaskPushNotificationConfig', value: params },
|
||||
options,
|
||||
this.transport.listTaskPushNotificationConfig.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an associated push notification configuration for a task.
|
||||
*/
|
||||
deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<void> {
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'deleteTaskPushNotificationConfig', value: params },
|
||||
options,
|
||||
this.transport.deleteTaskPushNotificationConfig.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the current state (including status, artifacts, and optionally history) of a previously initiated task.
|
||||
*/
|
||||
getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task> {
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'getTask', value: params },
|
||||
options,
|
||||
this.transport.getTask.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the cancellation of an ongoing task. The server will attempt to cancel the task,
|
||||
* but success is not guaranteed (e.g., the task might have already completed or failed, or cancellation might not be supported at its current stage).
|
||||
*/
|
||||
cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task> {
|
||||
return this.executeWithInterceptors(
|
||||
{ method: 'cancelTask', value: params },
|
||||
options,
|
||||
this.transport.cancelTask.bind(this.transport)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows a client to reconnect to an updates stream for an ongoing task after a previous connection was interrupted.
|
||||
*/
|
||||
async *resubscribeTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const method = 'resubscribeTask';
|
||||
|
||||
const beforeArgs: BeforeArgs<'resubscribeTask'> = {
|
||||
input: { method, value: params },
|
||||
agentCard: this.agentCard,
|
||||
options,
|
||||
};
|
||||
const beforeResult = await this.interceptBefore(beforeArgs);
|
||||
|
||||
if (beforeResult) {
|
||||
const earlyReturn = beforeResult.earlyReturn.value;
|
||||
const afterArgs: AfterArgs<'resubscribeTask'> = {
|
||||
result: { method, value: earlyReturn },
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs, beforeResult.executed);
|
||||
yield afterArgs.result.value;
|
||||
return;
|
||||
}
|
||||
|
||||
for await (const event of this.transport.resubscribeTask(
|
||||
beforeArgs.input.value,
|
||||
beforeArgs.options
|
||||
)) {
|
||||
const afterArgs: AfterArgs<'resubscribeTask'> = {
|
||||
result: { method, value: event },
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs);
|
||||
yield afterArgs.result.value;
|
||||
if (afterArgs.earlyReturn) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private applyClientConfig({
|
||||
params,
|
||||
blocking,
|
||||
}: {
|
||||
params: MessageSendParams;
|
||||
blocking: boolean;
|
||||
}): MessageSendParams {
|
||||
const result = { ...params, configuration: params.configuration ?? {} };
|
||||
|
||||
if (!result.configuration.acceptedOutputModes && this.config?.acceptedOutputModes) {
|
||||
result.configuration.acceptedOutputModes = this.config.acceptedOutputModes;
|
||||
}
|
||||
if (!result.configuration.pushNotificationConfig && this.config?.pushNotificationConfig) {
|
||||
result.configuration.pushNotificationConfig = this.config.pushNotificationConfig;
|
||||
}
|
||||
result.configuration.blocking ??= blocking;
|
||||
return result;
|
||||
}
|
||||
|
||||
private async executeWithInterceptors<K extends keyof Client>(
|
||||
input: ClientCallInput<K>,
|
||||
options: RequestOptions | undefined,
|
||||
transportCall: (
|
||||
params: ClientCallInput<K>['value'],
|
||||
options?: RequestOptions
|
||||
) => Promise<ClientCallResult<K>['value']>
|
||||
): Promise<ClientCallResult<K>['value']> {
|
||||
const beforeArgs: BeforeArgs<K> = {
|
||||
input: input,
|
||||
agentCard: this.agentCard,
|
||||
options,
|
||||
};
|
||||
const beforeResult = await this.interceptBefore(beforeArgs);
|
||||
|
||||
if (beforeResult) {
|
||||
const afterArgs: AfterArgs<K> = {
|
||||
result: {
|
||||
method: input.method,
|
||||
value: beforeResult.earlyReturn.value,
|
||||
} as ClientCallResult<K>,
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs, beforeResult.executed);
|
||||
return afterArgs.result.value;
|
||||
}
|
||||
|
||||
const result = await transportCall(beforeArgs.input.value, beforeArgs.options);
|
||||
|
||||
const afterArgs: AfterArgs<K> = {
|
||||
result: { method: input.method, value: result } as ClientCallResult<K>,
|
||||
agentCard: this.agentCard,
|
||||
options: beforeArgs.options,
|
||||
};
|
||||
await this.interceptAfter(afterArgs);
|
||||
|
||||
return afterArgs.result.value;
|
||||
}
|
||||
|
||||
private async interceptBefore<K extends keyof Client>(
|
||||
args: BeforeArgs<K>
|
||||
): Promise<{ earlyReturn: ClientCallResult<K>; executed: CallInterceptor[] } | undefined> {
|
||||
if (!this.config?.interceptors || this.config.interceptors.length === 0) {
|
||||
return;
|
||||
}
|
||||
const executed: CallInterceptor[] = [];
|
||||
for (const interceptor of this.config.interceptors) {
|
||||
await interceptor.before(args);
|
||||
executed.push(interceptor);
|
||||
if (args.earlyReturn) {
|
||||
return {
|
||||
earlyReturn: args.earlyReturn,
|
||||
executed,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async interceptAfter<K extends keyof Client>(
|
||||
args: AfterArgs<K>,
|
||||
interceptors?: CallInterceptor[]
|
||||
): Promise<void> {
|
||||
const reversedInterceptors = [...(interceptors ?? this.config?.interceptors ?? [])].reverse();
|
||||
for (const interceptor of reversedInterceptors) {
|
||||
await interceptor.after(args);
|
||||
if (args.earlyReturn) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
29
aitimemachine/a2a/src/client/service-parameters.ts
Normal file
29
aitimemachine/a2a/src/client/service-parameters.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { HTTP_EXTENSION_HEADER } from '../constants.js';
|
||||
import { Extensions } from '../extensions.js';
|
||||
|
||||
export type ServiceParameters = Record<string, string>;
|
||||
|
||||
export type ServiceParametersUpdate = (parameters: ServiceParameters) => void;
|
||||
|
||||
export const ServiceParameters = {
|
||||
create(...updates: ServiceParametersUpdate[]): ServiceParameters {
|
||||
return ServiceParameters.createFrom(undefined, ...updates);
|
||||
},
|
||||
|
||||
createFrom: (
|
||||
serviceParameters: ServiceParameters | undefined,
|
||||
...updates: ServiceParametersUpdate[]
|
||||
): ServiceParameters => {
|
||||
const result = serviceParameters ? { ...serviceParameters } : {};
|
||||
for (const update of updates) {
|
||||
update(result);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
|
||||
export function withA2AExtensions(...extensions: Extensions): ServiceParametersUpdate {
|
||||
return (parameters: ServiceParameters) => {
|
||||
parameters[HTTP_EXTENSION_HEADER] = Extensions.toServiceParameter(extensions);
|
||||
};
|
||||
}
|
||||
349
aitimemachine/a2a/src/client/transports/grpc/grpc_transport.ts
Normal file
349
aitimemachine/a2a/src/client/transports/grpc/grpc_transport.ts
Normal file
@ -0,0 +1,349 @@
|
||||
import * as grpc from '@grpc/grpc-js';
|
||||
import { TransportProtocolName } from '../../../core.js';
|
||||
import { A2AServiceClient } from '../../../grpc/pb/a2a_services.js';
|
||||
import {
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
TaskIdParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
TaskQueryParams,
|
||||
Task,
|
||||
AgentCard,
|
||||
GetTaskPushNotificationConfigParams,
|
||||
} from '../../../types.js';
|
||||
import { A2AStreamEventData, SendMessageResult } from '../../client.js';
|
||||
import { RequestOptions } from '../../multitransport-client.js';
|
||||
import { Transport, TransportFactory } from '../transport.js';
|
||||
import { ToProto } from '../../../types/converters/to_proto.js';
|
||||
import { FromProto } from '../../../types/converters/from_proto.js';
|
||||
|
||||
import {
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
PushNotificationNotSupportedError,
|
||||
TaskNotFoundError,
|
||||
TaskNotCancelableError,
|
||||
UnsupportedOperationError,
|
||||
} from '../../../errors.js';
|
||||
|
||||
type GrpcUnaryCall<TReq, TRes> = (
|
||||
request: TReq,
|
||||
metadata: grpc.Metadata,
|
||||
options: Partial<grpc.CallOptions>,
|
||||
callback: (error: grpc.ServiceError | null, response: TRes) => void
|
||||
) => grpc.ClientUnaryCall;
|
||||
|
||||
type GrpcStreamCall<TReq, TRes> = (
|
||||
request: TReq,
|
||||
metadata?: grpc.Metadata,
|
||||
options?: Partial<grpc.CallOptions>
|
||||
) => grpc.ClientReadableStream<TRes>;
|
||||
|
||||
export interface GrpcTransportOptions {
|
||||
endpoint: string;
|
||||
grpcChannelCredentials?: grpc.ChannelCredentials;
|
||||
grpcCallOptions?: Partial<grpc.CallOptions>;
|
||||
}
|
||||
|
||||
export class GrpcTransport implements Transport {
|
||||
private readonly grpcCallOptions?: Partial<grpc.CallOptions>;
|
||||
private readonly grpcClient: A2AServiceClient;
|
||||
|
||||
constructor(options: GrpcTransportOptions) {
|
||||
this.grpcCallOptions = options.grpcCallOptions;
|
||||
this.grpcClient = new A2AServiceClient(
|
||||
options.endpoint,
|
||||
options.grpcChannelCredentials ?? grpc.credentials.createInsecure()
|
||||
);
|
||||
}
|
||||
|
||||
async getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'getAgentCard',
|
||||
undefined,
|
||||
options,
|
||||
this.grpcClient.getAgentCard.bind(this.grpcClient),
|
||||
ToProto.getAgentCardRequest,
|
||||
FromProto.agentCard
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): Promise<SendMessageResult> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'sendMessage',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.sendMessage.bind(this.grpcClient),
|
||||
ToProto.messageSendParams,
|
||||
FromProto.sendMessageResult
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async *sendMessageStream(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendGrpcStreamingRequest(
|
||||
'sendStreamingMessage',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.sendStreamingMessage.bind(this.grpcClient),
|
||||
ToProto.messageSendParams
|
||||
);
|
||||
}
|
||||
|
||||
async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'createTaskPushNotificationConfig',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.createTaskPushNotificationConfig.bind(this.grpcClient),
|
||||
ToProto.taskPushNotificationConfigCreate,
|
||||
FromProto.taskPushNotificationConfig
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'getTaskPushNotificationConfig',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.getTaskPushNotificationConfig.bind(this.grpcClient),
|
||||
ToProto.getTaskPushNotificationConfigParams,
|
||||
FromProto.taskPushNotificationConfig
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'listTaskPushNotificationConfig',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.listTaskPushNotificationConfig.bind(this.grpcClient),
|
||||
ToProto.listTaskPushNotificationConfigParams,
|
||||
FromProto.listTaskPushNotificationConfig
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<void> {
|
||||
await this._sendGrpcRequest(
|
||||
'deleteTaskPushNotificationConfig',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.deleteTaskPushNotificationConfig.bind(this.grpcClient),
|
||||
ToProto.deleteTaskPushNotificationConfigParams,
|
||||
() => {}
|
||||
);
|
||||
}
|
||||
|
||||
async getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'getTask',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.getTask.bind(this.grpcClient),
|
||||
ToProto.taskQueryParams,
|
||||
FromProto.task
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task> {
|
||||
const rpcResponse = await this._sendGrpcRequest(
|
||||
'cancelTask',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.cancelTask.bind(this.grpcClient),
|
||||
ToProto.cancelTaskRequest,
|
||||
FromProto.task
|
||||
);
|
||||
return rpcResponse;
|
||||
}
|
||||
|
||||
async *resubscribeTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendGrpcStreamingRequest(
|
||||
'taskSubscription',
|
||||
params,
|
||||
options,
|
||||
this.grpcClient.taskSubscription.bind(this.grpcClient),
|
||||
ToProto.taskIdParams
|
||||
);
|
||||
}
|
||||
|
||||
private async _sendGrpcRequest<TReq, TRes, TParams, TResponse>(
|
||||
method: keyof A2AServiceClient,
|
||||
params: TParams,
|
||||
options: RequestOptions | undefined,
|
||||
call: GrpcUnaryCall<TReq, TRes>,
|
||||
parser: (req: TParams) => TReq,
|
||||
converter: (res: TRes) => TResponse
|
||||
): Promise<TResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let onAbort: (() => void) | undefined;
|
||||
|
||||
const clientCall = call(
|
||||
parser(params),
|
||||
this._buildMetadata(options),
|
||||
this.grpcCallOptions ?? {},
|
||||
(error, response) => {
|
||||
if (options?.signal && onAbort) {
|
||||
options.signal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
if (error) {
|
||||
return reject(GrpcTransport.mapToError(error, method));
|
||||
}
|
||||
resolve(converter(response));
|
||||
}
|
||||
);
|
||||
|
||||
if (options?.signal) {
|
||||
if (options.signal.aborted) {
|
||||
clientCall.cancel();
|
||||
} else {
|
||||
onAbort = () => clientCall.cancel();
|
||||
options.signal.addEventListener('abort', onAbort);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async *_sendGrpcStreamingRequest<TReq, TRes, TParams>(
|
||||
method: 'sendStreamingMessage' | 'taskSubscription',
|
||||
params: TParams,
|
||||
options: RequestOptions | undefined,
|
||||
call: GrpcStreamCall<TReq, TRes>,
|
||||
parser: (req: TParams) => TReq
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const streamResponse = call(
|
||||
parser(params),
|
||||
this._buildMetadata(options),
|
||||
this.grpcCallOptions ?? {}
|
||||
);
|
||||
|
||||
let onAbort: (() => void) | undefined;
|
||||
if (options?.signal) {
|
||||
if (options.signal.aborted) {
|
||||
streamResponse.cancel();
|
||||
} else {
|
||||
onAbort = () => streamResponse.cancel();
|
||||
options.signal.addEventListener('abort', onAbort);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for await (const response of streamResponse) {
|
||||
yield FromProto.messageStreamResult(response);
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.isServiceError(error)) {
|
||||
throw GrpcTransport.mapToError(error, method);
|
||||
} else {
|
||||
throw new Error(`GRPC error for ${String(method)}!`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
if (options?.signal && onAbort) {
|
||||
options.signal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
streamResponse.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
private isServiceError(error: unknown): error is grpc.ServiceError {
|
||||
return typeof error === 'object' && error !== null && 'code' in error;
|
||||
}
|
||||
|
||||
private _buildMetadata(options: RequestOptions | undefined): grpc.Metadata {
|
||||
const metadata = new grpc.Metadata();
|
||||
if (options?.serviceParameters) {
|
||||
for (const [key, value] of Object.entries(options.serviceParameters)) {
|
||||
metadata.set(key, value);
|
||||
}
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
|
||||
// TODO: the logic of mapToError will be removed in v1.0.0 with the enriched error model (https://a2a-protocol.org/latest/specification/#106-error-handling)
|
||||
private static mapToError(error: grpc.ServiceError, method: keyof A2AServiceClient): Error {
|
||||
switch (error.code) {
|
||||
case grpc.status.NOT_FOUND:
|
||||
return new TaskNotFoundError(error.details);
|
||||
case grpc.status.FAILED_PRECONDITION:
|
||||
if (method === 'cancelTask') {
|
||||
return new TaskNotCancelableError(error.details);
|
||||
}
|
||||
if (method === 'getAgentCard') {
|
||||
return new AuthenticatedExtendedCardNotConfiguredError(error.details);
|
||||
}
|
||||
break;
|
||||
case grpc.status.UNIMPLEMENTED:
|
||||
if (
|
||||
[
|
||||
'getTaskPushNotificationConfig',
|
||||
'createTaskPushNotificationConfig',
|
||||
'deleteTaskPushNotificationConfig',
|
||||
'listTaskPushNotificationConfig',
|
||||
].includes(method)
|
||||
) {
|
||||
return new PushNotificationNotSupportedError(error.details);
|
||||
}
|
||||
if (['getAgentCard', 'taskSubscription'].includes(method)) {
|
||||
return new UnsupportedOperationError(error.details);
|
||||
}
|
||||
break;
|
||||
//TODO: add case for grpc.status.INVALID_ARGUMENT and grpc.status.INTERNAL (the respective a2a errors are not implemented yet)
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return new Error(`GRPC error for ${String(method)}! ${error.code} ${error.details}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class GrpcTransportFactoryOptions {
|
||||
grpcChannelCredentials?: grpc.ChannelCredentials;
|
||||
grpcCallOptions?: Partial<grpc.CallOptions>;
|
||||
}
|
||||
|
||||
export class GrpcTransportFactory implements TransportFactory {
|
||||
public static readonly name: TransportProtocolName = 'GRPC';
|
||||
|
||||
constructor(private readonly options?: GrpcTransportFactoryOptions) {}
|
||||
|
||||
get protocolName(): string {
|
||||
return GrpcTransportFactory.name;
|
||||
}
|
||||
|
||||
async create(url: string, _agentCard: AgentCard): Promise<Transport> {
|
||||
return new GrpcTransport({
|
||||
endpoint: url,
|
||||
grpcChannelCredentials: this.options?.grpcChannelCredentials,
|
||||
grpcCallOptions: this.options?.grpcCallOptions,
|
||||
});
|
||||
}
|
||||
}
|
||||
5
aitimemachine/a2a/src/client/transports/grpc/index.ts
Normal file
5
aitimemachine/a2a/src/client/transports/grpc/index.ts
Normal file
@ -0,0 +1,5 @@
|
||||
export {
|
||||
GrpcTransport,
|
||||
GrpcTransportFactory,
|
||||
type GrpcTransportOptions,
|
||||
} from './grpc_transport.js';
|
||||
445
aitimemachine/a2a/src/client/transports/json_rpc_transport.ts
Normal file
445
aitimemachine/a2a/src/client/transports/json_rpc_transport.ts
Normal file
@ -0,0 +1,445 @@
|
||||
import { TransportProtocolName } from '../../core.js';
|
||||
import {
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
ContentTypeNotSupportedError,
|
||||
InvalidAgentResponseError,
|
||||
PushNotificationNotSupportedError,
|
||||
TaskNotCancelableError,
|
||||
TaskNotFoundError,
|
||||
UnsupportedOperationError,
|
||||
} from '../../errors.js';
|
||||
import {
|
||||
JSONRPCRequest,
|
||||
JSONRPCResponse,
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
TaskIdParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigResponse,
|
||||
TaskQueryParams,
|
||||
Task,
|
||||
JSONRPCErrorResponse,
|
||||
SendMessageSuccessResponse,
|
||||
SetTaskPushNotificationConfigSuccessResponse,
|
||||
GetTaskPushNotificationConfigSuccessResponse,
|
||||
ListTaskPushNotificationConfigSuccessResponse,
|
||||
GetTaskSuccessResponse,
|
||||
CancelTaskSuccessResponse,
|
||||
AgentCard,
|
||||
GetTaskPushNotificationConfigParams,
|
||||
GetAuthenticatedExtendedCardSuccessResponse,
|
||||
} from '../../types.js';
|
||||
import { A2AStreamEventData, SendMessageResult } from '../client.js';
|
||||
import { RequestOptions } from '../multitransport-client.js';
|
||||
import { parseSseStream } from '../../sse_utils.js';
|
||||
import { Transport, TransportFactory } from './transport.js';
|
||||
|
||||
export interface JsonRpcTransportOptions {
|
||||
endpoint: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
export class JsonRpcTransport implements Transport {
|
||||
private readonly customFetchImpl?: typeof fetch;
|
||||
private readonly endpoint: string;
|
||||
private requestIdCounter: number = 1;
|
||||
|
||||
constructor(options: JsonRpcTransportOptions) {
|
||||
this.endpoint = options.endpoint;
|
||||
this.customFetchImpl = options.fetchImpl;
|
||||
}
|
||||
|
||||
async getExtendedAgentCard(options?: RequestOptions, idOverride?: number): Promise<AgentCard> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
undefined,
|
||||
GetAuthenticatedExtendedCardSuccessResponse
|
||||
>('agent/getAuthenticatedExtendedCard', undefined, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<SendMessageResult> {
|
||||
const rpcResponse = await this._sendRpcRequest<MessageSendParams, SendMessageSuccessResponse>(
|
||||
'message/send',
|
||||
params,
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async *sendMessageStream(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendStreamingRequest('message/stream', params, options);
|
||||
}
|
||||
|
||||
async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
TaskPushNotificationConfig,
|
||||
SetTaskPushNotificationConfigSuccessResponse
|
||||
>('tasks/pushNotificationConfig/set', params, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
GetTaskPushNotificationConfigParams,
|
||||
GetTaskPushNotificationConfigSuccessResponse
|
||||
>('tasks/pushNotificationConfig/get', params, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
const rpcResponse = await this._sendRpcRequest<
|
||||
ListTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigSuccessResponse
|
||||
>('tasks/pushNotificationConfig/list', params, idOverride, options);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<void> {
|
||||
await this._sendRpcRequest<
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigResponse
|
||||
>('tasks/pushNotificationConfig/delete', params, idOverride, options);
|
||||
}
|
||||
|
||||
async getTask(
|
||||
params: TaskQueryParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<Task> {
|
||||
const rpcResponse = await this._sendRpcRequest<TaskQueryParams, GetTaskSuccessResponse>(
|
||||
'tasks/get',
|
||||
params,
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async cancelTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions,
|
||||
idOverride?: number
|
||||
): Promise<Task> {
|
||||
const rpcResponse = await this._sendRpcRequest<TaskIdParams, CancelTaskSuccessResponse>(
|
||||
'tasks/cancel',
|
||||
params,
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
return rpcResponse.result;
|
||||
}
|
||||
|
||||
async *resubscribeTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendStreamingRequest('tasks/resubscribe', params, options);
|
||||
}
|
||||
|
||||
async callExtensionMethod<TExtensionParams, TExtensionResponse extends JSONRPCResponse>(
|
||||
method: string,
|
||||
params: TExtensionParams,
|
||||
idOverride: number,
|
||||
options?: RequestOptions
|
||||
) {
|
||||
return await this._sendRpcRequest<TExtensionParams, TExtensionResponse>(
|
||||
method,
|
||||
params,
|
||||
idOverride,
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
private _fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
|
||||
if (this.customFetchImpl) {
|
||||
return this.customFetchImpl(...args);
|
||||
}
|
||||
if (typeof fetch === 'function') {
|
||||
return fetch(...args);
|
||||
}
|
||||
throw new Error(
|
||||
'A `fetch` implementation was not provided and is not available in the global scope. ' +
|
||||
'Please provide a `fetchImpl` in the A2ATransportOptions. '
|
||||
);
|
||||
}
|
||||
|
||||
private async _sendRpcRequest<
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
TParams extends { [key: string]: any },
|
||||
TResponse extends JSONRPCResponse,
|
||||
>(
|
||||
method: string,
|
||||
params: TParams,
|
||||
idOverride: number | undefined,
|
||||
options: RequestOptions | undefined
|
||||
): Promise<TResponse> {
|
||||
const requestId = idOverride ?? this.requestIdCounter++;
|
||||
|
||||
const rpcRequest: JSONRPCRequest = {
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params: params,
|
||||
id: requestId,
|
||||
};
|
||||
|
||||
const httpResponse = await this._fetchRpc(rpcRequest, 'application/json', options);
|
||||
|
||||
if (!httpResponse.ok) {
|
||||
let errorBodyText = '(empty or non-JSON response)';
|
||||
let errorJson: JSONRPCErrorResponse;
|
||||
try {
|
||||
errorBodyText = await httpResponse.text();
|
||||
errorJson = JSON.parse(errorBodyText);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,
|
||||
{ cause: e }
|
||||
);
|
||||
}
|
||||
if (errorJson.jsonrpc && errorJson.error) {
|
||||
throw JsonRpcTransport.mapToError(errorJson);
|
||||
} else {
|
||||
throw new Error(
|
||||
`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const rpcResponse: JSONRPCResponse = await httpResponse.json();
|
||||
if (rpcResponse.id !== requestId) {
|
||||
throw new Error(
|
||||
`JSON-RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}.`
|
||||
);
|
||||
}
|
||||
|
||||
if ('error' in rpcResponse) {
|
||||
throw JsonRpcTransport.mapToError(rpcResponse);
|
||||
}
|
||||
|
||||
return rpcResponse as TResponse;
|
||||
}
|
||||
|
||||
private async _fetchRpc(
|
||||
rpcRequest: JSONRPCRequest,
|
||||
acceptHeader: string = 'application/json',
|
||||
options?: RequestOptions
|
||||
): Promise<Response> {
|
||||
const requestInit: RequestInit = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...options?.serviceParameters,
|
||||
'Content-Type': 'application/json',
|
||||
Accept: acceptHeader,
|
||||
},
|
||||
body: JSON.stringify(rpcRequest),
|
||||
signal: options?.signal,
|
||||
};
|
||||
return this._fetch(this.endpoint, requestInit);
|
||||
}
|
||||
|
||||
private async *_sendStreamingRequest(
|
||||
method: string,
|
||||
params: unknown,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const clientRequestId = this.requestIdCounter++;
|
||||
const rpcRequest: JSONRPCRequest = {
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params: params as { [key: string]: unknown },
|
||||
id: clientRequestId,
|
||||
};
|
||||
|
||||
const response = await this._fetchRpc(rpcRequest, 'text/event-stream', options);
|
||||
|
||||
if (!response.ok) {
|
||||
let errorBody = '';
|
||||
let errorJson: JSONRPCErrorResponse;
|
||||
try {
|
||||
errorBody = await response.text();
|
||||
errorJson = JSON.parse(errorBody);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,
|
||||
{ cause: e }
|
||||
);
|
||||
}
|
||||
if (errorJson.error) {
|
||||
throw new Error(
|
||||
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`
|
||||
);
|
||||
}
|
||||
throw new Error(
|
||||
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}`
|
||||
);
|
||||
}
|
||||
if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {
|
||||
throw new Error(
|
||||
`Invalid response Content-Type for SSE stream for ${method}. Expected 'text/event-stream'.`
|
||||
);
|
||||
}
|
||||
|
||||
for await (const event of parseSseStream(response)) {
|
||||
yield this._processSseEventData<A2AStreamEventData>(event.data, clientRequestId);
|
||||
}
|
||||
}
|
||||
|
||||
private _processSseEventData<TStreamItem>(
|
||||
jsonData: string,
|
||||
originalRequestId: number | string | null
|
||||
): TStreamItem {
|
||||
if (!jsonData.trim()) {
|
||||
throw new Error('Attempted to process empty SSE event data.');
|
||||
}
|
||||
|
||||
let a2aStreamResponse: JSONRPCResponse;
|
||||
try {
|
||||
a2aStreamResponse = JSON.parse(jsonData) as JSONRPCResponse;
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${(e instanceof Error && e.message) || 'Unknown error'}`,
|
||||
{ cause: e }
|
||||
);
|
||||
}
|
||||
|
||||
if (a2aStreamResponse.id !== originalRequestId) {
|
||||
throw new Error(
|
||||
`JSON-RPC response ID mismatch in SSE event. Expected ${originalRequestId}, got ${a2aStreamResponse.id}.`
|
||||
);
|
||||
}
|
||||
|
||||
if ('error' in a2aStreamResponse) {
|
||||
const err = a2aStreamResponse.error;
|
||||
throw new Error(
|
||||
`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`,
|
||||
{ cause: JsonRpcTransport.mapToError(a2aStreamResponse) }
|
||||
);
|
||||
}
|
||||
|
||||
if (!('result' in a2aStreamResponse) || typeof a2aStreamResponse.result === 'undefined') {
|
||||
throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
|
||||
}
|
||||
|
||||
return a2aStreamResponse.result as TStreamItem;
|
||||
}
|
||||
|
||||
private static mapToError(response: JSONRPCErrorResponse): Error {
|
||||
switch (response.error.code) {
|
||||
case -32001:
|
||||
return new TaskNotFoundJSONRPCError(response);
|
||||
case -32002:
|
||||
return new TaskNotCancelableJSONRPCError(response);
|
||||
case -32003:
|
||||
return new PushNotificationNotSupportedJSONRPCError(response);
|
||||
case -32004:
|
||||
return new UnsupportedOperationJSONRPCError(response);
|
||||
case -32005:
|
||||
return new ContentTypeNotSupportedJSONRPCError(response);
|
||||
case -32006:
|
||||
return new InvalidAgentResponseJSONRPCError(response);
|
||||
case -32007:
|
||||
return new AuthenticatedExtendedCardNotConfiguredJSONRPCError(response);
|
||||
default:
|
||||
return new JSONRPCTransportError(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class JsonRpcTransportFactoryOptions {
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
export class JsonRpcTransportFactory implements TransportFactory {
|
||||
public static readonly name: TransportProtocolName = 'JSONRPC';
|
||||
|
||||
constructor(private readonly options?: JsonRpcTransportFactoryOptions) {}
|
||||
|
||||
get protocolName(): string {
|
||||
return JsonRpcTransportFactory.name;
|
||||
}
|
||||
|
||||
async create(url: string, _agentCard: AgentCard): Promise<Transport> {
|
||||
return new JsonRpcTransport({
|
||||
endpoint: url,
|
||||
fetchImpl: this.options?.fetchImpl,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class JSONRPCTransportError extends Error {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super(
|
||||
`JSON-RPC error: ${errorResponse.error.message} (Code: ${errorResponse.error.code}) Data: ${JSON.stringify(errorResponse.error.data || {})}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Redeclare domain errors with the original JSON-RPC response as a field to be compatible
|
||||
// with the legacy A2AClient built around JSON-RPC interface.
|
||||
|
||||
export class TaskNotFoundJSONRPCError extends TaskNotFoundError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class TaskNotCancelableJSONRPCError extends TaskNotCancelableError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class PushNotificationNotSupportedJSONRPCError extends PushNotificationNotSupportedError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class UnsupportedOperationJSONRPCError extends UnsupportedOperationError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class ContentTypeNotSupportedJSONRPCError extends ContentTypeNotSupportedError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class InvalidAgentResponseJSONRPCError extends InvalidAgentResponseError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
export class AuthenticatedExtendedCardNotConfiguredJSONRPCError extends AuthenticatedExtendedCardNotConfiguredError {
|
||||
constructor(public errorResponse: JSONRPCErrorResponse) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
383
aitimemachine/a2a/src/client/transports/rest_transport.ts
Normal file
383
aitimemachine/a2a/src/client/transports/rest_transport.ts
Normal file
@ -0,0 +1,383 @@
|
||||
import { TransportProtocolName } from '../../core.js';
|
||||
import {
|
||||
A2A_ERROR_CODE,
|
||||
AuthenticatedExtendedCardNotConfiguredError,
|
||||
ContentTypeNotSupportedError,
|
||||
InvalidAgentResponseError,
|
||||
PushNotificationNotSupportedError,
|
||||
TaskNotFoundError,
|
||||
TaskNotCancelableError,
|
||||
UnsupportedOperationError,
|
||||
} from '../../errors.js';
|
||||
import {
|
||||
AgentCard,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
GetTaskPushNotificationConfigParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
TaskIdParams,
|
||||
TaskQueryParams,
|
||||
Task,
|
||||
} from '../../types.js';
|
||||
import { A2AStreamEventData, SendMessageResult } from '../client.js';
|
||||
import { RequestOptions } from '../multitransport-client.js';
|
||||
import { parseSseStream } from '../../sse_utils.js';
|
||||
import { Transport, TransportFactory } from './transport.js';
|
||||
import { ToProto } from '../../types/converters/to_proto.js';
|
||||
import { FromProto } from '../../types/converters/from_proto.js';
|
||||
import * as a2a from '../../types/pb/a2a_types.js';
|
||||
|
||||
export interface RestTransportOptions {
|
||||
endpoint: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
interface RestErrorResponse {
|
||||
code: number;
|
||||
message: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export class RestTransport implements Transport {
|
||||
private readonly customFetchImpl?: typeof fetch;
|
||||
private readonly endpoint: string;
|
||||
|
||||
constructor(options: RestTransportOptions) {
|
||||
this.endpoint = options.endpoint.replace(/\/+$/, '');
|
||||
this.customFetchImpl = options.fetchImpl;
|
||||
}
|
||||
|
||||
async getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard> {
|
||||
const response = await this._sendRequest<undefined, a2a.AgentCard>(
|
||||
'GET',
|
||||
'/v1/card',
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
a2a.AgentCard
|
||||
);
|
||||
return FromProto.agentCard(response);
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): Promise<SendMessageResult> {
|
||||
const requestBody = ToProto.messageSendParams(params);
|
||||
const response = await this._sendRequest<a2a.SendMessageRequest, a2a.SendMessageResponse>(
|
||||
'POST',
|
||||
'/v1/message:send',
|
||||
requestBody,
|
||||
options,
|
||||
a2a.SendMessageRequest,
|
||||
a2a.SendMessageResponse
|
||||
);
|
||||
return FromProto.sendMessageResult(response);
|
||||
}
|
||||
|
||||
async *sendMessageStream(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const protoParams = ToProto.messageSendParams(params);
|
||||
const requestBody = a2a.SendMessageRequest.toJSON(protoParams);
|
||||
yield* this._sendStreamingRequest('/v1/message:stream', requestBody, options);
|
||||
}
|
||||
|
||||
async setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const requestBody = ToProto.taskPushNotificationConfig(params);
|
||||
const response = await this._sendRequest<
|
||||
a2a.TaskPushNotificationConfig,
|
||||
a2a.TaskPushNotificationConfig
|
||||
>(
|
||||
'POST',
|
||||
`/v1/tasks/${encodeURIComponent(params.taskId)}/pushNotificationConfigs`,
|
||||
requestBody,
|
||||
options,
|
||||
a2a.TaskPushNotificationConfig,
|
||||
a2a.TaskPushNotificationConfig
|
||||
);
|
||||
return FromProto.taskPushNotificationConfig(response);
|
||||
}
|
||||
|
||||
async getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig> {
|
||||
const { pushNotificationConfigId } = params;
|
||||
if (!pushNotificationConfigId) {
|
||||
throw new Error(
|
||||
'pushNotificationConfigId is required for getTaskPushNotificationConfig with REST transport.'
|
||||
);
|
||||
}
|
||||
const response = await this._sendRequest<undefined, a2a.TaskPushNotificationConfig>(
|
||||
'GET',
|
||||
`/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs/${encodeURIComponent(pushNotificationConfigId)}`,
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
a2a.TaskPushNotificationConfig
|
||||
);
|
||||
return FromProto.taskPushNotificationConfig(response);
|
||||
}
|
||||
|
||||
async listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig[]> {
|
||||
const response = await this._sendRequest<undefined, a2a.ListTaskPushNotificationConfigResponse>(
|
||||
'GET',
|
||||
`/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs`,
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
a2a.ListTaskPushNotificationConfigResponse
|
||||
);
|
||||
return FromProto.listTaskPushNotificationConfig(response);
|
||||
}
|
||||
|
||||
async deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<void> {
|
||||
await this._sendRequest<undefined, void>(
|
||||
'DELETE',
|
||||
`/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs/${encodeURIComponent(params.pushNotificationConfigId)}`,
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
}
|
||||
|
||||
async getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task> {
|
||||
const queryParams = new URLSearchParams();
|
||||
if (params.historyLength !== undefined) {
|
||||
queryParams.set('historyLength', String(params.historyLength));
|
||||
}
|
||||
const queryString = queryParams.toString();
|
||||
const path = `/v1/tasks/${encodeURIComponent(params.id)}${queryString ? `?${queryString}` : ''}`;
|
||||
const response = await this._sendRequest<undefined, a2a.Task>(
|
||||
'GET',
|
||||
path,
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
a2a.Task
|
||||
);
|
||||
return FromProto.task(response);
|
||||
}
|
||||
|
||||
async cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task> {
|
||||
const response = await this._sendRequest<undefined, a2a.Task>(
|
||||
'POST',
|
||||
`/v1/tasks/${encodeURIComponent(params.id)}:cancel`,
|
||||
undefined,
|
||||
options,
|
||||
undefined,
|
||||
a2a.Task
|
||||
);
|
||||
return FromProto.task(response);
|
||||
}
|
||||
|
||||
async *resubscribeTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
yield* this._sendStreamingRequest(
|
||||
`/v1/tasks/${encodeURIComponent(params.id)}:subscribe`,
|
||||
undefined,
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
private _fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
|
||||
if (this.customFetchImpl) {
|
||||
return this.customFetchImpl(...args);
|
||||
}
|
||||
if (typeof fetch === 'function') {
|
||||
return fetch(...args);
|
||||
}
|
||||
throw new Error(
|
||||
'A `fetch` implementation was not provided and is not available in the global scope. ' +
|
||||
'Please provide a `fetchImpl` in the RestTransportOptions.'
|
||||
);
|
||||
}
|
||||
|
||||
private _buildHeaders(
|
||||
options: RequestOptions | undefined,
|
||||
acceptHeader: string = 'application/json'
|
||||
): HeadersInit {
|
||||
return {
|
||||
...options?.serviceParameters,
|
||||
'Content-Type': 'application/json',
|
||||
Accept: acceptHeader,
|
||||
};
|
||||
}
|
||||
|
||||
private async _sendRequest<TRequest, TResponse>(
|
||||
method: 'GET' | 'POST' | 'DELETE',
|
||||
path: string,
|
||||
body: TRequest,
|
||||
options: RequestOptions | undefined,
|
||||
requestType: a2a.MessageFns<TRequest> | undefined,
|
||||
responseType: a2a.MessageFns<TResponse> | undefined
|
||||
): Promise<TResponse> {
|
||||
const url = `${this.endpoint}${path}`;
|
||||
const requestInit: RequestInit = {
|
||||
method,
|
||||
headers: this._buildHeaders(options),
|
||||
signal: options?.signal,
|
||||
};
|
||||
|
||||
if (body !== undefined && method !== 'GET') {
|
||||
if (!requestType) {
|
||||
throw new Error(
|
||||
`Bug: Request body provided for ${method} ${path} but no toJson serializer provided.`
|
||||
);
|
||||
}
|
||||
requestInit.body = JSON.stringify(requestType.toJSON(body));
|
||||
}
|
||||
|
||||
const response = await this._fetch(url, requestInit);
|
||||
|
||||
if (!response.ok) {
|
||||
await this._handleErrorResponse(response, path);
|
||||
}
|
||||
|
||||
if (response.status === 204 || !responseType) {
|
||||
return undefined as TResponse;
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
return responseType.fromJSON(result);
|
||||
}
|
||||
|
||||
private async _handleErrorResponse(response: Response, path: string): Promise<never> {
|
||||
let errorBodyText = '(empty or non-JSON response)';
|
||||
let errorBody: RestErrorResponse | undefined;
|
||||
|
||||
try {
|
||||
errorBodyText = await response.text();
|
||||
if (errorBodyText) {
|
||||
errorBody = JSON.parse(errorBodyText);
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`HTTP error for ${path}! Status: ${response.status} ${response.statusText}. Response: ${errorBodyText}`,
|
||||
{ cause: e }
|
||||
);
|
||||
}
|
||||
|
||||
if (errorBody && typeof errorBody.code === 'number') {
|
||||
throw RestTransport.mapToError(errorBody);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`HTTP error for ${path}! Status: ${response.status} ${response.statusText}. Response: ${errorBodyText}`
|
||||
);
|
||||
}
|
||||
|
||||
private async *_sendStreamingRequest(
|
||||
path: string,
|
||||
body: unknown | undefined,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined> {
|
||||
const url = `${this.endpoint}${path}`;
|
||||
const requestInit: RequestInit = {
|
||||
method: 'POST',
|
||||
headers: this._buildHeaders(options, 'text/event-stream'),
|
||||
signal: options?.signal,
|
||||
};
|
||||
|
||||
if (body !== undefined) {
|
||||
requestInit.body = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const response = await this._fetch(url, requestInit);
|
||||
|
||||
if (!response.ok) {
|
||||
await this._handleErrorResponse(response, path);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('Content-Type');
|
||||
if (!contentType?.startsWith('text/event-stream')) {
|
||||
throw new Error(
|
||||
`Invalid response Content-Type for SSE stream. Expected 'text/event-stream', got '${contentType}'.`
|
||||
);
|
||||
}
|
||||
|
||||
for await (const event of parseSseStream(response)) {
|
||||
if (event.type === 'error') {
|
||||
const errorData = JSON.parse(event.data);
|
||||
throw RestTransport.mapToError(errorData);
|
||||
}
|
||||
yield this._processSseEventData(event.data);
|
||||
}
|
||||
}
|
||||
|
||||
private _processSseEventData(jsonData: string): A2AStreamEventData {
|
||||
if (!jsonData.trim()) {
|
||||
throw new Error('Attempted to process empty SSE event data.');
|
||||
}
|
||||
|
||||
try {
|
||||
const response = JSON.parse(jsonData);
|
||||
const protoResponse = a2a.StreamResponse.fromJSON(response);
|
||||
return FromProto.messageStreamResult(protoResponse);
|
||||
} catch (e) {
|
||||
console.error('Failed to parse SSE event data:', jsonData, e);
|
||||
throw new Error(
|
||||
`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${(e instanceof Error && e.message) || 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static mapToError(error: RestErrorResponse): Error {
|
||||
switch (error.code) {
|
||||
case A2A_ERROR_CODE.TASK_NOT_FOUND:
|
||||
return new TaskNotFoundError(error.message);
|
||||
case A2A_ERROR_CODE.TASK_NOT_CANCELABLE:
|
||||
return new TaskNotCancelableError(error.message);
|
||||
case A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED:
|
||||
return new PushNotificationNotSupportedError(error.message);
|
||||
case A2A_ERROR_CODE.UNSUPPORTED_OPERATION:
|
||||
return new UnsupportedOperationError(error.message);
|
||||
case A2A_ERROR_CODE.CONTENT_TYPE_NOT_SUPPORTED:
|
||||
return new ContentTypeNotSupportedError(error.message);
|
||||
case A2A_ERROR_CODE.INVALID_AGENT_RESPONSE:
|
||||
return new InvalidAgentResponseError(error.message);
|
||||
case A2A_ERROR_CODE.AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED:
|
||||
return new AuthenticatedExtendedCardNotConfiguredError(error.message);
|
||||
default:
|
||||
return new Error(
|
||||
`REST error: ${error.message} (Code: ${error.code})${error.data ? ` Data: ${JSON.stringify(error.data)}` : ''}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface RestTransportFactoryOptions {
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
export class RestTransportFactory implements TransportFactory {
|
||||
public static readonly name: TransportProtocolName = 'HTTP+JSON';
|
||||
|
||||
constructor(private readonly options?: RestTransportFactoryOptions) {}
|
||||
|
||||
get protocolName(): string {
|
||||
return RestTransportFactory.name;
|
||||
}
|
||||
|
||||
async create(url: string, _agentCard: AgentCard): Promise<Transport> {
|
||||
return new RestTransport({
|
||||
endpoint: url,
|
||||
fetchImpl: this.options?.fetchImpl,
|
||||
});
|
||||
}
|
||||
}
|
||||
59
aitimemachine/a2a/src/client/transports/transport.ts
Normal file
59
aitimemachine/a2a/src/client/transports/transport.ts
Normal file
@ -0,0 +1,59 @@
|
||||
import {
|
||||
MessageSendParams,
|
||||
TaskPushNotificationConfig,
|
||||
TaskIdParams,
|
||||
ListTaskPushNotificationConfigParams,
|
||||
DeleteTaskPushNotificationConfigParams,
|
||||
TaskQueryParams,
|
||||
Task,
|
||||
AgentCard,
|
||||
GetTaskPushNotificationConfigParams,
|
||||
} from '../../types.js';
|
||||
import { A2AStreamEventData, SendMessageResult } from '../client.js';
|
||||
import { RequestOptions } from '../multitransport-client.js';
|
||||
|
||||
export interface Transport {
|
||||
getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard>;
|
||||
|
||||
sendMessage(params: MessageSendParams, options?: RequestOptions): Promise<SendMessageResult>;
|
||||
|
||||
sendMessageStream(
|
||||
params: MessageSendParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined>;
|
||||
|
||||
setTaskPushNotificationConfig(
|
||||
params: TaskPushNotificationConfig,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
|
||||
getTaskPushNotificationConfig(
|
||||
params: GetTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig>;
|
||||
|
||||
listTaskPushNotificationConfig(
|
||||
params: ListTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<TaskPushNotificationConfig[]>;
|
||||
|
||||
deleteTaskPushNotificationConfig(
|
||||
params: DeleteTaskPushNotificationConfigParams,
|
||||
options?: RequestOptions
|
||||
): Promise<void>;
|
||||
|
||||
getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task>;
|
||||
|
||||
cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task>;
|
||||
|
||||
resubscribeTask(
|
||||
params: TaskIdParams,
|
||||
options?: RequestOptions
|
||||
): AsyncGenerator<A2AStreamEventData, void, undefined>;
|
||||
}
|
||||
|
||||
export interface TransportFactory {
|
||||
get protocolName(): string;
|
||||
|
||||
create(url: string, agentCard: AgentCard): Promise<Transport>;
|
||||
}
|
||||
13
aitimemachine/a2a/src/constants.ts
Normal file
13
aitimemachine/a2a/src/constants.ts
Normal file
@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Shared constants for the A2A library
|
||||
*/
|
||||
|
||||
/**
|
||||
* The well-known path for the agent card
|
||||
*/
|
||||
export const AGENT_CARD_PATH = '.well-known/agent-card.json';
|
||||
|
||||
/**
|
||||
* The name of the extension header used in http
|
||||
*/
|
||||
export const HTTP_EXTENSION_HEADER = 'X-A2A-Extensions';
|
||||
1
aitimemachine/a2a/src/core.ts
Normal file
1
aitimemachine/a2a/src/core.ts
Normal file
@ -0,0 +1 @@
|
||||
export type TransportProtocolName = 'JSONRPC' | 'HTTP+JSON' | 'GRPC' | (string & {});
|
||||
69
aitimemachine/a2a/src/errors.ts
Normal file
69
aitimemachine/a2a/src/errors.ts
Normal file
@ -0,0 +1,69 @@
|
||||
// Legacy JSON-RPC error codes.
|
||||
export const A2A_ERROR_CODE = {
|
||||
PARSE_ERROR: -32700,
|
||||
INVALID_REQUEST: -32600,
|
||||
METHOD_NOT_FOUND: -32601,
|
||||
INVALID_PARAMS: -32602,
|
||||
INTERNAL_ERROR: -32603,
|
||||
TASK_NOT_FOUND: -32001,
|
||||
TASK_NOT_CANCELABLE: -32002,
|
||||
PUSH_NOTIFICATION_NOT_SUPPORTED: -32003,
|
||||
UNSUPPORTED_OPERATION: -32004,
|
||||
CONTENT_TYPE_NOT_SUPPORTED: -32005,
|
||||
INVALID_AGENT_RESPONSE: -32006,
|
||||
AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED: -32007,
|
||||
} as const;
|
||||
|
||||
// Transport-agnostic errors according to https://a2a-protocol.org/v0.3.0/specification/#82-a2a-specific-errors.
|
||||
// Due to a name conflict with legacy JSON-RPC types reexported from src/index.ts
|
||||
// below errors are going to be exported via src/client/index.ts to allow usage
|
||||
// from external transport implementations.
|
||||
|
||||
export class TaskNotFoundError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Task not found');
|
||||
this.name = 'TaskNotFoundError';
|
||||
}
|
||||
}
|
||||
|
||||
export class TaskNotCancelableError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Task cannot be canceled');
|
||||
this.name = 'TaskNotCancelableError';
|
||||
}
|
||||
}
|
||||
|
||||
export class PushNotificationNotSupportedError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Push Notification is not supported');
|
||||
this.name = 'PushNotificationNotSupportedError';
|
||||
}
|
||||
}
|
||||
|
||||
export class UnsupportedOperationError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'This operation is not supported');
|
||||
this.name = 'UnsupportedOperationError';
|
||||
}
|
||||
}
|
||||
|
||||
export class ContentTypeNotSupportedError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Incompatible content types');
|
||||
this.name = 'ContentTypeNotSupportedError';
|
||||
}
|
||||
}
|
||||
|
||||
export class InvalidAgentResponseError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Invalid agent response type');
|
||||
this.name = 'InvalidAgentResponseError';
|
||||
}
|
||||
}
|
||||
|
||||
export class AuthenticatedExtendedCardNotConfiguredError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? 'Authenticated Extended Card not configured');
|
||||
this.name = 'AuthenticatedExtendedCardNotConfiguredError';
|
||||
}
|
||||
}
|
||||
48
aitimemachine/a2a/src/extensions.ts
Normal file
48
aitimemachine/a2a/src/extensions.ts
Normal file
@ -0,0 +1,48 @@
|
||||
/**
|
||||
* A2A Protocol Extension URI.
|
||||
*/
|
||||
export type ExtensionURI = string;
|
||||
|
||||
/**
|
||||
* A collection of {@link ExtensionURI}.
|
||||
*/
|
||||
export type Extensions = ExtensionURI[];
|
||||
|
||||
export const Extensions = {
|
||||
/**
|
||||
* Creates new {@link Extensions} from `current` and `additional`.
|
||||
* If `current` already contains `additional` it is returned unmodified.
|
||||
*/
|
||||
createFrom: (current: Extensions | undefined, additional: ExtensionURI): Extensions => {
|
||||
if (current?.includes(additional)) {
|
||||
return current;
|
||||
}
|
||||
return [...(current ?? []), additional];
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates {@link Extensions} from comma separated extensions identifiers as per
|
||||
* https://a2a-protocol.org/latest/specification/#326-service-parameters.
|
||||
* Parses the output of `toServiceParameter`.
|
||||
*/
|
||||
parseServiceParameter: (value: string | undefined): Extensions => {
|
||||
if (!value) {
|
||||
return [];
|
||||
}
|
||||
const unique = new Set(
|
||||
value
|
||||
.split(',')
|
||||
.map((ext) => ext.trim())
|
||||
.filter((ext) => ext.length > 0)
|
||||
);
|
||||
return Array.from(unique);
|
||||
},
|
||||
|
||||
/**
|
||||
* Converts {@link Extensions} to comma separated extensions identifiers as per
|
||||
* https://a2a-protocol.org/latest/specification/#326-service-parameters.
|
||||
*/
|
||||
toServiceParameter: (value: Extensions): string => {
|
||||
return value.join(',');
|
||||
},
|
||||
};
|
||||
51
aitimemachine/a2a/src/grpc/README.md
Normal file
51
aitimemachine/a2a/src/grpc/README.md
Normal file
@ -0,0 +1,51 @@
|
||||
# gRPC Service Generation
|
||||
|
||||
This directory contains the configuration for generating the gRPC service definitions for the A2A SDK. The generation process uses [Buf](https://buf.build/) and `ts-proto`.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Ensure you have the project dependencies installed:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
This project uses `@bufbuild/buf` which is listed in the `devDependencies`.
|
||||
Add the `a2a_services.proto` files to the `pb` directory.
|
||||
|
||||
## Generating Code
|
||||
|
||||
To generate the gRPC service definitions, run the following command from this directory (`src/grpc`):
|
||||
|
||||
```bash
|
||||
npx buf generate
|
||||
```
|
||||
|
||||
This will generate the TypeScript files in the `./pb` directory (as configured in `buf.gen.yaml`).
|
||||
|
||||
## Post-Processing
|
||||
|
||||
**Important:** After running the generation, a post-processing step is **necessary**.
|
||||
|
||||
The `buf` generation process produces a file (e.g., `src/grpc/pb/a2a_services.ts`) that contains both the service definitions and the message types. However, to maintain consistency across the SDK and ensure that we are using the canonical types, we must update the generated file to import the actual types from the central types definition file.
|
||||
|
||||
**Steps:**
|
||||
|
||||
1. Open the generated file (e.g., `src/grpc/pb/a2a_services.ts`).
|
||||
2. Locate the imports/type definitions section.
|
||||
3. Replace the local message type definitions or imports with an import from the shared types file:
|
||||
`src/types/pb/a2a_types.ts`
|
||||
|
||||
For example, change:
|
||||
```typescript
|
||||
export interface Task { ... }
|
||||
```
|
||||
to:
|
||||
```typescript
|
||||
import * as pb from "../../types/pb/a2a_types.js";
|
||||
|
||||
export type Task = pb.Task;
|
||||
// ... maps other types similarly
|
||||
```
|
||||
|
||||
This ensures that the gRPC services operate on the same `Task` (and other) interfaces as the rest of the application, avoiding type mismatch errors.
|
||||
18
aitimemachine/a2a/src/grpc/buf.gen.yaml
Normal file
18
aitimemachine/a2a/src/grpc/buf.gen.yaml
Normal file
@ -0,0 +1,18 @@
|
||||
# buf generate
|
||||
# Configuration for the buf generate command
|
||||
# Uses remote plugins, no separate install required.
|
||||
version: v2
|
||||
inputs:
|
||||
- directory: ./pb
|
||||
plugins:
|
||||
- remote: buf.build/community/stephenh-ts-proto:v2.6.1
|
||||
opt:
|
||||
- oneof=unions-value
|
||||
- importSuffix=.js
|
||||
- outputServices=grpc-js
|
||||
- env=node
|
||||
- esModuleInterop=true
|
||||
- outputJsonMethods=false
|
||||
- outputPartialMethods=false
|
||||
- useDate=string
|
||||
out: ./pb
|
||||
6
aitimemachine/a2a/src/grpc/buf.lock
Normal file
6
aitimemachine/a2a/src/grpc/buf.lock
Normal file
@ -0,0 +1,6 @@
|
||||
# Generated by buf. DO NOT EDIT.
|
||||
version: v2
|
||||
deps:
|
||||
- name: buf.build/googleapis/googleapis
|
||||
commit: 004180b77378443887d3b55cabc00384
|
||||
digest: b5:e8f475fe3330f31f5fd86ac689093bcd274e19611a09db91f41d637cb9197881ce89882b94d13a58738e53c91c6e4bae7dc1feba85f590164c975a89e25115dc
|
||||
6
aitimemachine/a2a/src/grpc/buf.yaml
Normal file
6
aitimemachine/a2a/src/grpc/buf.yaml
Normal file
@ -0,0 +1,6 @@
|
||||
version: v2
|
||||
modules:
|
||||
- path: ./pb
|
||||
deps:
|
||||
# Common Protobuf types.
|
||||
- buf.build/googleapis/googleapis
|
||||
3627
aitimemachine/a2a/src/grpc/pb/a2a_services.ts
Normal file
3627
aitimemachine/a2a/src/grpc/pb/a2a_services.ts
Normal file
File diff suppressed because it is too large
Load Diff
9
aitimemachine/a2a/src/grpc/pb/google/api/annotations.ts
Normal file
9
aitimemachine/a2a/src/grpc/pb/google/api/annotations.ts
Normal file
@ -0,0 +1,9 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.6.1
|
||||
// protoc unknown
|
||||
// source: google/api/annotations.proto
|
||||
|
||||
/* eslint-disable */
|
||||
|
||||
export const protobufPackage = "google.api";
|
||||
1697
aitimemachine/a2a/src/grpc/pb/google/api/client.ts
Normal file
1697
aitimemachine/a2a/src/grpc/pb/google/api/client.ts
Normal file
File diff suppressed because it is too large
Load Diff
83
aitimemachine/a2a/src/grpc/pb/google/api/field_behavior.ts
Normal file
83
aitimemachine/a2a/src/grpc/pb/google/api/field_behavior.ts
Normal file
@ -0,0 +1,83 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.6.1
|
||||
// protoc unknown
|
||||
// source: google/api/field_behavior.proto
|
||||
|
||||
/* eslint-disable */
|
||||
|
||||
export const protobufPackage = "google.api";
|
||||
|
||||
/**
|
||||
* An indicator of the behavior of a given field (for example, that a field
|
||||
* is required in requests, or given as output but ignored as input).
|
||||
* This **does not** change the behavior in protocol buffers itself; it only
|
||||
* denotes the behavior and may affect how API tooling handles the field.
|
||||
*
|
||||
* Note: This enum **may** receive new values in the future.
|
||||
*/
|
||||
export enum FieldBehavior {
|
||||
/** FIELD_BEHAVIOR_UNSPECIFIED - Conventional default for enums. Do not use this. */
|
||||
FIELD_BEHAVIOR_UNSPECIFIED = 0,
|
||||
/**
|
||||
* OPTIONAL - Specifically denotes a field as optional.
|
||||
* While all fields in protocol buffers are optional, this may be specified
|
||||
* for emphasis if appropriate.
|
||||
*/
|
||||
OPTIONAL = 1,
|
||||
/**
|
||||
* REQUIRED - Denotes a field as required.
|
||||
* This indicates that the field **must** be provided as part of the request,
|
||||
* and failure to do so will cause an error (usually `INVALID_ARGUMENT`).
|
||||
*/
|
||||
REQUIRED = 2,
|
||||
/**
|
||||
* OUTPUT_ONLY - Denotes a field as output only.
|
||||
* This indicates that the field is provided in responses, but including the
|
||||
* field in a request does nothing (the server *must* ignore it and
|
||||
* *must not* throw an error as a result of the field's presence).
|
||||
*/
|
||||
OUTPUT_ONLY = 3,
|
||||
/**
|
||||
* INPUT_ONLY - Denotes a field as input only.
|
||||
* This indicates that the field is provided in requests, and the
|
||||
* corresponding field is not included in output.
|
||||
*/
|
||||
INPUT_ONLY = 4,
|
||||
/**
|
||||
* IMMUTABLE - Denotes a field as immutable.
|
||||
* This indicates that the field may be set once in a request to create a
|
||||
* resource, but may not be changed thereafter.
|
||||
*/
|
||||
IMMUTABLE = 5,
|
||||
/**
|
||||
* UNORDERED_LIST - Denotes that a (repeated) field is an unordered list.
|
||||
* This indicates that the service may provide the elements of the list
|
||||
* in any arbitrary order, rather than the order the user originally
|
||||
* provided. Additionally, the list's order may or may not be stable.
|
||||
*/
|
||||
UNORDERED_LIST = 6,
|
||||
/**
|
||||
* NON_EMPTY_DEFAULT - Denotes that this field returns a non-empty default value if not set.
|
||||
* This indicates that if the user provides the empty value in a request,
|
||||
* a non-empty value will be returned. The user will not be aware of what
|
||||
* non-empty value to expect.
|
||||
*/
|
||||
NON_EMPTY_DEFAULT = 7,
|
||||
/**
|
||||
* IDENTIFIER - Denotes that the field in a resource (a message annotated with
|
||||
* google.api.resource) is used in the resource name to uniquely identify the
|
||||
* resource. For AIP-compliant APIs, this should only be applied to the
|
||||
* `name` field on the resource.
|
||||
*
|
||||
* This behavior should not be applied to references to other resources within
|
||||
* the message.
|
||||
*
|
||||
* The identifier field of resources often have different field behavior
|
||||
* depending on the request it is embedded in (e.g. for Create methods name
|
||||
* is optional and unused, while for Update methods it is required). Instead
|
||||
* of method-specific annotations, only `IDENTIFIER` is required.
|
||||
*/
|
||||
IDENTIFIER = 8,
|
||||
UNRECOGNIZED = -1,
|
||||
}
|
||||
612
aitimemachine/a2a/src/grpc/pb/google/api/http.ts
Normal file
612
aitimemachine/a2a/src/grpc/pb/google/api/http.ts
Normal file
@ -0,0 +1,612 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.6.1
|
||||
// protoc unknown
|
||||
// source: google/api/http.proto
|
||||
|
||||
/* eslint-disable */
|
||||
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
|
||||
|
||||
export const protobufPackage = "google.api";
|
||||
|
||||
/**
|
||||
* Defines the HTTP configuration for an API service. It contains a list of
|
||||
* [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
|
||||
* to one or more HTTP REST API methods.
|
||||
*/
|
||||
export interface Http {
|
||||
/**
|
||||
* A list of HTTP configuration rules that apply to individual API methods.
|
||||
*
|
||||
* **NOTE:** All service configuration rules follow "last one wins" order.
|
||||
*/
|
||||
rules: HttpRule[];
|
||||
/**
|
||||
* When set to true, URL path parameters will be fully URI-decoded except in
|
||||
* cases of single segment matches in reserved expansion, where "%2F" will be
|
||||
* left encoded.
|
||||
*
|
||||
* The default behavior is to not decode RFC 6570 reserved characters in multi
|
||||
* segment matches.
|
||||
*/
|
||||
fullyDecodeReservedExpansion: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* gRPC Transcoding
|
||||
*
|
||||
* gRPC Transcoding is a feature for mapping between a gRPC method and one or
|
||||
* more HTTP REST endpoints. It allows developers to build a single API service
|
||||
* that supports both gRPC APIs and REST APIs. Many systems, including [Google
|
||||
* APIs](https://github.com/googleapis/googleapis),
|
||||
* [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC
|
||||
* Gateway](https://github.com/grpc-ecosystem/grpc-gateway),
|
||||
* and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature
|
||||
* and use it for large scale production services.
|
||||
*
|
||||
* `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies
|
||||
* how different portions of the gRPC request message are mapped to the URL
|
||||
* path, URL query parameters, and HTTP request body. It also controls how the
|
||||
* gRPC response message is mapped to the HTTP response body. `HttpRule` is
|
||||
* typically specified as an `google.api.http` annotation on the gRPC method.
|
||||
*
|
||||
* Each mapping specifies a URL path template and an HTTP method. The path
|
||||
* template may refer to one or more fields in the gRPC request message, as long
|
||||
* as each field is a non-repeated field with a primitive (non-message) type.
|
||||
* The path template controls how fields of the request message are mapped to
|
||||
* the URL path.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* service Messaging {
|
||||
* rpc GetMessage(GetMessageRequest) returns (Message) {
|
||||
* option (google.api.http) = {
|
||||
* get: "/v1/{name=messages/*}"
|
||||
* };
|
||||
* }
|
||||
* }
|
||||
* message GetMessageRequest {
|
||||
* string name = 1; // Mapped to URL path.
|
||||
* }
|
||||
* message Message {
|
||||
* string text = 1; // The resource content.
|
||||
* }
|
||||
*
|
||||
* This enables an HTTP REST to gRPC mapping as below:
|
||||
*
|
||||
* - HTTP: `GET /v1/messages/123456`
|
||||
* - gRPC: `GetMessage(name: "messages/123456")`
|
||||
*
|
||||
* Any fields in the request message which are not bound by the path template
|
||||
* automatically become HTTP query parameters if there is no HTTP request body.
|
||||
* For example:
|
||||
*
|
||||
* service Messaging {
|
||||
* rpc GetMessage(GetMessageRequest) returns (Message) {
|
||||
* option (google.api.http) = {
|
||||
* get:"/v1/messages/{message_id}"
|
||||
* };
|
||||
* }
|
||||
* }
|
||||
* message GetMessageRequest {
|
||||
* message SubMessage {
|
||||
* string subfield = 1;
|
||||
* }
|
||||
* string message_id = 1; // Mapped to URL path.
|
||||
* int64 revision = 2; // Mapped to URL query parameter `revision`.
|
||||
* SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`.
|
||||
* }
|
||||
*
|
||||
* This enables a HTTP JSON to RPC mapping as below:
|
||||
*
|
||||
* - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo`
|
||||
* - gRPC: `GetMessage(message_id: "123456" revision: 2 sub:
|
||||
* SubMessage(subfield: "foo"))`
|
||||
*
|
||||
* Note that fields which are mapped to URL query parameters must have a
|
||||
* primitive type or a repeated primitive type or a non-repeated message type.
|
||||
* In the case of a repeated type, the parameter can be repeated in the URL
|
||||
* as `...?param=A¶m=B`. In the case of a message type, each field of the
|
||||
* message is mapped to a separate parameter, such as
|
||||
* `...?foo.a=A&foo.b=B&foo.c=C`.
|
||||
*
|
||||
* For HTTP methods that allow a request body, the `body` field
|
||||
* specifies the mapping. Consider a REST update method on the
|
||||
* message resource collection:
|
||||
*
|
||||
* service Messaging {
|
||||
* rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
|
||||
* option (google.api.http) = {
|
||||
* patch: "/v1/messages/{message_id}"
|
||||
* body: "message"
|
||||
* };
|
||||
* }
|
||||
* }
|
||||
* message UpdateMessageRequest {
|
||||
* string message_id = 1; // mapped to the URL
|
||||
* Message message = 2; // mapped to the body
|
||||
* }
|
||||
*
|
||||
* The following HTTP JSON to RPC mapping is enabled, where the
|
||||
* representation of the JSON in the request body is determined by
|
||||
* protos JSON encoding:
|
||||
*
|
||||
* - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }`
|
||||
* - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })`
|
||||
*
|
||||
* The special name `*` can be used in the body mapping to define that
|
||||
* every field not bound by the path template should be mapped to the
|
||||
* request body. This enables the following alternative definition of
|
||||
* the update method:
|
||||
*
|
||||
* service Messaging {
|
||||
* rpc UpdateMessage(Message) returns (Message) {
|
||||
* option (google.api.http) = {
|
||||
* patch: "/v1/messages/{message_id}"
|
||||
* body: "*"
|
||||
* };
|
||||
* }
|
||||
* }
|
||||
* message Message {
|
||||
* string message_id = 1;
|
||||
* string text = 2;
|
||||
* }
|
||||
*
|
||||
* The following HTTP JSON to RPC mapping is enabled:
|
||||
*
|
||||
* - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }`
|
||||
* - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")`
|
||||
*
|
||||
* Note that when using `*` in the body mapping, it is not possible to
|
||||
* have HTTP parameters, as all fields not bound by the path end in
|
||||
* the body. This makes this option more rarely used in practice when
|
||||
* defining REST APIs. The common usage of `*` is in custom methods
|
||||
* which don't use the URL at all for transferring data.
|
||||
*
|
||||
* It is possible to define multiple HTTP methods for one RPC by using
|
||||
* the `additional_bindings` option. Example:
|
||||
*
|
||||
* service Messaging {
|
||||
* rpc GetMessage(GetMessageRequest) returns (Message) {
|
||||
* option (google.api.http) = {
|
||||
* get: "/v1/messages/{message_id}"
|
||||
* additional_bindings {
|
||||
* get: "/v1/users/{user_id}/messages/{message_id}"
|
||||
* }
|
||||
* };
|
||||
* }
|
||||
* }
|
||||
* message GetMessageRequest {
|
||||
* string message_id = 1;
|
||||
* string user_id = 2;
|
||||
* }
|
||||
*
|
||||
* This enables the following two alternative HTTP JSON to RPC mappings:
|
||||
*
|
||||
* - HTTP: `GET /v1/messages/123456`
|
||||
* - gRPC: `GetMessage(message_id: "123456")`
|
||||
*
|
||||
* - HTTP: `GET /v1/users/me/messages/123456`
|
||||
* - gRPC: `GetMessage(user_id: "me" message_id: "123456")`
|
||||
*
|
||||
* Rules for HTTP mapping
|
||||
*
|
||||
* 1. Leaf request fields (recursive expansion nested messages in the request
|
||||
* message) are classified into three categories:
|
||||
* - Fields referred by the path template. They are passed via the URL path.
|
||||
* - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They
|
||||
* are passed via the HTTP
|
||||
* request body.
|
||||
* - All other fields are passed via the URL query parameters, and the
|
||||
* parameter name is the field path in the request message. A repeated
|
||||
* field can be represented as multiple query parameters under the same
|
||||
* name.
|
||||
* 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL
|
||||
* query parameter, all fields
|
||||
* are passed via URL path and HTTP request body.
|
||||
* 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP
|
||||
* request body, all
|
||||
* fields are passed via URL path and URL query parameters.
|
||||
*
|
||||
* Path template syntax
|
||||
*
|
||||
* Template = "/" Segments [ Verb ] ;
|
||||
* Segments = Segment { "/" Segment } ;
|
||||
* Segment = "*" | "**" | LITERAL | Variable ;
|
||||
* Variable = "{" FieldPath [ "=" Segments ] "}" ;
|
||||
* FieldPath = IDENT { "." IDENT } ;
|
||||
* Verb = ":" LITERAL ;
|
||||
*
|
||||
* The syntax `*` matches a single URL path segment. The syntax `**` matches
|
||||
* zero or more URL path segments, which must be the last part of the URL path
|
||||
* except the `Verb`.
|
||||
*
|
||||
* The syntax `Variable` matches part of the URL path as specified by its
|
||||
* template. A variable template must not contain other variables. If a variable
|
||||
* matches a single path segment, its template may be omitted, e.g. `{var}`
|
||||
* is equivalent to `{var=*}`.
|
||||
*
|
||||
* The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL`
|
||||
* contains any reserved character, such characters should be percent-encoded
|
||||
* before the matching.
|
||||
*
|
||||
* If a variable contains exactly one path segment, such as `"{var}"` or
|
||||
* `"{var=*}"`, when such a variable is expanded into a URL path on the client
|
||||
* side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The
|
||||
* server side does the reverse decoding. Such variables show up in the
|
||||
* [Discovery
|
||||
* Document](https://developers.google.com/discovery/v1/reference/apis) as
|
||||
* `{var}`.
|
||||
*
|
||||
* If a variable contains multiple path segments, such as `"{var=foo/*}"`
|
||||
* or `"{var=**}"`, when such a variable is expanded into a URL path on the
|
||||
* client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded.
|
||||
* The server side does the reverse decoding, except "%2F" and "%2f" are left
|
||||
* unchanged. Such variables show up in the
|
||||
* [Discovery
|
||||
* Document](https://developers.google.com/discovery/v1/reference/apis) as
|
||||
* `{+var}`.
|
||||
*
|
||||
* Using gRPC API Service Configuration
|
||||
*
|
||||
* gRPC API Service Configuration (service config) is a configuration language
|
||||
* for configuring a gRPC service to become a user-facing product. The
|
||||
* service config is simply the YAML representation of the `google.api.Service`
|
||||
* proto message.
|
||||
*
|
||||
* As an alternative to annotating your proto file, you can configure gRPC
|
||||
* transcoding in your service config YAML files. You do this by specifying a
|
||||
* `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same
|
||||
* effect as the proto annotation. This can be particularly useful if you
|
||||
* have a proto that is reused in multiple services. Note that any transcoding
|
||||
* specified in the service config will override any matching transcoding
|
||||
* configuration in the proto.
|
||||
*
|
||||
* The following example selects a gRPC method and applies an `HttpRule` to it:
|
||||
*
|
||||
* http:
|
||||
* rules:
|
||||
* - selector: example.v1.Messaging.GetMessage
|
||||
* get: /v1/messages/{message_id}/{sub.subfield}
|
||||
*
|
||||
* Special notes
|
||||
*
|
||||
* When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the
|
||||
* proto to JSON conversion must follow the [proto3
|
||||
* specification](https://developers.google.com/protocol-buffers/docs/proto3#json).
|
||||
*
|
||||
* While the single segment variable follows the semantics of
|
||||
* [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String
|
||||
* Expansion, the multi segment variable **does not** follow RFC 6570 Section
|
||||
* 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion
|
||||
* does not expand special characters like `?` and `#`, which would lead
|
||||
* to invalid URLs. As the result, gRPC Transcoding uses a custom encoding
|
||||
* for multi segment variables.
|
||||
*
|
||||
* The path variables **must not** refer to any repeated or mapped field,
|
||||
* because client libraries are not capable of handling such variable expansion.
|
||||
*
|
||||
* The path variables **must not** capture the leading "/" character. The reason
|
||||
* is that the most common use case "{var}" does not capture the leading "/"
|
||||
* character. For consistency, all path variables must share the same behavior.
|
||||
*
|
||||
* Repeated message fields must not be mapped to URL query parameters, because
|
||||
* no client library can support such complicated mapping.
|
||||
*
|
||||
* If an API needs to use a JSON array for request or response body, it can map
|
||||
* the request or response body to a repeated field. However, some gRPC
|
||||
* Transcoding implementations may not support this feature.
|
||||
*/
|
||||
export interface HttpRule {
|
||||
/**
|
||||
* Selects a method to which this rule applies.
|
||||
*
|
||||
* Refer to [selector][google.api.DocumentationRule.selector] for syntax
|
||||
* details.
|
||||
*/
|
||||
selector: string;
|
||||
/**
|
||||
* Determines the URL pattern is matched by this rules. This pattern can be
|
||||
* used with any of the {get|put|post|delete|patch} methods. A custom method
|
||||
* can be defined using the 'custom' field.
|
||||
*/
|
||||
pattern?:
|
||||
| //
|
||||
/**
|
||||
* Maps to HTTP GET. Used for listing and getting information about
|
||||
* resources.
|
||||
*/
|
||||
{ $case: "get"; value: string }
|
||||
| //
|
||||
/** Maps to HTTP PUT. Used for replacing a resource. */
|
||||
{ $case: "put"; value: string }
|
||||
| //
|
||||
/** Maps to HTTP POST. Used for creating a resource or performing an action. */
|
||||
{ $case: "post"; value: string }
|
||||
| //
|
||||
/** Maps to HTTP DELETE. Used for deleting a resource. */
|
||||
{ $case: "delete"; value: string }
|
||||
| //
|
||||
/** Maps to HTTP PATCH. Used for updating a resource. */
|
||||
{ $case: "patch"; value: string }
|
||||
| //
|
||||
/**
|
||||
* The custom pattern is used for specifying an HTTP method that is not
|
||||
* included in the `pattern` field, such as HEAD, or "*" to leave the
|
||||
* HTTP method unspecified for this rule. The wild-card rule is useful
|
||||
* for services that provide content to Web (HTML) clients.
|
||||
*/
|
||||
{ $case: "custom"; value: CustomHttpPattern }
|
||||
| undefined;
|
||||
/**
|
||||
* The name of the request field whose value is mapped to the HTTP request
|
||||
* body, or `*` for mapping all request fields not captured by the path
|
||||
* pattern to the HTTP body, or omitted for not having any HTTP request body.
|
||||
*
|
||||
* NOTE: the referred field must be present at the top-level of the request
|
||||
* message type.
|
||||
*/
|
||||
body: string;
|
||||
/**
|
||||
* Optional. The name of the response field whose value is mapped to the HTTP
|
||||
* response body. When omitted, the entire response message will be used
|
||||
* as the HTTP response body.
|
||||
*
|
||||
* NOTE: The referred field must be present at the top-level of the response
|
||||
* message type.
|
||||
*/
|
||||
responseBody: string;
|
||||
/**
|
||||
* Additional HTTP bindings for the selector. Nested bindings must
|
||||
* not contain an `additional_bindings` field themselves (that is,
|
||||
* the nesting may only be one level deep).
|
||||
*/
|
||||
additionalBindings: HttpRule[];
|
||||
}
|
||||
|
||||
/** A custom pattern is used for defining custom HTTP verb. */
|
||||
export interface CustomHttpPattern {
|
||||
/** The name of this custom HTTP verb. */
|
||||
kind: string;
|
||||
/** The path matched by this custom verb. */
|
||||
path: string;
|
||||
}
|
||||
|
||||
function createBaseHttp(): Http {
|
||||
return { rules: [], fullyDecodeReservedExpansion: false };
|
||||
}
|
||||
|
||||
export const Http: MessageFns<Http> = {
|
||||
encode(message: Http, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
for (const v of message.rules) {
|
||||
HttpRule.encode(v!, writer.uint32(10).fork()).join();
|
||||
}
|
||||
if (message.fullyDecodeReservedExpansion !== false) {
|
||||
writer.uint32(16).bool(message.fullyDecodeReservedExpansion);
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): Http {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
let end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseHttp();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 10) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.rules.push(HttpRule.decode(reader, reader.uint32()));
|
||||
continue;
|
||||
}
|
||||
case 2: {
|
||||
if (tag !== 16) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.fullyDecodeReservedExpansion = reader.bool();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
function createBaseHttpRule(): HttpRule {
|
||||
return { selector: "", pattern: undefined, body: "", responseBody: "", additionalBindings: [] };
|
||||
}
|
||||
|
||||
export const HttpRule: MessageFns<HttpRule> = {
|
||||
encode(message: HttpRule, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
if (message.selector !== "") {
|
||||
writer.uint32(10).string(message.selector);
|
||||
}
|
||||
switch (message.pattern?.$case) {
|
||||
case "get":
|
||||
writer.uint32(18).string(message.pattern.value);
|
||||
break;
|
||||
case "put":
|
||||
writer.uint32(26).string(message.pattern.value);
|
||||
break;
|
||||
case "post":
|
||||
writer.uint32(34).string(message.pattern.value);
|
||||
break;
|
||||
case "delete":
|
||||
writer.uint32(42).string(message.pattern.value);
|
||||
break;
|
||||
case "patch":
|
||||
writer.uint32(50).string(message.pattern.value);
|
||||
break;
|
||||
case "custom":
|
||||
CustomHttpPattern.encode(message.pattern.value, writer.uint32(66).fork()).join();
|
||||
break;
|
||||
}
|
||||
if (message.body !== "") {
|
||||
writer.uint32(58).string(message.body);
|
||||
}
|
||||
if (message.responseBody !== "") {
|
||||
writer.uint32(98).string(message.responseBody);
|
||||
}
|
||||
for (const v of message.additionalBindings) {
|
||||
HttpRule.encode(v!, writer.uint32(90).fork()).join();
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): HttpRule {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
let end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseHttpRule();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 10) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.selector = reader.string();
|
||||
continue;
|
||||
}
|
||||
case 2: {
|
||||
if (tag !== 18) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.pattern = { $case: "get", value: reader.string() };
|
||||
continue;
|
||||
}
|
||||
case 3: {
|
||||
if (tag !== 26) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.pattern = { $case: "put", value: reader.string() };
|
||||
continue;
|
||||
}
|
||||
case 4: {
|
||||
if (tag !== 34) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.pattern = { $case: "post", value: reader.string() };
|
||||
continue;
|
||||
}
|
||||
case 5: {
|
||||
if (tag !== 42) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.pattern = { $case: "delete", value: reader.string() };
|
||||
continue;
|
||||
}
|
||||
case 6: {
|
||||
if (tag !== 50) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.pattern = { $case: "patch", value: reader.string() };
|
||||
continue;
|
||||
}
|
||||
case 8: {
|
||||
if (tag !== 66) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.pattern = { $case: "custom", value: CustomHttpPattern.decode(reader, reader.uint32()) };
|
||||
continue;
|
||||
}
|
||||
case 7: {
|
||||
if (tag !== 58) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.body = reader.string();
|
||||
continue;
|
||||
}
|
||||
case 12: {
|
||||
if (tag !== 98) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.responseBody = reader.string();
|
||||
continue;
|
||||
}
|
||||
case 11: {
|
||||
if (tag !== 90) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.additionalBindings.push(HttpRule.decode(reader, reader.uint32()));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
function createBaseCustomHttpPattern(): CustomHttpPattern {
|
||||
return { kind: "", path: "" };
|
||||
}
|
||||
|
||||
export const CustomHttpPattern: MessageFns<CustomHttpPattern> = {
|
||||
encode(message: CustomHttpPattern, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
if (message.kind !== "") {
|
||||
writer.uint32(10).string(message.kind);
|
||||
}
|
||||
if (message.path !== "") {
|
||||
writer.uint32(18).string(message.path);
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): CustomHttpPattern {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
let end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseCustomHttpPattern();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 10) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.kind = reader.string();
|
||||
continue;
|
||||
}
|
||||
case 2: {
|
||||
if (tag !== 18) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.path = reader.string();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
export interface MessageFns<T> {
|
||||
encode(message: T, writer?: BinaryWriter): BinaryWriter;
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): T;
|
||||
}
|
||||
64
aitimemachine/a2a/src/grpc/pb/google/api/launch_stage.ts
Normal file
64
aitimemachine/a2a/src/grpc/pb/google/api/launch_stage.ts
Normal file
@ -0,0 +1,64 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.6.1
|
||||
// protoc unknown
|
||||
// source: google/api/launch_stage.proto
|
||||
|
||||
/* eslint-disable */
|
||||
|
||||
export const protobufPackage = "google.api";
|
||||
|
||||
/**
|
||||
* The launch stage as defined by [Google Cloud Platform
|
||||
* Launch Stages](https://cloud.google.com/terms/launch-stages).
|
||||
*/
|
||||
export enum LaunchStage {
|
||||
/** LAUNCH_STAGE_UNSPECIFIED - Do not use this default value. */
|
||||
LAUNCH_STAGE_UNSPECIFIED = 0,
|
||||
/** UNIMPLEMENTED - The feature is not yet implemented. Users can not use it. */
|
||||
UNIMPLEMENTED = 6,
|
||||
/** PRELAUNCH - Prelaunch features are hidden from users and are only visible internally. */
|
||||
PRELAUNCH = 7,
|
||||
/**
|
||||
* EARLY_ACCESS - Early Access features are limited to a closed group of testers. To use
|
||||
* these features, you must sign up in advance and sign a Trusted Tester
|
||||
* agreement (which includes confidentiality provisions). These features may
|
||||
* be unstable, changed in backward-incompatible ways, and are not
|
||||
* guaranteed to be released.
|
||||
*/
|
||||
EARLY_ACCESS = 1,
|
||||
/**
|
||||
* ALPHA - Alpha is a limited availability test for releases before they are cleared
|
||||
* for widespread use. By Alpha, all significant design issues are resolved
|
||||
* and we are in the process of verifying functionality. Alpha customers
|
||||
* need to apply for access, agree to applicable terms, and have their
|
||||
* projects allowlisted. Alpha releases don't have to be feature complete,
|
||||
* no SLAs are provided, and there are no technical support obligations, but
|
||||
* they will be far enough along that customers can actually use them in
|
||||
* test environments or for limited-use tests -- just like they would in
|
||||
* normal production cases.
|
||||
*/
|
||||
ALPHA = 2,
|
||||
/**
|
||||
* BETA - Beta is the point at which we are ready to open a release for any
|
||||
* customer to use. There are no SLA or technical support obligations in a
|
||||
* Beta release. Products will be complete from a feature perspective, but
|
||||
* may have some open outstanding issues. Beta releases are suitable for
|
||||
* limited production use cases.
|
||||
*/
|
||||
BETA = 3,
|
||||
/**
|
||||
* GA - GA features are open to all developers and are considered stable and
|
||||
* fully qualified for production use.
|
||||
*/
|
||||
GA = 4,
|
||||
/**
|
||||
* DEPRECATED - Deprecated features are scheduled to be shut down and removed. For more
|
||||
* information, see the "Deprecation Policy" section of our [Terms of
|
||||
* Service](https://cloud.google.com/terms/)
|
||||
* and the [Google Cloud Platform Subject to the Deprecation
|
||||
* Policy](https://cloud.google.com/terms/deprecation) documentation.
|
||||
*/
|
||||
DEPRECATED = 5,
|
||||
UNRECOGNIZED = -1,
|
||||
}
|
||||
4478
aitimemachine/a2a/src/grpc/pb/google/protobuf/descriptor.ts
Normal file
4478
aitimemachine/a2a/src/grpc/pb/google/protobuf/descriptor.ts
Normal file
File diff suppressed because it is too large
Load Diff
152
aitimemachine/a2a/src/grpc/pb/google/protobuf/duration.ts
Normal file
152
aitimemachine/a2a/src/grpc/pb/google/protobuf/duration.ts
Normal file
@ -0,0 +1,152 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.6.1
|
||||
// protoc unknown
|
||||
// source: google/protobuf/duration.proto
|
||||
|
||||
/* eslint-disable */
|
||||
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
|
||||
|
||||
export const protobufPackage = "google.protobuf";
|
||||
|
||||
/**
|
||||
* A Duration represents a signed, fixed-length span of time represented
|
||||
* as a count of seconds and fractions of seconds at nanosecond
|
||||
* resolution. It is independent of any calendar and concepts like "day"
|
||||
* or "month". It is related to Timestamp in that the difference between
|
||||
* two Timestamp values is a Duration and it can be added or subtracted
|
||||
* from a Timestamp. Range is approximately +-10,000 years.
|
||||
*
|
||||
* # Examples
|
||||
*
|
||||
* Example 1: Compute Duration from two Timestamps in pseudo code.
|
||||
*
|
||||
* Timestamp start = ...;
|
||||
* Timestamp end = ...;
|
||||
* Duration duration = ...;
|
||||
*
|
||||
* duration.seconds = end.seconds - start.seconds;
|
||||
* duration.nanos = end.nanos - start.nanos;
|
||||
*
|
||||
* if (duration.seconds < 0 && duration.nanos > 0) {
|
||||
* duration.seconds += 1;
|
||||
* duration.nanos -= 1000000000;
|
||||
* } else if (duration.seconds > 0 && duration.nanos < 0) {
|
||||
* duration.seconds -= 1;
|
||||
* duration.nanos += 1000000000;
|
||||
* }
|
||||
*
|
||||
* Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
|
||||
*
|
||||
* Timestamp start = ...;
|
||||
* Duration duration = ...;
|
||||
* Timestamp end = ...;
|
||||
*
|
||||
* end.seconds = start.seconds + duration.seconds;
|
||||
* end.nanos = start.nanos + duration.nanos;
|
||||
*
|
||||
* if (end.nanos < 0) {
|
||||
* end.seconds -= 1;
|
||||
* end.nanos += 1000000000;
|
||||
* } else if (end.nanos >= 1000000000) {
|
||||
* end.seconds += 1;
|
||||
* end.nanos -= 1000000000;
|
||||
* }
|
||||
*
|
||||
* Example 3: Compute Duration from datetime.timedelta in Python.
|
||||
*
|
||||
* td = datetime.timedelta(days=3, minutes=10)
|
||||
* duration = Duration()
|
||||
* duration.FromTimedelta(td)
|
||||
*
|
||||
* # JSON Mapping
|
||||
*
|
||||
* In JSON format, the Duration type is encoded as a string rather than an
|
||||
* object, where the string ends in the suffix "s" (indicating seconds) and
|
||||
* is preceded by the number of seconds, with nanoseconds expressed as
|
||||
* fractional seconds. For example, 3 seconds with 0 nanoseconds should be
|
||||
* encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
|
||||
* be expressed in JSON format as "3.000000001s", and 3 seconds and 1
|
||||
* microsecond should be expressed in JSON format as "3.000001s".
|
||||
*/
|
||||
export interface Duration {
|
||||
/**
|
||||
* Signed seconds of the span of time. Must be from -315,576,000,000
|
||||
* to +315,576,000,000 inclusive. Note: these bounds are computed from:
|
||||
* 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
|
||||
*/
|
||||
seconds: number;
|
||||
/**
|
||||
* Signed fractions of a second at nanosecond resolution of the span
|
||||
* of time. Durations less than one second are represented with a 0
|
||||
* `seconds` field and a positive or negative `nanos` field. For durations
|
||||
* of one second or more, a non-zero value for the `nanos` field must be
|
||||
* of the same sign as the `seconds` field. Must be from -999,999,999
|
||||
* to +999,999,999 inclusive.
|
||||
*/
|
||||
nanos: number;
|
||||
}
|
||||
|
||||
function createBaseDuration(): Duration {
|
||||
return { seconds: 0, nanos: 0 };
|
||||
}
|
||||
|
||||
export const Duration: MessageFns<Duration> = {
|
||||
encode(message: Duration, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
if (message.seconds !== 0) {
|
||||
writer.uint32(8).int64(message.seconds);
|
||||
}
|
||||
if (message.nanos !== 0) {
|
||||
writer.uint32(16).int32(message.nanos);
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): Duration {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
let end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseDuration();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 8) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.seconds = longToNumber(reader.int64());
|
||||
continue;
|
||||
}
|
||||
case 2: {
|
||||
if (tag !== 16) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.nanos = reader.int32();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
function longToNumber(int64: { toString(): string }): number {
|
||||
const num = globalThis.Number(int64.toString());
|
||||
if (num > globalThis.Number.MAX_SAFE_INTEGER) {
|
||||
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
|
||||
}
|
||||
if (num < globalThis.Number.MIN_SAFE_INTEGER) {
|
||||
throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
export interface MessageFns<T> {
|
||||
encode(message: T, writer?: BinaryWriter): BinaryWriter;
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): T;
|
||||
}
|
||||
53
aitimemachine/a2a/src/grpc/pb/google/protobuf/empty.ts
Normal file
53
aitimemachine/a2a/src/grpc/pb/google/protobuf/empty.ts
Normal file
@ -0,0 +1,53 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.6.1
|
||||
// protoc unknown
|
||||
// source: google/protobuf/empty.proto
|
||||
|
||||
/* eslint-disable */
|
||||
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
|
||||
|
||||
export const protobufPackage = "google.protobuf";
|
||||
|
||||
/**
|
||||
* A generic empty message that you can re-use to avoid defining duplicated
|
||||
* empty messages in your APIs. A typical example is to use it as the request
|
||||
* or the response type of an API method. For instance:
|
||||
*
|
||||
* service Foo {
|
||||
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
|
||||
* }
|
||||
*/
|
||||
export interface Empty {
|
||||
}
|
||||
|
||||
function createBaseEmpty(): Empty {
|
||||
return {};
|
||||
}
|
||||
|
||||
export const Empty: MessageFns<Empty> = {
|
||||
encode(_: Empty, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): Empty {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
let end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseEmpty();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
export interface MessageFns<T> {
|
||||
encode(message: T, writer?: BinaryWriter): BinaryWriter;
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): T;
|
||||
}
|
||||
384
aitimemachine/a2a/src/grpc/pb/google/protobuf/struct.ts
Normal file
384
aitimemachine/a2a/src/grpc/pb/google/protobuf/struct.ts
Normal file
@ -0,0 +1,384 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.6.1
|
||||
// protoc unknown
|
||||
// source: google/protobuf/struct.proto
|
||||
|
||||
/* eslint-disable */
|
||||
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
|
||||
|
||||
export const protobufPackage = "google.protobuf";
|
||||
|
||||
/**
|
||||
* `NullValue` is a singleton enumeration to represent the null value for the
|
||||
* `Value` type union.
|
||||
*
|
||||
* The JSON representation for `NullValue` is JSON `null`.
|
||||
*/
|
||||
export enum NullValue {
|
||||
/** NULL_VALUE - Null value. */
|
||||
NULL_VALUE = 0,
|
||||
UNRECOGNIZED = -1,
|
||||
}
|
||||
|
||||
/**
|
||||
* `Struct` represents a structured data value, consisting of fields
|
||||
* which map to dynamically typed values. In some languages, `Struct`
|
||||
* might be supported by a native representation. For example, in
|
||||
* scripting languages like JS a struct is represented as an
|
||||
* object. The details of that representation are described together
|
||||
* with the proto support for the language.
|
||||
*
|
||||
* The JSON representation for `Struct` is JSON object.
|
||||
*/
|
||||
export interface Struct {
|
||||
/** Unordered map of dynamically typed values. */
|
||||
fields: { [key: string]: any | undefined };
|
||||
}
|
||||
|
||||
export interface Struct_FieldsEntry {
|
||||
key: string;
|
||||
value: any | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* `Value` represents a dynamically typed value which can be either
|
||||
* null, a number, a string, a boolean, a recursive struct value, or a
|
||||
* list of values. A producer of value is expected to set one of these
|
||||
* variants. Absence of any variant indicates an error.
|
||||
*
|
||||
* The JSON representation for `Value` is JSON value.
|
||||
*/
|
||||
export interface Value {
|
||||
/** The kind of value. */
|
||||
kind?:
|
||||
| //
|
||||
/** Represents a null value. */
|
||||
{ $case: "nullValue"; value: NullValue }
|
||||
| //
|
||||
/** Represents a double value. */
|
||||
{ $case: "numberValue"; value: number }
|
||||
| //
|
||||
/** Represents a string value. */
|
||||
{ $case: "stringValue"; value: string }
|
||||
| //
|
||||
/** Represents a boolean value. */
|
||||
{ $case: "boolValue"; value: boolean }
|
||||
| //
|
||||
/** Represents a structured value. */
|
||||
{ $case: "structValue"; value: { [key: string]: any } | undefined }
|
||||
| //
|
||||
/** Represents a repeated `Value`. */
|
||||
{ $case: "listValue"; value: Array<any> | undefined }
|
||||
| undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* `ListValue` is a wrapper around a repeated field of values.
|
||||
*
|
||||
* The JSON representation for `ListValue` is JSON array.
|
||||
*/
|
||||
export interface ListValue {
|
||||
/** Repeated field of dynamically typed values. */
|
||||
values: any[];
|
||||
}
|
||||
|
||||
function createBaseStruct(): Struct {
|
||||
return { fields: {} };
|
||||
}
|
||||
|
||||
export const Struct: MessageFns<Struct> & StructWrapperFns = {
|
||||
encode(message: Struct, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
Object.entries(message.fields).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
Struct_FieldsEntry.encode({ key: key as any, value }, writer.uint32(10).fork()).join();
|
||||
}
|
||||
});
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): Struct {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
let end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseStruct();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 10) {
|
||||
break;
|
||||
}
|
||||
|
||||
const entry1 = Struct_FieldsEntry.decode(reader, reader.uint32());
|
||||
if (entry1.value !== undefined) {
|
||||
message.fields[entry1.key] = entry1.value;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
|
||||
wrap(object: { [key: string]: any } | undefined): Struct {
|
||||
const struct = createBaseStruct();
|
||||
|
||||
if (object !== undefined) {
|
||||
for (const key of Object.keys(object)) {
|
||||
struct.fields[key] = object[key];
|
||||
}
|
||||
}
|
||||
return struct;
|
||||
},
|
||||
|
||||
unwrap(message: Struct): { [key: string]: any } {
|
||||
const object: { [key: string]: any } = {};
|
||||
if (message.fields) {
|
||||
for (const key of Object.keys(message.fields)) {
|
||||
object[key] = message.fields[key];
|
||||
}
|
||||
}
|
||||
return object;
|
||||
},
|
||||
};
|
||||
|
||||
function createBaseStruct_FieldsEntry(): Struct_FieldsEntry {
|
||||
return { key: "", value: undefined };
|
||||
}
|
||||
|
||||
export const Struct_FieldsEntry: MessageFns<Struct_FieldsEntry> = {
|
||||
encode(message: Struct_FieldsEntry, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
if (message.key !== "") {
|
||||
writer.uint32(10).string(message.key);
|
||||
}
|
||||
if (message.value !== undefined) {
|
||||
Value.encode(Value.wrap(message.value), writer.uint32(18).fork()).join();
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): Struct_FieldsEntry {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
let end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseStruct_FieldsEntry();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 10) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.key = reader.string();
|
||||
continue;
|
||||
}
|
||||
case 2: {
|
||||
if (tag !== 18) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.value = Value.unwrap(Value.decode(reader, reader.uint32()));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
function createBaseValue(): Value {
|
||||
return { kind: undefined };
|
||||
}
|
||||
|
||||
export const Value: MessageFns<Value> & AnyValueWrapperFns = {
|
||||
encode(message: Value, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
switch (message.kind?.$case) {
|
||||
case "nullValue":
|
||||
writer.uint32(8).int32(message.kind.value);
|
||||
break;
|
||||
case "numberValue":
|
||||
writer.uint32(17).double(message.kind.value);
|
||||
break;
|
||||
case "stringValue":
|
||||
writer.uint32(26).string(message.kind.value);
|
||||
break;
|
||||
case "boolValue":
|
||||
writer.uint32(32).bool(message.kind.value);
|
||||
break;
|
||||
case "structValue":
|
||||
Struct.encode(Struct.wrap(message.kind.value), writer.uint32(42).fork()).join();
|
||||
break;
|
||||
case "listValue":
|
||||
ListValue.encode(ListValue.wrap(message.kind.value), writer.uint32(50).fork()).join();
|
||||
break;
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): Value {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
let end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseValue();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 8) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.kind = { $case: "nullValue", value: reader.int32() as any };
|
||||
continue;
|
||||
}
|
||||
case 2: {
|
||||
if (tag !== 17) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.kind = { $case: "numberValue", value: reader.double() };
|
||||
continue;
|
||||
}
|
||||
case 3: {
|
||||
if (tag !== 26) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.kind = { $case: "stringValue", value: reader.string() };
|
||||
continue;
|
||||
}
|
||||
case 4: {
|
||||
if (tag !== 32) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.kind = { $case: "boolValue", value: reader.bool() };
|
||||
continue;
|
||||
}
|
||||
case 5: {
|
||||
if (tag !== 42) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.kind = { $case: "structValue", value: Struct.unwrap(Struct.decode(reader, reader.uint32())) };
|
||||
continue;
|
||||
}
|
||||
case 6: {
|
||||
if (tag !== 50) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.kind = { $case: "listValue", value: ListValue.unwrap(ListValue.decode(reader, reader.uint32())) };
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
|
||||
wrap(value: any): Value {
|
||||
const result = createBaseValue();
|
||||
if (value === null) {
|
||||
result.kind = { $case: "nullValue", value };
|
||||
} else if (typeof value === "boolean") {
|
||||
result.kind = { $case: "boolValue", value };
|
||||
} else if (typeof value === "number") {
|
||||
result.kind = { $case: "numberValue", value };
|
||||
} else if (typeof value === "string") {
|
||||
result.kind = { $case: "stringValue", value };
|
||||
} else if (globalThis.Array.isArray(value)) {
|
||||
result.kind = { $case: "listValue", value };
|
||||
} else if (typeof value === "object") {
|
||||
result.kind = { $case: "structValue", value };
|
||||
} else if (typeof value !== "undefined") {
|
||||
throw new globalThis.Error("Unsupported any value type: " + typeof value);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
unwrap(message: Value): string | number | boolean | Object | null | Array<any> | undefined {
|
||||
return message.kind?.value;
|
||||
},
|
||||
};
|
||||
|
||||
function createBaseListValue(): ListValue {
|
||||
return { values: [] };
|
||||
}
|
||||
|
||||
export const ListValue: MessageFns<ListValue> & ListValueWrapperFns = {
|
||||
encode(message: ListValue, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
for (const v of message.values) {
|
||||
Value.encode(Value.wrap(v!), writer.uint32(10).fork()).join();
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): ListValue {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
let end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseListValue();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 10) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.values.push(Value.unwrap(Value.decode(reader, reader.uint32())));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
|
||||
wrap(array: Array<any> | undefined): ListValue {
|
||||
const result = createBaseListValue();
|
||||
result.values = array ?? [];
|
||||
return result;
|
||||
},
|
||||
|
||||
unwrap(message: ListValue): Array<any> {
|
||||
if (message?.hasOwnProperty("values") && globalThis.Array.isArray(message.values)) {
|
||||
return message.values;
|
||||
} else {
|
||||
return message as any;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export interface MessageFns<T> {
|
||||
encode(message: T, writer?: BinaryWriter): BinaryWriter;
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): T;
|
||||
}
|
||||
|
||||
export interface StructWrapperFns {
|
||||
wrap(object: { [key: string]: any } | undefined): Struct;
|
||||
unwrap(message: Struct): { [key: string]: any };
|
||||
}
|
||||
|
||||
export interface AnyValueWrapperFns {
|
||||
wrap(value: any): Value;
|
||||
unwrap(message: any): string | number | boolean | Object | null | Array<any> | undefined;
|
||||
}
|
||||
|
||||
export interface ListValueWrapperFns {
|
||||
wrap(array: Array<any> | undefined): ListValue;
|
||||
unwrap(message: ListValue): Array<any>;
|
||||
}
|
||||
181
aitimemachine/a2a/src/grpc/pb/google/protobuf/timestamp.ts
Normal file
181
aitimemachine/a2a/src/grpc/pb/google/protobuf/timestamp.ts
Normal file
@ -0,0 +1,181 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.6.1
|
||||
// protoc unknown
|
||||
// source: google/protobuf/timestamp.proto
|
||||
|
||||
/* eslint-disable */
|
||||
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
|
||||
|
||||
export const protobufPackage = "google.protobuf";
|
||||
|
||||
/**
|
||||
* A Timestamp represents a point in time independent of any time zone or local
|
||||
* calendar, encoded as a count of seconds and fractions of seconds at
|
||||
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
|
||||
* January 1, 1970, in the proleptic Gregorian calendar which extends the
|
||||
* Gregorian calendar backwards to year one.
|
||||
*
|
||||
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
|
||||
* second table is needed for interpretation, using a [24-hour linear
|
||||
* smear](https://developers.google.com/time/smear).
|
||||
*
|
||||
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
|
||||
* restricting to that range, we ensure that we can convert to and from [RFC
|
||||
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
|
||||
*
|
||||
* # Examples
|
||||
*
|
||||
* Example 1: Compute Timestamp from POSIX `time()`.
|
||||
*
|
||||
* Timestamp timestamp;
|
||||
* timestamp.set_seconds(time(NULL));
|
||||
* timestamp.set_nanos(0);
|
||||
*
|
||||
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
|
||||
*
|
||||
* struct timeval tv;
|
||||
* gettimeofday(&tv, NULL);
|
||||
*
|
||||
* Timestamp timestamp;
|
||||
* timestamp.set_seconds(tv.tv_sec);
|
||||
* timestamp.set_nanos(tv.tv_usec * 1000);
|
||||
*
|
||||
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
|
||||
*
|
||||
* FILETIME ft;
|
||||
* GetSystemTimeAsFileTime(&ft);
|
||||
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
|
||||
*
|
||||
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
|
||||
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
|
||||
* Timestamp timestamp;
|
||||
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
|
||||
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
|
||||
*
|
||||
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
|
||||
*
|
||||
* long millis = System.currentTimeMillis();
|
||||
*
|
||||
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
|
||||
* .setNanos((int) ((millis % 1000) * 1000000)).build();
|
||||
*
|
||||
* Example 5: Compute Timestamp from Java `Instant.now()`.
|
||||
*
|
||||
* Instant now = Instant.now();
|
||||
*
|
||||
* Timestamp timestamp =
|
||||
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
|
||||
* .setNanos(now.getNano()).build();
|
||||
*
|
||||
* Example 6: Compute Timestamp from current time in Python.
|
||||
*
|
||||
* timestamp = Timestamp()
|
||||
* timestamp.GetCurrentTime()
|
||||
*
|
||||
* # JSON Mapping
|
||||
*
|
||||
* In JSON format, the Timestamp type is encoded as a string in the
|
||||
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
|
||||
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
|
||||
* where {year} is always expressed using four digits while {month}, {day},
|
||||
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
|
||||
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
|
||||
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
|
||||
* is required. A proto3 JSON serializer should always use UTC (as indicated by
|
||||
* "Z") when printing the Timestamp type and a proto3 JSON parser should be
|
||||
* able to accept both UTC and other timezones (as indicated by an offset).
|
||||
*
|
||||
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
|
||||
* 01:30 UTC on January 15, 2017.
|
||||
*
|
||||
* In JavaScript, one can convert a Date object to this format using the
|
||||
* standard
|
||||
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
|
||||
* method. In Python, a standard `datetime.datetime` object can be converted
|
||||
* to this format using
|
||||
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
|
||||
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
|
||||
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
|
||||
* http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
|
||||
* ) to obtain a formatter capable of generating timestamps in this format.
|
||||
*/
|
||||
export interface Timestamp {
|
||||
/**
|
||||
* Represents seconds of UTC time since Unix epoch
|
||||
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
|
||||
* 9999-12-31T23:59:59Z inclusive.
|
||||
*/
|
||||
seconds: number;
|
||||
/**
|
||||
* Non-negative fractions of a second at nanosecond resolution. Negative
|
||||
* second values with fractions must still have non-negative nanos values
|
||||
* that count forward in time. Must be from 0 to 999,999,999
|
||||
* inclusive.
|
||||
*/
|
||||
nanos: number;
|
||||
}
|
||||
|
||||
function createBaseTimestamp(): Timestamp {
|
||||
return { seconds: 0, nanos: 0 };
|
||||
}
|
||||
|
||||
export const Timestamp: MessageFns<Timestamp> = {
|
||||
encode(message: Timestamp, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
if (message.seconds !== 0) {
|
||||
writer.uint32(8).int64(message.seconds);
|
||||
}
|
||||
if (message.nanos !== 0) {
|
||||
writer.uint32(16).int32(message.nanos);
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): Timestamp {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
let end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseTimestamp();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 8) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.seconds = longToNumber(reader.int64());
|
||||
continue;
|
||||
}
|
||||
case 2: {
|
||||
if (tag !== 16) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.nanos = reader.int32();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
function longToNumber(int64: { toString(): string }): number {
|
||||
const num = globalThis.Number(int64.toString());
|
||||
if (num > globalThis.Number.MAX_SAFE_INTEGER) {
|
||||
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
|
||||
}
|
||||
if (num < globalThis.Number.MIN_SAFE_INTEGER) {
|
||||
throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
export interface MessageFns<T> {
|
||||
encode(message: T, writer?: BinaryWriter): BinaryWriter;
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): T;
|
||||
}
|
||||
11
aitimemachine/a2a/src/index.ts
Normal file
11
aitimemachine/a2a/src/index.ts
Normal file
@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Exports the common types.
|
||||
*
|
||||
* Use the client/index.ts file to import the client-only codebase.
|
||||
* Use the server/index.ts file to import the server-only codebase.
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export type { A2AResponse } from './a2a_response.js';
|
||||
export { AGENT_CARD_PATH, HTTP_EXTENSION_HEADER } from './constants.js';
|
||||
export { Extensions, type ExtensionURI } from './extensions.js';
|
||||
11
aitimemachine/a2a/src/samples/agents/movie-agent/README.md
Normal file
11
aitimemachine/a2a/src/samples/agents/movie-agent/README.md
Normal file
@ -0,0 +1,11 @@
|
||||
# Movie Info Agent
|
||||
|
||||
This agent uses the TMDB API to answer questions about movies. To run:
|
||||
|
||||
```bash
|
||||
export TMDB_API_KEY=<api_key> # see https://developer.themoviedb.org/docs/getting-started
|
||||
export GEMINI_API_KEY=<api_key>
|
||||
npm run agents:movie-agent
|
||||
```
|
||||
|
||||
The agent will start on `http://localhost:41241`.
|
||||
12
aitimemachine/a2a/src/samples/agents/movie-agent/genkit.ts
Normal file
12
aitimemachine/a2a/src/samples/agents/movie-agent/genkit.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { googleAI } from '@genkit-ai/googleai';
|
||||
import { genkit } from 'genkit';
|
||||
import { dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
export const ai = genkit({
|
||||
plugins: [googleAI()],
|
||||
model: googleAI.model('gemini-2.0-flash'),
|
||||
promptDir: dirname(fileURLToPath(import.meta.url)),
|
||||
});
|
||||
|
||||
export { z } from 'genkit';
|
||||
339
aitimemachine/a2a/src/samples/agents/movie-agent/index.ts
Normal file
339
aitimemachine/a2a/src/samples/agents/movie-agent/index.ts
Normal file
@ -0,0 +1,339 @@
|
||||
import express from 'express';
|
||||
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
|
||||
|
||||
import {
|
||||
AgentCard,
|
||||
Task,
|
||||
TaskState,
|
||||
TaskStatusUpdateEvent,
|
||||
TextPart,
|
||||
Message,
|
||||
AGENT_CARD_PATH,
|
||||
TaskArtifactUpdateEvent,
|
||||
Artifact,
|
||||
Part,
|
||||
} from '../../../index.js';
|
||||
import {
|
||||
InMemoryTaskStore,
|
||||
TaskStore,
|
||||
AgentExecutor,
|
||||
RequestContext,
|
||||
ExecutionEventBus,
|
||||
DefaultRequestHandler,
|
||||
} from '../../../server/index.js';
|
||||
import { agentCardHandler, jsonRpcHandler, UserBuilder } from '../../../server/express/index.js';
|
||||
import { MessageData } from 'genkit';
|
||||
import { ai } from './genkit.js';
|
||||
import { searchMovies, searchPeople } from './tools.js';
|
||||
|
||||
if (!process.env.GEMINI_API_KEY || !process.env.TMDB_API_KEY) {
|
||||
console.error('GEMINI_API_KEY and TMDB_API_KEY environment variables are required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Simple store for contexts
|
||||
const contexts: Map<string, Message[]> = new Map();
|
||||
|
||||
// Load the Genkit prompt
|
||||
const movieAgentPrompt = ai.prompt('movie_agent');
|
||||
|
||||
/**
|
||||
* MovieAgentExecutor implements the agent's core logic.
|
||||
*/
|
||||
class MovieAgentExecutor implements AgentExecutor {
|
||||
private cancelledTasks = new Set<string>();
|
||||
|
||||
public cancelTask = async (taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {
|
||||
this.cancelledTasks.add(taskId);
|
||||
// The execute loop is responsible for publishing the final state
|
||||
};
|
||||
|
||||
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
const userMessage = requestContext.userMessage;
|
||||
const existingTask = requestContext.task;
|
||||
|
||||
// Determine IDs for the task and context
|
||||
const taskId = requestContext.taskId;
|
||||
const contextId = requestContext.contextId;
|
||||
|
||||
console.log(
|
||||
`[MovieAgentExecutor] Processing message ${userMessage.messageId} for task ${taskId} (context: ${contextId})`
|
||||
);
|
||||
|
||||
// 1. Publish initial Task event if it's a new task
|
||||
if (!existingTask) {
|
||||
const initialTask: Task = {
|
||||
kind: 'task',
|
||||
id: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'submitted',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
history: [userMessage], // Start history with the current user message
|
||||
metadata: userMessage.metadata, // Carry over metadata from message if any
|
||||
};
|
||||
eventBus.publish(initialTask);
|
||||
}
|
||||
|
||||
// 2. Publish "working" status update
|
||||
const workingStatusUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'working',
|
||||
message: {
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [{ kind: 'text', text: 'Processing your question, hang tight!' }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
final: false,
|
||||
};
|
||||
eventBus.publish(workingStatusUpdate);
|
||||
|
||||
// 3. Prepare messages for Genkit prompt
|
||||
const historyForGenkit = contexts.get(contextId) || [];
|
||||
if (!historyForGenkit.find((m) => m.messageId === userMessage.messageId)) {
|
||||
historyForGenkit.push(userMessage);
|
||||
}
|
||||
contexts.set(contextId, historyForGenkit);
|
||||
|
||||
const messages: MessageData[] = historyForGenkit
|
||||
.map((m) => ({
|
||||
role: (m.role === 'agent' ? 'model' : 'user') as 'user' | 'model',
|
||||
content: m.parts
|
||||
.filter((p): p is TextPart => p.kind === 'text' && !!(p as TextPart).text)
|
||||
.map((p) => ({
|
||||
text: (p as TextPart).text,
|
||||
})),
|
||||
}))
|
||||
.filter((m) => m.content.length > 0);
|
||||
|
||||
if (messages.length === 0) {
|
||||
console.warn(
|
||||
`[MovieAgentExecutor] No valid text messages found in history for task ${taskId}.`
|
||||
);
|
||||
const failureUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'failed',
|
||||
message: {
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [{ kind: 'text', text: 'No message found to process.' }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(failureUpdate);
|
||||
return;
|
||||
}
|
||||
|
||||
const goal =
|
||||
(existingTask?.metadata?.goal as string | undefined) ||
|
||||
(userMessage.metadata?.goal as string | undefined);
|
||||
|
||||
try {
|
||||
// 4. Run the Genkit prompt
|
||||
const response = await movieAgentPrompt(
|
||||
{ goal: goal, now: new Date().toISOString() },
|
||||
{
|
||||
messages,
|
||||
tools: [searchMovies, searchPeople],
|
||||
}
|
||||
);
|
||||
|
||||
// Check if the request has been cancelled
|
||||
if (this.cancelledTasks.has(taskId)) {
|
||||
console.log(`[MovieAgentExecutor] Request cancelled for task: ${taskId}`);
|
||||
|
||||
const cancelledUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'canceled',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
final: true, // Cancellation is a final state
|
||||
};
|
||||
eventBus.publish(cancelledUpdate);
|
||||
return;
|
||||
}
|
||||
|
||||
const responseText = response.text; // Access the text property using .text()
|
||||
console.info(`[MovieAgentExecutor] Prompt response: ${responseText}`);
|
||||
const lines = responseText.trim().split('\n');
|
||||
const finalStateLine = lines.at(-1)?.trim().toUpperCase();
|
||||
const agentReplyText = lines
|
||||
.slice(0, lines.length - 1)
|
||||
.join('\n')
|
||||
.trim();
|
||||
|
||||
let finalA2AState: TaskState = 'unknown';
|
||||
|
||||
if (finalStateLine === 'COMPLETED') {
|
||||
finalA2AState = 'completed';
|
||||
} else if (finalStateLine === 'AWAITING_USER_INPUT') {
|
||||
finalA2AState = 'input-required';
|
||||
} else {
|
||||
console.warn(
|
||||
`[MovieAgentExecutor] Unexpected final state line from prompt: ${finalStateLine}. Defaulting to 'completed'.`
|
||||
);
|
||||
finalA2AState = 'completed'; // Default if LLM deviates
|
||||
}
|
||||
|
||||
// 5. Publish artifact with the result
|
||||
const parts: Part[] = [{ kind: 'text', text: agentReplyText || 'Completed.' }];
|
||||
const artifactId = uuidv4();
|
||||
const resultArtifact: Artifact = {
|
||||
artifactId: artifactId,
|
||||
name: 'Result',
|
||||
description: 'The result of the movie agent.',
|
||||
parts: parts,
|
||||
};
|
||||
|
||||
const artifactUpdate: TaskArtifactUpdateEvent = {
|
||||
kind: 'artifact-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
artifact: resultArtifact,
|
||||
lastChunk: true,
|
||||
};
|
||||
eventBus.publish(artifactUpdate);
|
||||
|
||||
// 6. Update local history context (internal only)
|
||||
const agentMessage: Message = {
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: parts,
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
};
|
||||
historyForGenkit.push(agentMessage);
|
||||
contexts.set(contextId, historyForGenkit);
|
||||
|
||||
// 7. Publish final task status update
|
||||
const finalUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: finalA2AState,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(finalUpdate);
|
||||
|
||||
console.log(`[MovieAgentExecutor] Task ${taskId} finished with state: ${finalA2AState}`);
|
||||
} catch (error: any) {
|
||||
console.error(`[MovieAgentExecutor] Error processing task ${taskId}:`, error);
|
||||
const errorUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'failed',
|
||||
message: {
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [{ kind: 'text', text: `Agent error: ${error.message}` }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(errorUpdate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Server Setup ---
|
||||
|
||||
const movieAgentCard: AgentCard = {
|
||||
name: 'Movie Agent',
|
||||
description: 'An agent that can answer questions about movies and actors using TMDB.',
|
||||
url: 'http://localhost:41241/',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples', // Added provider URL
|
||||
},
|
||||
version: '0.0.2', // Incremented version
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
streaming: true, // The new framework supports streaming
|
||||
pushNotifications: false, // Assuming not implemented for this agent yet
|
||||
stateTransitionHistory: true, // Agent uses history
|
||||
},
|
||||
// authentication: null, // Property 'authentication' does not exist on type 'AgentCard'.
|
||||
securitySchemes: undefined, // Or define actual security schemes if any
|
||||
security: undefined,
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text', 'task-status'], // task-status is a common output mode
|
||||
skills: [
|
||||
{
|
||||
id: 'general_movie_chat',
|
||||
name: 'General Movie Chat',
|
||||
description: 'Answer general questions or chat about movies, actors, directors.',
|
||||
tags: ['movies', 'actors', 'directors'],
|
||||
examples: [
|
||||
'Tell me about the plot of Inception.',
|
||||
'Recommend a good sci-fi movie.',
|
||||
'Who directed The Matrix?',
|
||||
'What other movies has Scarlett Johansson been in?',
|
||||
'Find action movies starring Keanu Reeves',
|
||||
'Which came out first, Jurassic Park or Terminator 2?',
|
||||
],
|
||||
inputModes: ['text'], // Explicitly defining for skill
|
||||
outputModes: ['text', 'task-status'], // Explicitly defining for skill
|
||||
},
|
||||
],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// 1. Create TaskStore
|
||||
const taskStore: TaskStore = new InMemoryTaskStore();
|
||||
|
||||
// 2. Create AgentExecutor
|
||||
const agentExecutor: AgentExecutor = new MovieAgentExecutor();
|
||||
|
||||
// 3. Create DefaultRequestHandler
|
||||
const requestHandler = new DefaultRequestHandler(movieAgentCard, taskStore, agentExecutor);
|
||||
|
||||
// 4. Create and setup Express.js app
|
||||
const app = express();
|
||||
|
||||
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
|
||||
app.use(jsonRpcHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
|
||||
|
||||
// 5. Start the server
|
||||
const PORT = process.env.PORT || 41241;
|
||||
app.listen(PORT, (err) => {
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
console.log(`[MovieAgent] Server using new framework started on http://localhost:${PORT}`);
|
||||
console.log(`[MovieAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`);
|
||||
console.log('[MovieAgent] Press Ctrl+C to stop the server');
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@ -0,0 +1,22 @@
|
||||
{{role "system"}}
|
||||
You are a movie expert. Answer the user's question about movies and film industry personalities, using the searchMovies and searchPeople tools to find out more information as needed. Feel free to call them multiple times in parallel if necessary.{{#if goal}}
|
||||
|
||||
Your goal in this task is: {{goal}}{{/if}}
|
||||
|
||||
The current date and time is: {{now}}
|
||||
|
||||
If the user asks you for specific information about a movie or person (such as the plot or a specific role an actor played), do a search for that movie/actor using the available functions before responding.
|
||||
|
||||
## Output Instructions
|
||||
|
||||
ALWAYS end your response with either "COMPLETED" or "AWAITING_USER_INPUT" on its own line. If you have answered the user's question, use COMPLETED. If you need more information to answer the question, use AWAITING_USER_INPUT.
|
||||
|
||||
<example>
|
||||
<question>
|
||||
when was [some_movie] released?
|
||||
</question>
|
||||
<output>
|
||||
[some_movie] was released on October 3, 1992.
|
||||
COMPLETED
|
||||
</output>
|
||||
</example>
|
||||
34
aitimemachine/a2a/src/samples/agents/movie-agent/tmdb.ts
Normal file
34
aitimemachine/a2a/src/samples/agents/movie-agent/tmdb.ts
Normal file
@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Utility function to call the TMDB API
|
||||
* @param endpoint The TMDB API endpoint (e.g., 'movie', 'person')
|
||||
* @param query The search query
|
||||
* @returns Promise that resolves to the API response data
|
||||
*/
|
||||
export async function callTmdbApi(endpoint: string, query: string) {
|
||||
// Validate API key
|
||||
const apiKey = process.env.TMDB_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error('TMDB_API_KEY environment variable is not set');
|
||||
}
|
||||
|
||||
try {
|
||||
// Make request to TMDB API
|
||||
const url = new URL(`https://api.themoviedb.org/3/search/${endpoint}`);
|
||||
url.searchParams.append('api_key', apiKey);
|
||||
url.searchParams.append('query', query);
|
||||
url.searchParams.append('include_adult', 'false');
|
||||
url.searchParams.append('language', 'en-US');
|
||||
url.searchParams.append('page', '1');
|
||||
|
||||
const response = await fetch(url.toString());
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`TMDB API error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`Error calling TMDB API (${endpoint}):`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
85
aitimemachine/a2a/src/samples/agents/movie-agent/tools.ts
Normal file
85
aitimemachine/a2a/src/samples/agents/movie-agent/tools.ts
Normal file
@ -0,0 +1,85 @@
|
||||
import { ai, z } from './genkit.js';
|
||||
import { callTmdbApi } from './tmdb.js';
|
||||
|
||||
export const searchMovies = ai.defineTool(
|
||||
{
|
||||
name: 'searchMovies',
|
||||
description: 'search TMDB for movies by title',
|
||||
inputSchema: z.object({
|
||||
query: z.string(),
|
||||
}),
|
||||
},
|
||||
async ({ query }) => {
|
||||
console.log('[tmdb:searchMovies]', JSON.stringify(query));
|
||||
try {
|
||||
const data = await callTmdbApi('movie', query);
|
||||
|
||||
// Only modify image paths to be full URLs
|
||||
const results = data.results.map((movie: any) => {
|
||||
if (movie.poster_path) {
|
||||
movie.poster_path = `https://image.tmdb.org/t/p/w500${movie.poster_path}`;
|
||||
}
|
||||
if (movie.backdrop_path) {
|
||||
movie.backdrop_path = `https://image.tmdb.org/t/p/w500${movie.backdrop_path}`;
|
||||
}
|
||||
return movie;
|
||||
});
|
||||
|
||||
return {
|
||||
...data,
|
||||
results,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error searching movies:', error);
|
||||
// Re-throwing allows Genkit/the caller to handle it appropriately
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export const searchPeople = ai.defineTool(
|
||||
{
|
||||
name: 'searchPeople',
|
||||
description: 'search TMDB for people by name',
|
||||
inputSchema: z.object({
|
||||
query: z.string(),
|
||||
}),
|
||||
},
|
||||
async ({ query }) => {
|
||||
console.log('[tmdb:searchPeople]', JSON.stringify(query));
|
||||
try {
|
||||
const data = await callTmdbApi('person', query);
|
||||
|
||||
// Only modify image paths to be full URLs
|
||||
const results = data.results.map((person: any) => {
|
||||
if (person.profile_path) {
|
||||
person.profile_path = `https://image.tmdb.org/t/p/w500${person.profile_path}`;
|
||||
}
|
||||
|
||||
// Also modify poster paths in known_for works
|
||||
if (person.known_for && Array.isArray(person.known_for)) {
|
||||
person.known_for = person.known_for.map((work: any) => {
|
||||
if (work.poster_path) {
|
||||
work.poster_path = `https://image.tmdb.org/t/p/w500${work.poster_path}`;
|
||||
}
|
||||
if (work.backdrop_path) {
|
||||
work.backdrop_path = `https://image.tmdb.org/t/p/w500${work.backdrop_path}`;
|
||||
}
|
||||
return work;
|
||||
});
|
||||
}
|
||||
|
||||
return person;
|
||||
});
|
||||
|
||||
return {
|
||||
...data,
|
||||
results,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error searching people:', error);
|
||||
// Re-throwing allows Genkit/the caller to handle it appropriately
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
);
|
||||
@ -0,0 +1,9 @@
|
||||
# Sample Agent
|
||||
|
||||
This agent is a sample to emulate the task flow in a streaming scenario. To run:
|
||||
|
||||
```bash
|
||||
npm run agents:sample-agent
|
||||
```
|
||||
|
||||
The agent will start on `http://localhost:41241`.
|
||||
@ -0,0 +1,126 @@
|
||||
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
|
||||
|
||||
import {
|
||||
Task,
|
||||
TaskStatusUpdateEvent,
|
||||
Message,
|
||||
TaskArtifactUpdateEvent,
|
||||
Artifact,
|
||||
} from '../../../index.js';
|
||||
import { AgentExecutor, RequestContext, ExecutionEventBus } from '../../../server/index.js';
|
||||
|
||||
/**
|
||||
* SampleAgentExecutor implements the agent's core logic.
|
||||
*/
|
||||
export class SampleAgentExecutor implements AgentExecutor {
|
||||
public cancelTask = async (_taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {};
|
||||
|
||||
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
const userMessage = requestContext.userMessage;
|
||||
const existingTask = requestContext.task;
|
||||
|
||||
// Determine IDs for the task and context
|
||||
const taskId = requestContext.taskId;
|
||||
const contextId = requestContext.contextId;
|
||||
|
||||
console.log(
|
||||
`[SampleAgentExecutor] Processing message ${userMessage.messageId} for task ${taskId} (context: ${contextId})`
|
||||
);
|
||||
|
||||
// 1. Publish initial Task event if it's a new task
|
||||
if (!existingTask) {
|
||||
const initialTask: Task = {
|
||||
kind: 'task',
|
||||
id: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'submitted',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
history: [userMessage], // Start history with the current user message
|
||||
metadata: userMessage.metadata, // Carry over metadata from message if any
|
||||
};
|
||||
eventBus.publish(initialTask);
|
||||
}
|
||||
|
||||
// 2. Publish "working" status update
|
||||
const workingStatusUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'working',
|
||||
message: {
|
||||
kind: 'message',
|
||||
role: 'agent',
|
||||
messageId: uuidv4(),
|
||||
parts: [{ kind: 'text', text: 'Processing your question' }],
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
final: false,
|
||||
};
|
||||
eventBus.publish(workingStatusUpdate);
|
||||
|
||||
// 3. Publish artifact with the result
|
||||
const agentReplyText = this.parseInputMessage(userMessage);
|
||||
console.info(`[SampleAgentExecutor] Prompt response: ${agentReplyText}`);
|
||||
|
||||
const artifactId = uuidv4();
|
||||
const resultArtifact: Artifact = {
|
||||
artifactId: artifactId,
|
||||
name: 'Result',
|
||||
description: 'The final result from the agent.',
|
||||
parts: [{ kind: 'text', text: agentReplyText }],
|
||||
};
|
||||
|
||||
const artifactUpdate: TaskArtifactUpdateEvent = {
|
||||
kind: 'artifact-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
artifact: resultArtifact,
|
||||
lastChunk: true,
|
||||
};
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate processing delay
|
||||
eventBus.publish(artifactUpdate);
|
||||
|
||||
// 4. Publish final task status update (completed, no message)
|
||||
const finalUpdate: TaskStatusUpdateEvent = {
|
||||
kind: 'status-update',
|
||||
taskId: taskId,
|
||||
contextId: contextId,
|
||||
status: {
|
||||
state: 'completed',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
final: true,
|
||||
};
|
||||
eventBus.publish(finalUpdate);
|
||||
|
||||
console.log(`[SampleAgentExecutor] Task ${taskId} finished with state: completed`);
|
||||
}
|
||||
|
||||
parseInputMessage(message: Message): string {
|
||||
/** Process the user query and return a response. */
|
||||
const textPart = message.parts.find((part) => part.kind === 'text');
|
||||
const query = textPart ? textPart.text.trim() : '';
|
||||
|
||||
if (!query) {
|
||||
return 'Hello! Please provide a message for me to respond to.';
|
||||
}
|
||||
|
||||
// Simple responses based on input
|
||||
const queryLower = query.toLowerCase();
|
||||
if (queryLower.includes('hello') || queryLower.includes('hi')) {
|
||||
return 'Hello World! Nice to meet you!';
|
||||
} else if (queryLower.includes('how are you')) {
|
||||
return "I'm doing great! Thanks for asking. How can I help you today?";
|
||||
} else if (queryLower.includes('goodbye') || queryLower.includes('bye')) {
|
||||
return 'Goodbye! Have a wonderful day!';
|
||||
} else {
|
||||
return `Hello World! You said: '${query}'. Thanks for your message!`;
|
||||
}
|
||||
}
|
||||
}
|
||||
74
aitimemachine/a2a/src/samples/agents/sample-agent/index.ts
Normal file
74
aitimemachine/a2a/src/samples/agents/sample-agent/index.ts
Normal file
@ -0,0 +1,74 @@
|
||||
import express from 'express';
|
||||
import { AgentCard, AGENT_CARD_PATH } from '../../../index.js';
|
||||
import {
|
||||
InMemoryTaskStore,
|
||||
TaskStore,
|
||||
AgentExecutor,
|
||||
DefaultRequestHandler,
|
||||
} from '../../../server/index.js';
|
||||
import { agentCardHandler, jsonRpcHandler, UserBuilder } from '../../../server/express/index.js';
|
||||
import { SampleAgentExecutor } from './agent_executor.js';
|
||||
|
||||
// --- Server Setup ---
|
||||
|
||||
const sampleAgentCard: AgentCard = {
|
||||
name: 'Sample Agent',
|
||||
description:
|
||||
'A sample agent to test the stream functionality and simulate the flow of tasks statuses.',
|
||||
url: 'http://localhost:41241/',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples', // Added provider URL
|
||||
},
|
||||
version: '1.0.0', // Incremented version
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
streaming: true, // The new framework supports streaming
|
||||
pushNotifications: false, // Assuming not implemented for this agent yet
|
||||
stateTransitionHistory: true, // Agent uses history
|
||||
},
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text', 'task-status'], // task-status is a common output mode
|
||||
skills: [
|
||||
{
|
||||
id: 'sample_agent',
|
||||
name: 'Sample Agent',
|
||||
description: 'Simulate the general flow of a streaming agent.',
|
||||
tags: ['sample'],
|
||||
examples: ['hi', 'hello world', 'how are you', 'goodbye'],
|
||||
inputModes: ['text'], // Explicitly defining for skill
|
||||
outputModes: ['text', 'task-status'], // Explicitly defining for skill
|
||||
},
|
||||
],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// 1. Create TaskStore
|
||||
const taskStore: TaskStore = new InMemoryTaskStore();
|
||||
|
||||
// 2. Create AgentExecutor
|
||||
const agentExecutor: AgentExecutor = new SampleAgentExecutor();
|
||||
|
||||
// 3. Create DefaultRequestHandler
|
||||
const requestHandler = new DefaultRequestHandler(sampleAgentCard, taskStore, agentExecutor);
|
||||
|
||||
// 4. Create and setup Express app
|
||||
const app = express();
|
||||
|
||||
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
|
||||
app.use(jsonRpcHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
|
||||
|
||||
// 5. Start the server
|
||||
const PORT = process.env.PORT || 41241;
|
||||
app.listen(PORT, (err) => {
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
console.log(`[SampleAgent] Server using new framework started on http://localhost:${PORT}`);
|
||||
console.log(`[SampleAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`);
|
||||
console.log('[SampleAgent] Press Ctrl+C to stop the server');
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
80
aitimemachine/a2a/src/samples/authentication/README.md
Normal file
80
aitimemachine/a2a/src/samples/authentication/README.md
Normal file
@ -0,0 +1,80 @@
|
||||
# Authentication Sample
|
||||
|
||||
This sample demonstrates how to implement **Bearer Token authentication**. It shows how to intercept requests, validate tokens, extract the user generated by the authentication and pass it to the context.
|
||||
|
||||
|
||||
## Key Components
|
||||
|
||||
- `index.ts`: generates an `AgentCard` that requires for the Bearer authentication for incoming requests and starts the server with the authentication middleware and user builder.
|
||||
- `authentication_middleware.ts`: creates the middleware responsible for authentication. It uses Passport to support Bearer token authorization and populates the `user` parameter in the Request object with the plain extracted object.
|
||||
- `user_builder.ts`: defines the callback for the user extraction. It expects the user object (populated by the middleware) to contain specific values (`email`, `userName`, `role`) which are used to build the `CustomUser` object.
|
||||
- `agent_executor.ts`: creates a simple agent executor that checks the authentication status of the user object present in the context, which is expected to be an instance of `CustomUser` in case of successful authentication, and sends back the content.
|
||||
|
||||
|
||||
To test the agent:
|
||||
|
||||
```bash
|
||||
npm run agents:authentication-agent
|
||||
```
|
||||
|
||||
The agent will start on `http://localhost:41241`.
|
||||
|
||||
Use this [tool](https://www.jwt.io/) to generate your Json Web Token with the JWT Encoder. The secret key for the signature is `a2a-secret-for-authentication-sample`.
|
||||
For a successful authentication the payload data MUST contain these values: "email", "userName", "role".
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:41241/
|
||||
-H "Authorization: Bearer <jwt-token>"
|
||||
-H "Content-Type: application/json"
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "message/send",
|
||||
"params": {
|
||||
"message": {
|
||||
"role": "user",
|
||||
"parts": [
|
||||
{
|
||||
"kind": "text",
|
||||
"text": "Hello, who am i?"
|
||||
}
|
||||
],
|
||||
"messageId": "9229e770-767c-417b-a0b0-f0741243c589"
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
Expected response, with successful authentication:
|
||||
```json
|
||||
{
|
||||
"jsonrpc":"2.0",
|
||||
"id":1,
|
||||
"result": {
|
||||
"kind":"message",
|
||||
"role":"agent",
|
||||
"parts":[ {
|
||||
"kind":"text",
|
||||
"text":"The request is coming from the authenticated user <your-userName>, with email <your-email> and role <your-role>."
|
||||
} ]
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Expected response, with failed authentication:
|
||||
```json
|
||||
{
|
||||
"jsonrpc":"2.0",
|
||||
"id":1,
|
||||
"result": {
|
||||
"kind":"message",
|
||||
"role":"agent",
|
||||
"parts":[ {
|
||||
"kind":"text",
|
||||
"text":"The request is not coming from an authenticated user."
|
||||
} ]
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
@ -0,0 +1,28 @@
|
||||
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
|
||||
import { AgentExecutor, ExecutionEventBus, RequestContext } from '../../server/index.js';
|
||||
import { CustomUser } from './user_builder.js';
|
||||
import { Message } from '../../types.js';
|
||||
|
||||
export class AuthenticationAgentExecutor implements AgentExecutor {
|
||||
public cancelTask = async (_taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {};
|
||||
|
||||
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
|
||||
let finalText;
|
||||
if (
|
||||
requestContext.context?.user?.isAuthenticated &&
|
||||
requestContext.context.user instanceof CustomUser
|
||||
) {
|
||||
const customUser = requestContext.context.user;
|
||||
finalText = `The request is coming from the authenticated user ${customUser.userName}, with email ${customUser.email} and role ${customUser.role}.`;
|
||||
} else {
|
||||
finalText = `The request is not coming from an authenticated user.`;
|
||||
}
|
||||
const finalMessage: Message = {
|
||||
kind: 'message',
|
||||
messageId: uuidv4(),
|
||||
role: 'agent',
|
||||
parts: [{ kind: 'text', text: finalText }],
|
||||
};
|
||||
eventBus.publish(finalMessage);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
import { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
import passport from 'passport';
|
||||
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
|
||||
|
||||
passport.use(
|
||||
new JwtStrategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: 'a2a-secret-for-authentication-sample',
|
||||
},
|
||||
(jwt_payload, done) => {
|
||||
return done(null, jwt_payload);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const authenticationHandler: RequestHandler = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
passport.authenticate('jwt', { session: false }, (err: any, user: any) => {
|
||||
if (err) {
|
||||
return next(err);
|
||||
}
|
||||
if (user) {
|
||||
req.user = user;
|
||||
}
|
||||
next();
|
||||
})(req, res, next);
|
||||
};
|
||||
88
aitimemachine/a2a/src/samples/authentication/index.ts
Normal file
88
aitimemachine/a2a/src/samples/authentication/index.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import express from 'express';
|
||||
import { AgentCard } from '../../index.js';
|
||||
import {
|
||||
InMemoryTaskStore,
|
||||
TaskStore,
|
||||
AgentExecutor,
|
||||
DefaultRequestHandler,
|
||||
} from '../../server/index.js';
|
||||
import { jsonRpcHandler } from '../../server/express/index.js';
|
||||
import { AuthenticationAgentExecutor } from './agent_executor.js';
|
||||
import { userBuilder } from './user_builder.js';
|
||||
import { authenticationHandler } from './authentication_middleware.js';
|
||||
|
||||
// --- Server Setup ---
|
||||
|
||||
const authenticationAgentCard: AgentCard = {
|
||||
name: 'Sample Authentication Agent',
|
||||
description: 'A sample agent to test the authentication functionality',
|
||||
url: 'http://localhost:41241/',
|
||||
provider: {
|
||||
organization: 'A2A Samples',
|
||||
url: 'https://example.com/a2a-samples',
|
||||
},
|
||||
version: '1.0.0',
|
||||
protocolVersion: '0.3.0',
|
||||
capabilities: {
|
||||
stateTransitionHistory: true, // Agent uses history
|
||||
},
|
||||
defaultInputModes: ['text'],
|
||||
defaultOutputModes: ['text', 'task-status'],
|
||||
skills: [
|
||||
{
|
||||
id: 'sample_agent',
|
||||
name: 'Sample Agent',
|
||||
description: 'Simulate the general flow of an agent with authentication feature.',
|
||||
tags: ['sample'],
|
||||
examples: ['hello, who am i?'],
|
||||
inputModes: ['text'],
|
||||
outputModes: ['text', 'task-status'],
|
||||
},
|
||||
],
|
||||
supportsAuthenticatedExtendedCard: false,
|
||||
security: [{ Bearer: [] }],
|
||||
securitySchemes: { Bearer: { type: 'http', scheme: 'bearer' } },
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// 1. Create TaskStore
|
||||
const taskStore: TaskStore = new InMemoryTaskStore();
|
||||
|
||||
// 2. Create AgentExecutor
|
||||
const agentExecutor: AgentExecutor = new AuthenticationAgentExecutor();
|
||||
|
||||
// 3. Create DefaultRequestHandler
|
||||
const requestHandler = new DefaultRequestHandler(
|
||||
authenticationAgentCard,
|
||||
taskStore,
|
||||
agentExecutor
|
||||
);
|
||||
|
||||
// 4. Create and setup express app, with authentication middleware and user builder
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(authenticationHandler);
|
||||
app.use(
|
||||
jsonRpcHandler({
|
||||
requestHandler,
|
||||
userBuilder,
|
||||
})
|
||||
);
|
||||
|
||||
// 5. Start the server
|
||||
const PORT = process.env.PORT || 41241;
|
||||
app.listen(PORT, (err: unknown) => {
|
||||
if (err) {
|
||||
throw err;
|
||||
}
|
||||
console.log(
|
||||
`[AuthenticationAgent] Server using new framework started on http://localhost:${PORT}`
|
||||
);
|
||||
console.log(
|
||||
`[AuthenticationAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`
|
||||
);
|
||||
console.log('[AuthenticationAgent] Press Ctrl+C to stop the server');
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user