zorvex-api 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- zorvex_api/__init__.py +5 -0
- zorvex_api/alembic/env.py +76 -0
- zorvex_api/alembic/script.py.mako +24 -0
- zorvex_api/alembic/versions/0001_baseline.py +153 -0
- zorvex_api/alembic.ini +107 -0
- zorvex_api/api/__init__.py +1 -0
- zorvex_api/api/a2a.py +236 -0
- zorvex_api/api/assistants.py +245 -0
- zorvex_api/api/crons.py +235 -0
- zorvex_api/api/event_streaming.py +174 -0
- zorvex_api/api/mcp.py +103 -0
- zorvex_api/api/runs.py +423 -0
- zorvex_api/api/stateless_runs.py +116 -0
- zorvex_api/api/store.py +216 -0
- zorvex_api/api/system.py +131 -0
- zorvex_api/api/threads.py +620 -0
- zorvex_api/api/ui.py +48 -0
- zorvex_api/config.py +360 -0
- zorvex_api/constants.py +8 -0
- zorvex_api/core/__init__.py +0 -0
- zorvex_api/core/active_runs.py +16 -0
- zorvex_api/core/auth_deps.py +30 -0
- zorvex_api/core/auth_filters.py +90 -0
- zorvex_api/core/auth_middleware.py +108 -0
- zorvex_api/core/authorization.py +162 -0
- zorvex_api/core/database.py +176 -0
- zorvex_api/core/loopback.py +45 -0
- zorvex_api/core/migrations.py +130 -0
- zorvex_api/core/orm.py +274 -0
- zorvex_api/core/redis_manager.py +113 -0
- zorvex_api/core/route_merger.py +72 -0
- zorvex_api/core/serializers.py +67 -0
- zorvex_api/core/sse.py +84 -0
- zorvex_api/main.py +525 -0
- zorvex_api/middleware/__init__.py +5 -0
- zorvex_api/middleware/auth_first.py +38 -0
- zorvex_api/middleware/configurable_headers.py +25 -0
- zorvex_api/middleware/content_type_fix.py +59 -0
- zorvex_api/middleware/logger_middleware.py +82 -0
- zorvex_api/models/__init__.py +91 -0
- zorvex_api/models/assistants.py +154 -0
- zorvex_api/models/auth.py +34 -0
- zorvex_api/models/crons.py +185 -0
- zorvex_api/models/entity_ids.py +9 -0
- zorvex_api/models/enums.py +54 -0
- zorvex_api/models/errors.py +58 -0
- zorvex_api/models/event_streaming.py +32 -0
- zorvex_api/models/run_job.py +104 -0
- zorvex_api/models/runs.py +274 -0
- zorvex_api/models/search.py +11 -0
- zorvex_api/models/store.py +83 -0
- zorvex_api/models/threads.py +321 -0
- zorvex_api/observability/__init__.py +1 -0
- zorvex_api/observability/metrics.py +135 -0
- zorvex_api/observability/tracing.py +222 -0
- zorvex_api/services/__init__.py +0 -0
- zorvex_api/services/a2a_messages.py +656 -0
- zorvex_api/services/a2a_service.py +1296 -0
- zorvex_api/services/a2ui.py +225 -0
- zorvex_api/services/a2ui_schemas/README.md +6 -0
- zorvex_api/services/a2ui_schemas/client_capabilities.json +97 -0
- zorvex_api/services/a2ui_schemas/client_data_model.json +22 -0
- zorvex_api/services/a2ui_schemas/client_to_server.json +104 -0
- zorvex_api/services/a2ui_schemas/server_to_client.json +132 -0
- zorvex_api/services/assistant_service.py +610 -0
- zorvex_api/services/base_broker.py +160 -0
- zorvex_api/services/base_executor.py +37 -0
- zorvex_api/services/broker.py +273 -0
- zorvex_api/services/checkpoints.py +105 -0
- zorvex_api/services/cron_scheduler.py +205 -0
- zorvex_api/services/cron_service.py +515 -0
- zorvex_api/services/event_converter.py +30 -0
- zorvex_api/services/event_streaming/__init__.py +6 -0
- zorvex_api/services/event_streaming/channels.py +23 -0
- zorvex_api/services/event_streaming/commands.py +446 -0
- zorvex_api/services/event_streaming/native_stream.py +96 -0
- zorvex_api/services/event_streaming/normalizers.py +353 -0
- zorvex_api/services/event_streaming/protocol.py +55 -0
- zorvex_api/services/event_streaming/session.py +526 -0
- zorvex_api/services/event_streaming/ws.py +175 -0
- zorvex_api/services/executor.py +29 -0
- zorvex_api/services/graph_factory.py +139 -0
- zorvex_api/services/graph_streaming.py +159 -0
- zorvex_api/services/job_queue.py +42 -0
- zorvex_api/services/langgraph_service.py +291 -0
- zorvex_api/services/lease_reaper.py +281 -0
- zorvex_api/services/local_executor.py +89 -0
- zorvex_api/services/mcp_calls.py +662 -0
- zorvex_api/services/mcp_elicitation.py +648 -0
- zorvex_api/services/mcp_forms.py +308 -0
- zorvex_api/services/mcp_server.py +290 -0
- zorvex_api/services/ownership.py +85 -0
- zorvex_api/services/priority.py +92 -0
- zorvex_api/services/redis_broker.py +520 -0
- zorvex_api/services/run_cancel.py +79 -0
- zorvex_api/services/run_cleanup.py +210 -0
- zorvex_api/services/run_executor.py +332 -0
- zorvex_api/services/run_preparation.py +536 -0
- zorvex_api/services/run_queue.py +52 -0
- zorvex_api/services/run_status.py +190 -0
- zorvex_api/services/run_waiters.py +179 -0
- zorvex_api/services/streaming_service.py +163 -0
- zorvex_api/services/thread_events.py +68 -0
- zorvex_api/services/thread_service.py +185 -0
- zorvex_api/services/thread_state_service.py +84 -0
- zorvex_api/services/thread_stream.py +171 -0
- zorvex_api/services/thread_ttl.py +277 -0
- zorvex_api/services/webhook_delivery.py +329 -0
- zorvex_api/services/webhook_policy.py +218 -0
- zorvex_api/services/webhook_signing.py +54 -0
- zorvex_api/services/worker_executor.py +620 -0
- zorvex_api/settings.py +278 -0
- zorvex_api/utils/__init__.py +3 -0
- zorvex_api/utils/assistants.py +23 -0
- zorvex_api/utils/event_loop.py +12 -0
- zorvex_api/utils/headers.py +100 -0
- zorvex_api/utils/jsonb.py +41 -0
- zorvex_api/utils/loader.py +50 -0
- zorvex_api/utils/pagination.py +12 -0
- zorvex_api/utils/run_utils.py +120 -0
- zorvex_api/utils/setup_logging.py +143 -0
- zorvex_api/utils/sse_utils.py +26 -0
- zorvex_api-0.0.1.dist-info/METADATA +45 -0
- zorvex_api-0.0.1.dist-info/RECORD +125 -0
- zorvex_api-0.0.1.dist-info/WHEEL +4 -0
zorvex_api/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Alembic environment configuration for Zorvex database migrations."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import threading
|
|
5
|
+
from logging.config import fileConfig
|
|
6
|
+
|
|
7
|
+
from sqlalchemy import pool
|
|
8
|
+
from sqlalchemy.engine import Connection
|
|
9
|
+
|
|
10
|
+
from alembic import context
|
|
11
|
+
from zorvex_api.core.database import create_db_engine
|
|
12
|
+
from zorvex_api.core.orm import Base
|
|
13
|
+
|
|
14
|
+
# This is the Alembic Config object, which provides
|
|
15
|
+
# access to the values within the .ini file in use.
|
|
16
|
+
config = context.config
|
|
17
|
+
|
|
18
|
+
# Interpret the config file for Python logging.
|
|
19
|
+
# Only reconfigure logging when running from CLI (main thread).
|
|
20
|
+
# When invoked programmatically via asyncio.to_thread(), fileConfig()
|
|
21
|
+
# causes a cross-thread deadlock with the application's logging.
|
|
22
|
+
# See: https://github.com/sqlalchemy/alembic/discussions/1483
|
|
23
|
+
if config.config_file_name is not None and threading.current_thread() is threading.main_thread():
|
|
24
|
+
fileConfig(config.config_file_name)
|
|
25
|
+
|
|
26
|
+
target_metadata = Base.metadata
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _include_name(name: str | None, type_: str, _parent_names: object) -> bool:
|
|
30
|
+
"""Autogenerate compares Zorvex's tables only; LangGraph creates and migrates its own."""
|
|
31
|
+
return type_ != "table" or name in target_metadata.tables
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run_migrations_offline() -> None:
|
|
35
|
+
"""Emit the migration SQL instead of running it."""
|
|
36
|
+
context.configure(
|
|
37
|
+
dialect_name="postgresql",
|
|
38
|
+
target_metadata=target_metadata,
|
|
39
|
+
include_name=_include_name,
|
|
40
|
+
literal_binds=True,
|
|
41
|
+
dialect_opts={"paramstyle": "named"},
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
with context.begin_transaction():
|
|
45
|
+
context.run_migrations()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def do_run_migrations(connection: Connection) -> None:
|
|
49
|
+
"""Run migrations with the given connection."""
|
|
50
|
+
context.configure(connection=connection, target_metadata=target_metadata, include_name=_include_name)
|
|
51
|
+
|
|
52
|
+
with context.begin_transaction():
|
|
53
|
+
context.run_migrations()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def run_async_migrations() -> None:
|
|
57
|
+
"""Run the migrations on a connection to settings' database."""
|
|
58
|
+
# The URL never goes through alembic.ini: configparser would reject the %XX
|
|
59
|
+
# escapes of a quoted password.
|
|
60
|
+
connectable = create_db_engine(poolclass=pool.NullPool)
|
|
61
|
+
|
|
62
|
+
async with connectable.connect() as connection:
|
|
63
|
+
await connection.run_sync(do_run_migrations)
|
|
64
|
+
|
|
65
|
+
await connectable.dispose()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def run_migrations_online() -> None:
|
|
69
|
+
"""Run migrations in 'online' mode."""
|
|
70
|
+
asyncio.run(run_async_migrations())
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
if context.is_offline_mode():
|
|
74
|
+
run_migrations_offline()
|
|
75
|
+
else:
|
|
76
|
+
run_migrations_online()
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""${message}
|
|
2
|
+
|
|
3
|
+
Revision ID: ${up_revision}
|
|
4
|
+
Revises: ${down_revision | comma,n}
|
|
5
|
+
Create Date: ${create_date}
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
from alembic import op
|
|
9
|
+
import sqlalchemy as sa
|
|
10
|
+
${imports if imports else ""}
|
|
11
|
+
|
|
12
|
+
# revision identifiers, used by Alembic.
|
|
13
|
+
revision = ${repr(up_revision)}
|
|
14
|
+
down_revision = ${repr(down_revision)}
|
|
15
|
+
branch_labels = ${repr(branch_labels)}
|
|
16
|
+
depends_on = ${repr(depends_on)}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def upgrade() -> None:
|
|
20
|
+
${upgrades if upgrades else "pass"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def downgrade() -> None:
|
|
24
|
+
${downgrades if downgrades else "pass"}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Baseline schema
|
|
2
|
+
|
|
3
|
+
Revision ID: 0001
|
|
4
|
+
Revises:
|
|
5
|
+
Create Date: 2026-11-25
|
|
6
|
+
|
|
7
|
+
Zorvex's own tables, as core/orm.py defines them. LangGraph creates and migrates
|
|
8
|
+
its checkpoint and store tables itself. A database from before this baseline has
|
|
9
|
+
no upgrade path: recreate it. One at 0002 (run priority, folded in here) already
|
|
10
|
+
has this schema: stamp it instead, ``alembic stamp --purge 0001``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import sqlalchemy as sa
|
|
14
|
+
from sqlalchemy.dialects import postgresql
|
|
15
|
+
|
|
16
|
+
from alembic import op
|
|
17
|
+
|
|
18
|
+
revision = "0001"
|
|
19
|
+
down_revision = None
|
|
20
|
+
branch_labels = None
|
|
21
|
+
depends_on = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def upgrade() -> None:
|
|
25
|
+
op.create_table(
|
|
26
|
+
"assistant",
|
|
27
|
+
sa.Column("assistant_id", sa.Text(), server_default=sa.text("gen_random_uuid()::text"), nullable=False),
|
|
28
|
+
sa.Column("name", sa.Text(), nullable=False),
|
|
29
|
+
sa.Column("description", sa.Text(), nullable=True),
|
|
30
|
+
sa.Column("graph_id", sa.Text(), nullable=False),
|
|
31
|
+
sa.Column("config", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
32
|
+
sa.Column("context", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
33
|
+
sa.Column("user_id", sa.Text(), nullable=False),
|
|
34
|
+
sa.Column("version", sa.Integer(), server_default=sa.text("1"), nullable=False),
|
|
35
|
+
sa.Column("metadata", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
36
|
+
sa.Column("created_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
37
|
+
sa.Column("updated_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
38
|
+
sa.PrimaryKeyConstraint("assistant_id"),
|
|
39
|
+
)
|
|
40
|
+
op.create_index(
|
|
41
|
+
"idx_assistant_metadata_gin",
|
|
42
|
+
"assistant",
|
|
43
|
+
["metadata"],
|
|
44
|
+
unique=False,
|
|
45
|
+
postgresql_using="gin",
|
|
46
|
+
postgresql_ops={"metadata": "jsonb_path_ops"},
|
|
47
|
+
)
|
|
48
|
+
op.create_index("idx_assistant_user", "assistant", ["user_id"], unique=False)
|
|
49
|
+
op.create_table(
|
|
50
|
+
"thread",
|
|
51
|
+
sa.Column("thread_id", sa.Text(), nullable=False),
|
|
52
|
+
sa.Column("status", sa.Text(), server_default=sa.text("'idle'"), nullable=False),
|
|
53
|
+
sa.Column("metadata", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
54
|
+
sa.Column("config", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
55
|
+
sa.Column("values", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
56
|
+
sa.Column("interrupts", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
57
|
+
sa.Column("user_id", sa.Text(), nullable=False),
|
|
58
|
+
sa.Column("created_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
59
|
+
sa.Column("updated_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
60
|
+
sa.Column("state_updated_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
61
|
+
sa.Column("run_priority", sa.Integer(), nullable=True),
|
|
62
|
+
sa.Column("fairness_group", sa.Text(), nullable=True),
|
|
63
|
+
sa.PrimaryKeyConstraint("thread_id"),
|
|
64
|
+
)
|
|
65
|
+
op.create_index(
|
|
66
|
+
"idx_thread_metadata_gin",
|
|
67
|
+
"thread",
|
|
68
|
+
["metadata"],
|
|
69
|
+
unique=False,
|
|
70
|
+
postgresql_using="gin",
|
|
71
|
+
postgresql_ops={"metadata": "jsonb_path_ops"},
|
|
72
|
+
)
|
|
73
|
+
op.create_index("idx_thread_user", "thread", ["user_id"], unique=False)
|
|
74
|
+
op.create_table(
|
|
75
|
+
"assistant_versions",
|
|
76
|
+
sa.Column("assistant_id", sa.Text(), nullable=False),
|
|
77
|
+
sa.Column("version", sa.Integer(), nullable=False),
|
|
78
|
+
sa.Column("graph_id", sa.Text(), nullable=False),
|
|
79
|
+
sa.Column("config", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
80
|
+
sa.Column("context", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
81
|
+
sa.Column("created_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
82
|
+
sa.Column("metadata", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
83
|
+
sa.Column("name", sa.Text(), nullable=False),
|
|
84
|
+
sa.Column("description", sa.Text(), nullable=True),
|
|
85
|
+
sa.ForeignKeyConstraint(["assistant_id"], ["assistant.assistant_id"], ondelete="CASCADE"),
|
|
86
|
+
sa.PrimaryKeyConstraint("assistant_id", "version"),
|
|
87
|
+
)
|
|
88
|
+
op.create_table(
|
|
89
|
+
"cron",
|
|
90
|
+
sa.Column("cron_id", sa.Text(), server_default=sa.text("gen_random_uuid()::text"), nullable=False),
|
|
91
|
+
sa.Column("assistant_id", sa.Text(), nullable=False),
|
|
92
|
+
sa.Column("thread_id", sa.Text(), nullable=True),
|
|
93
|
+
sa.Column("user_id", sa.Text(), nullable=False),
|
|
94
|
+
sa.Column("schedule", sa.Text(), nullable=False),
|
|
95
|
+
sa.Column("timezone", sa.Text(), nullable=True),
|
|
96
|
+
sa.Column("payload", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
97
|
+
sa.Column("metadata", postgresql.JSONB(), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
98
|
+
sa.Column("on_run_completed", sa.Text(), nullable=True),
|
|
99
|
+
sa.Column("enabled", sa.Boolean(), server_default=sa.text("true"), nullable=False),
|
|
100
|
+
sa.Column("end_time", sa.TIMESTAMP(timezone=True), nullable=True),
|
|
101
|
+
sa.Column("next_run_date", sa.TIMESTAMP(timezone=True), nullable=True),
|
|
102
|
+
sa.Column("claimed_until", sa.TIMESTAMP(timezone=True), nullable=True),
|
|
103
|
+
sa.Column("created_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
104
|
+
sa.Column("updated_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
105
|
+
sa.ForeignKeyConstraint(["assistant_id"], ["assistant.assistant_id"], ondelete="CASCADE"),
|
|
106
|
+
sa.ForeignKeyConstraint(["thread_id"], ["thread.thread_id"], ondelete="CASCADE"),
|
|
107
|
+
sa.PrimaryKeyConstraint("cron_id"),
|
|
108
|
+
)
|
|
109
|
+
op.create_index("idx_cron_assistant_id", "cron", ["assistant_id"], unique=False)
|
|
110
|
+
op.create_index("idx_cron_next_run", "cron", ["enabled", "next_run_date"], unique=False)
|
|
111
|
+
op.create_index("idx_cron_thread_id", "cron", ["thread_id"], unique=False)
|
|
112
|
+
op.create_index("idx_cron_user", "cron", ["user_id"], unique=False)
|
|
113
|
+
op.create_table(
|
|
114
|
+
"run",
|
|
115
|
+
sa.Column("run_id", sa.Text(), server_default=sa.text("gen_random_uuid()::text"), nullable=False),
|
|
116
|
+
sa.Column("thread_id", sa.Text(), nullable=False),
|
|
117
|
+
sa.Column("assistant_id", sa.Text(), nullable=False),
|
|
118
|
+
sa.Column("status", sa.Text(), server_default=sa.text("'pending'"), nullable=False),
|
|
119
|
+
sa.Column("error", postgresql.JSONB(), nullable=True),
|
|
120
|
+
sa.Column("user_id", sa.Text(), nullable=False),
|
|
121
|
+
sa.Column("created_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
122
|
+
sa.Column("updated_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
123
|
+
sa.Column("priority", sa.Integer(), server_default=sa.text("0"), nullable=False),
|
|
124
|
+
sa.Column("execution_params", postgresql.JSONB(), nullable=False),
|
|
125
|
+
sa.Column("claimed_by", sa.Text(), nullable=True),
|
|
126
|
+
sa.Column("lease_expires_at", sa.TIMESTAMP(timezone=True), nullable=True),
|
|
127
|
+
sa.Column("retries", sa.Integer(), server_default=sa.text("0"), nullable=False),
|
|
128
|
+
sa.Column("cancel_action", sa.Text(), nullable=True),
|
|
129
|
+
sa.Column("cancel_reason", sa.Text(), nullable=True),
|
|
130
|
+
sa.ForeignKeyConstraint(["assistant_id"], ["assistant.assistant_id"], ondelete="CASCADE"),
|
|
131
|
+
sa.ForeignKeyConstraint(["thread_id"], ["thread.thread_id"], ondelete="CASCADE"),
|
|
132
|
+
sa.PrimaryKeyConstraint("run_id"),
|
|
133
|
+
)
|
|
134
|
+
op.create_index("idx_run_assistant_id", "run", ["assistant_id"], unique=False)
|
|
135
|
+
op.create_index("idx_run_created_at", "run", ["created_at"], unique=False)
|
|
136
|
+
op.create_index("idx_run_lease_reaper", "run", ["status", "lease_expires_at"], unique=False)
|
|
137
|
+
op.create_index("idx_run_thread_id", "run", ["thread_id"], unique=False)
|
|
138
|
+
op.create_index("idx_run_user", "run", ["user_id"], unique=False)
|
|
139
|
+
op.create_table(
|
|
140
|
+
"thread_ttl",
|
|
141
|
+
sa.Column("thread_id", sa.Text(), nullable=False),
|
|
142
|
+
sa.Column("strategy", sa.Text(), server_default=sa.text("'delete'"), nullable=False),
|
|
143
|
+
sa.Column("ttl_minutes", sa.Float(), nullable=False),
|
|
144
|
+
sa.Column("expires_at", sa.TIMESTAMP(timezone=True), nullable=False),
|
|
145
|
+
sa.ForeignKeyConstraint(["thread_id"], ["thread.thread_id"], ondelete="CASCADE"),
|
|
146
|
+
sa.PrimaryKeyConstraint("thread_id"),
|
|
147
|
+
)
|
|
148
|
+
op.create_index("idx_thread_ttl_expires_at", "thread_ttl", ["expires_at"], unique=False)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def downgrade() -> None:
|
|
152
|
+
for table in ("thread_ttl", "run", "cron", "assistant_versions", "thread", "assistant"):
|
|
153
|
+
op.drop_table(table)
|
zorvex_api/alembic.ini
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# A generic, single database configuration.
|
|
2
|
+
|
|
3
|
+
[alembic]
|
|
4
|
+
# path to migration scripts
|
|
5
|
+
script_location = alembic
|
|
6
|
+
|
|
7
|
+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
|
8
|
+
# Using timestamp-based naming for better readability
|
|
9
|
+
file_template = %%(year)d%%(month).2d%%(day).2d%%(hour).2d%%(minute).2d%%(second).2d_%%(slug)s
|
|
10
|
+
|
|
11
|
+
# sys.path path, will be prepended to sys.path if present.
|
|
12
|
+
# defaults to the current working directory.
|
|
13
|
+
prepend_sys_path = .
|
|
14
|
+
|
|
15
|
+
# timezone to use when rendering the date within the migration file
|
|
16
|
+
# as well as the filename.
|
|
17
|
+
# If specified, requires the python-dateutil library that can be
|
|
18
|
+
# installed by adding `alembic[tz]` to the pip requirements
|
|
19
|
+
# string value is passed to dateutil.tz.gettz()
|
|
20
|
+
# leave blank for localtime
|
|
21
|
+
# timezone =
|
|
22
|
+
|
|
23
|
+
# max length of characters to apply to the
|
|
24
|
+
# "slug" field
|
|
25
|
+
# truncate_slug_length = 40
|
|
26
|
+
|
|
27
|
+
# set to 'true' to run the environment during
|
|
28
|
+
# the 'revision' command, regardless of autogenerate
|
|
29
|
+
# revision_environment = false
|
|
30
|
+
|
|
31
|
+
# set to 'true' to allow .pyc and .pyo files without
|
|
32
|
+
# a source .py file to be detected as revisions in the
|
|
33
|
+
# versions/ directory
|
|
34
|
+
# sourceless = false
|
|
35
|
+
|
|
36
|
+
# version number format
|
|
37
|
+
version_num_format = %%04d
|
|
38
|
+
|
|
39
|
+
# version path separator; As mentioned above, this is the character used to split
|
|
40
|
+
# version_locations. The default within new alembic.ini files is "os", which uses
|
|
41
|
+
# os.pathsep. If this key is omitted entirely, it falls back to the legacy
|
|
42
|
+
# behavior of splitting on spaces and/or commas.
|
|
43
|
+
# Valid values for version_path_separator are:
|
|
44
|
+
#
|
|
45
|
+
# version_path_separator = :
|
|
46
|
+
# version_path_separator = ;
|
|
47
|
+
# version_path_separator = space
|
|
48
|
+
version_path_separator = os
|
|
49
|
+
|
|
50
|
+
# the output encoding used when revision files
|
|
51
|
+
# are written from script.py.mako
|
|
52
|
+
# output_encoding = utf-8
|
|
53
|
+
|
|
54
|
+
# env.py connects to DATABASE_URI through the server's engine; no URL is configured here.
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
[post_write_hooks]
|
|
58
|
+
# post_write_hooks defines scripts or Python functions that are run
|
|
59
|
+
# on newly generated revision scripts. See the documentation for further
|
|
60
|
+
# detail and examples
|
|
61
|
+
|
|
62
|
+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
|
63
|
+
# hooks = black
|
|
64
|
+
# black.type = console_scripts
|
|
65
|
+
# black.entrypoint = black
|
|
66
|
+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
|
67
|
+
|
|
68
|
+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
|
|
69
|
+
# hooks = ruff
|
|
70
|
+
# ruff.type = exec
|
|
71
|
+
# ruff.executable = %(here)s/.venv/bin/ruff
|
|
72
|
+
# ruff.options = --fix REVISION_SCRIPT_FILENAME
|
|
73
|
+
|
|
74
|
+
# Logging configuration
|
|
75
|
+
[loggers]
|
|
76
|
+
keys = root,sqlalchemy,alembic
|
|
77
|
+
|
|
78
|
+
[handlers]
|
|
79
|
+
keys = console
|
|
80
|
+
|
|
81
|
+
[formatters]
|
|
82
|
+
keys = generic
|
|
83
|
+
|
|
84
|
+
[logger_root]
|
|
85
|
+
level = WARN
|
|
86
|
+
handlers = console
|
|
87
|
+
qualname =
|
|
88
|
+
|
|
89
|
+
[logger_sqlalchemy]
|
|
90
|
+
level = WARN
|
|
91
|
+
handlers =
|
|
92
|
+
qualname = sqlalchemy.engine
|
|
93
|
+
|
|
94
|
+
[logger_alembic]
|
|
95
|
+
level = INFO
|
|
96
|
+
handlers =
|
|
97
|
+
qualname = alembic
|
|
98
|
+
|
|
99
|
+
[handler_console]
|
|
100
|
+
class = StreamHandler
|
|
101
|
+
args = (sys.stderr,)
|
|
102
|
+
level = NOTSET
|
|
103
|
+
formatter = generic
|
|
104
|
+
|
|
105
|
+
[formatter_generic]
|
|
106
|
+
format = %(levelname)-5.5s [%(name)s] %(message)s
|
|
107
|
+
datefmt = %H:%M:%S
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Agent Protocol API endpoints"""
|
zorvex_api/api/a2a.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""Agent-to-Agent protocol, as the Agent Server serves it: JSON-RPC at ``/a2a/{assistant_id}`` and agent cards.
|
|
2
|
+
|
|
3
|
+
services/a2a_service.py answers each method from runs and threads, in the
|
|
4
|
+
Agent Server's wire format. This module checks the JSON-RPC envelope in the
|
|
5
|
+
Agent Server's order, routes the method (answering a v0.3 method name in v0.3's
|
|
6
|
+
spelling, and SendStreamingMessage as SSE), and serves the cards: at
|
|
7
|
+
``/a2a/{assistant_id}``, its ``.well-known`` paths, and the domain root, which
|
|
8
|
+
describes the ``?assistant_id`` or ``DEFAULT_A2A_ASSISTANT_ID``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import uuid
|
|
15
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import structlog
|
|
19
|
+
from fastapi import APIRouter, Depends, Query, Request, Response
|
|
20
|
+
from fastapi.responses import JSONResponse
|
|
21
|
+
from sse_starlette import ServerSentEvent
|
|
22
|
+
|
|
23
|
+
from zorvex_api.core import sse
|
|
24
|
+
from zorvex_api.core.auth_deps import auth_dependency, require_auth
|
|
25
|
+
from zorvex_api.core.authorization import Authorization, Authorize
|
|
26
|
+
from zorvex_api.core.serializers import to_jsonable
|
|
27
|
+
from zorvex_api.models import User
|
|
28
|
+
from zorvex_api.services import a2a_service
|
|
29
|
+
from zorvex_api.services.a2a_messages import to_spec_format
|
|
30
|
+
from zorvex_api.services.a2a_service import METHODS, V03_METHODS, Call
|
|
31
|
+
from zorvex_api.settings import settings
|
|
32
|
+
|
|
33
|
+
router = APIRouter(tags=["A2A"], dependencies=auth_dependency)
|
|
34
|
+
logger = structlog.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
# The dispatcher reads the body itself; the schema is declared here for the docs.
|
|
37
|
+
_REQUEST_SCHEMA: dict[str, Any] = {
|
|
38
|
+
"requestBody": {
|
|
39
|
+
"required": True,
|
|
40
|
+
"content": {
|
|
41
|
+
"application/json": {
|
|
42
|
+
"schema": {
|
|
43
|
+
"type": "object",
|
|
44
|
+
"required": ["jsonrpc", "id", "method"],
|
|
45
|
+
"properties": {
|
|
46
|
+
"jsonrpc": {"type": "string", "enum": ["2.0"]},
|
|
47
|
+
"id": {"type": ["string", "integer"]},
|
|
48
|
+
"method": {"type": "string", "enum": [*sorted(METHODS), *sorted(V03_METHODS)]},
|
|
49
|
+
"params": {
|
|
50
|
+
"type": "object",
|
|
51
|
+
"description": "Method parameters, as the A2A 1.0 (or 0.3) spec defines them. SendMessage "
|
|
52
|
+
"and SendStreamingMessage also take `context`, the run's context, and the message a "
|
|
53
|
+
"`command` (resume, update or goto), the LangGraph Command it runs with.",
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
_UNREADABLE = object()
|
|
63
|
+
_STREAMING = frozenset({"SendStreamingMessage", "message/stream"})
|
|
64
|
+
_SENDING = _STREAMING | {"SendMessage", "message/send"}
|
|
65
|
+
_HANDLERS: dict[str, Callable[[Call, dict[str, Any]], Awaitable[dict[str, Any]]]] = {
|
|
66
|
+
"SendMessage": a2a_service.send_message,
|
|
67
|
+
"GetTask": a2a_service.get_task,
|
|
68
|
+
"CancelTask": a2a_service.cancel_task,
|
|
69
|
+
"ListTasks": a2a_service.list_tasks,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def _body(request: Request) -> Any:
|
|
74
|
+
try:
|
|
75
|
+
return json.loads(await request.body())
|
|
76
|
+
except ValueError:
|
|
77
|
+
return _UNREADABLE
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _rpc_error(request_id: str | int | None, code: int, message: str) -> JSONResponse:
|
|
81
|
+
"""A JSON-RPC error; HTTP 200, as JSON-RPC answers."""
|
|
82
|
+
return JSONResponse({"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}})
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _accepts(request: Request, media_type: str) -> bool:
|
|
86
|
+
"""Whether the Accept header admits *media_type*: by name, as ``type/*``, or as ``*/*``."""
|
|
87
|
+
admitting = {"*/*", media_type, media_type.split("/", 1)[0] + "/*"}
|
|
88
|
+
return any(
|
|
89
|
+
item.split(";", 1)[0].strip().lower() in admitting for item in request.headers.get("accept", "").split(",")
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _rejection(request: Request, body: Any) -> Response | None:
|
|
94
|
+
"""The answer to a request turned away before its method runs, checked in the Agent Server's order; None to run it.
|
|
95
|
+
|
|
96
|
+
A float or boolean id is turned away too: the Agent Server would take it,
|
|
97
|
+
but JSON-RPC asks for integers.
|
|
98
|
+
"""
|
|
99
|
+
if body is _UNREADABLE:
|
|
100
|
+
return _rpc_error(None, -32700, "Invalid JSON payload")
|
|
101
|
+
if not isinstance(body, dict):
|
|
102
|
+
return _rpc_error(None, -32600, "Invalid message format: expected object")
|
|
103
|
+
request_id = body.get("id")
|
|
104
|
+
id_ok = request_id is None or (isinstance(request_id, (str, int)) and not isinstance(request_id, bool))
|
|
105
|
+
if body.get("jsonrpc") != "2.0":
|
|
106
|
+
return _rpc_error(
|
|
107
|
+
request_id if id_ok else None, -32600, "Invalid JSON-RPC message: missing or invalid jsonrpc version"
|
|
108
|
+
)
|
|
109
|
+
if not id_ok:
|
|
110
|
+
return _rpc_error(None, -32600, "Invalid JSON-RPC request: 'id' must be a string, integer, or null")
|
|
111
|
+
method = body.get("method")
|
|
112
|
+
if method is not None and not isinstance(method, str):
|
|
113
|
+
return _rpc_error(request_id, -32601, "Method not found: method must be a string")
|
|
114
|
+
if method is not None and method not in METHODS and method not in V03_METHODS:
|
|
115
|
+
return _rpc_error(request_id, -32601, f"Method not found: {method}")
|
|
116
|
+
if method in _SENDING:
|
|
117
|
+
params = body.get("params", {})
|
|
118
|
+
if not isinstance(params, dict):
|
|
119
|
+
return _rpc_error(request_id, -32602, "Invalid params: must be an object")
|
|
120
|
+
if not params.get("message") or not isinstance(params["message"], dict):
|
|
121
|
+
return _rpc_error(request_id, -32602, "Missing or invalid 'message' in params")
|
|
122
|
+
if method in _STREAMING and not _accepts(request, "text/event-stream"):
|
|
123
|
+
return JSONResponse({"error": "Accept header must include text/event-stream for streaming"}, status_code=400)
|
|
124
|
+
if method not in _STREAMING and not _accepts(request, "application/json"):
|
|
125
|
+
return JSONResponse({"error": "Accept header must include application/json"}, status_code=400)
|
|
126
|
+
if request_id is None:
|
|
127
|
+
# Notifications too: every A2A method has an answer to give.
|
|
128
|
+
return _rpc_error(None, -32600, "Invalid message format: must be a JSON-RPC request or notification")
|
|
129
|
+
if method is None:
|
|
130
|
+
if "result" in body or "error" in body:
|
|
131
|
+
return Response(status_code=202) # a response, of which the server expects none
|
|
132
|
+
return _rpc_error(request_id, -32600, "Invalid JSON-RPC request: missing 'method' field")
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _is_uuid(value: str) -> bool:
|
|
137
|
+
try:
|
|
138
|
+
uuid.UUID(value)
|
|
139
|
+
except ValueError:
|
|
140
|
+
return False
|
|
141
|
+
return True
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _sse_data(payload: Any) -> str:
|
|
145
|
+
"""A payload as one SSE data line: compact JSON, with the line separators SSE readers split on escaped."""
|
|
146
|
+
text = json.dumps(to_jsonable(payload), separators=(",", ":"), ensure_ascii=False)
|
|
147
|
+
return text.replace("\u0085", "\\u0085").replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
async def _sse_frames(payloads: AsyncIterator[dict[str, Any]], *, spec_format: bool) -> AsyncIterator[ServerSentEvent]:
|
|
151
|
+
async for payload in payloads:
|
|
152
|
+
data = to_spec_format(payload) if spec_format else payload
|
|
153
|
+
yield ServerSentEvent(_sse_data(data), event="message")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@router.post("/a2a/{assistant_id}", openapi_extra=_REQUEST_SCHEMA)
|
|
157
|
+
@router.post("/a2a/{assistant_id}/", include_in_schema=False, name="a2a_rpc_slash")
|
|
158
|
+
async def a2a_rpc(
|
|
159
|
+
assistant_id: str,
|
|
160
|
+
request: Request,
|
|
161
|
+
user: User = Depends(require_auth),
|
|
162
|
+
authorize: Authorization = Authorize("assistants", "read"),
|
|
163
|
+
) -> Response:
|
|
164
|
+
"""Serve one A2A JSON-RPC request against an assistant; SendStreamingMessage answers with SSE.
|
|
165
|
+
|
|
166
|
+
Talking to an assistant authorizes as ``assistants.read``. A message also
|
|
167
|
+
creates a run, authorized as ``threads.create_run``; reading a task
|
|
168
|
+
authorizes ``threads.read``, listing them ``threads.search``, and
|
|
169
|
+
cancelling one ``threads.update``.
|
|
170
|
+
"""
|
|
171
|
+
body = await _body(request)
|
|
172
|
+
rejection = _rejection(request, body)
|
|
173
|
+
if rejection is None and not _is_uuid(assistant_id):
|
|
174
|
+
rejection = _rpc_error(body["id"], -32602, "Invalid assistant ID: must be a UUID")
|
|
175
|
+
await authorize({"assistant_id": assistant_id})
|
|
176
|
+
if rejection is not None:
|
|
177
|
+
return rejection
|
|
178
|
+
|
|
179
|
+
method: str = body["method"]
|
|
180
|
+
spec_format = method in V03_METHODS
|
|
181
|
+
method = V03_METHODS.get(method, method)
|
|
182
|
+
params = body.get("params", {})
|
|
183
|
+
call = Call(user=user, assistant_id=str(uuid.UUID(assistant_id)), request=request)
|
|
184
|
+
if method == "SendStreamingMessage":
|
|
185
|
+
frames = _sse_frames(a2a_service.stream_message(call, params, body["id"]), spec_format=spec_format)
|
|
186
|
+
return sse.response(frames, headers={"Content-Type": "text/event-stream"})
|
|
187
|
+
if method == "GetExtendedAgentCard":
|
|
188
|
+
result = await a2a_service.extended_card(call)
|
|
189
|
+
else:
|
|
190
|
+
result = await _HANDLERS[method](call, params)
|
|
191
|
+
payload = {"jsonrpc": "2.0", "id": body["id"], **result}
|
|
192
|
+
return JSONResponse(to_spec_format(payload) if spec_format else payload)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
async def _card(request: Request, user: User, assistant_id: str) -> Response:
|
|
196
|
+
"""The agent card, or the Agent Server's error for an assistant it cannot describe."""
|
|
197
|
+
try:
|
|
198
|
+
return JSONResponse(await a2a_service.agent_card(request, user, assistant_id))
|
|
199
|
+
except ValueError as exc:
|
|
200
|
+
return JSONResponse({"error": {"code": -32602, "message": str(exc)}}, status_code=400)
|
|
201
|
+
except Exception:
|
|
202
|
+
logger.exception("Failed to generate agent card", assistant_id=assistant_id)
|
|
203
|
+
return JSONResponse({"error": {"code": -32603, "message": "Internal server error"}}, status_code=500)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@router.get("/a2a/{assistant_id}")
|
|
207
|
+
@router.get("/a2a/{assistant_id}/", include_in_schema=False, name="a2a_agent_card_slash")
|
|
208
|
+
@router.get("/a2a/{assistant_id}/.well-known/agent-card.json")
|
|
209
|
+
@router.get("/a2a/{assistant_id}/.well-known/agent.json", include_in_schema=False)
|
|
210
|
+
async def a2a_agent_card(
|
|
211
|
+
assistant_id: str,
|
|
212
|
+
request: Request,
|
|
213
|
+
user: User = Depends(require_auth),
|
|
214
|
+
authorize: Authorization = Authorize("assistants", "read"),
|
|
215
|
+
) -> Response:
|
|
216
|
+
"""The assistant's A2A agent card; 400 with a JSON-RPC error for an assistant it cannot describe."""
|
|
217
|
+
await authorize({"assistant_id": assistant_id})
|
|
218
|
+
return await _card(request, user, assistant_id)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@router.get("/.well-known/agent-card.json")
|
|
222
|
+
async def default_agent_card(
|
|
223
|
+
request: Request,
|
|
224
|
+
assistant_id: str | None = Query(
|
|
225
|
+
None, description="The assistant to describe; DEFAULT_A2A_ASSISTANT_ID when omitted."
|
|
226
|
+
),
|
|
227
|
+
user: User = Depends(require_auth),
|
|
228
|
+
authorize: Authorization = Authorize("assistants", "read"),
|
|
229
|
+
) -> Response:
|
|
230
|
+
"""The agent card of the assistant the query names, or of the deployment's default one."""
|
|
231
|
+
assistant_id = assistant_id or settings.a2a.DEFAULT_A2A_ASSISTANT_ID
|
|
232
|
+
await authorize({"assistant_id": assistant_id})
|
|
233
|
+
if not assistant_id:
|
|
234
|
+
message = "Missing required query parameter: assistant_id"
|
|
235
|
+
return JSONResponse({"error": {"code": -32602, "message": message}}, status_code=400)
|
|
236
|
+
return await _card(request, user, assistant_id)
|