albert-memory 0.4.0__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.
Files changed (74) hide show
  1. albert/__init__.py +3 -0
  2. albert/admin.py +532 -0
  3. albert/api.py +698 -0
  4. albert/automatic_memory_release.json +14 -0
  5. albert/benchmark.py +272 -0
  6. albert/benchmark_cli.py +37 -0
  7. albert/capture.py +1051 -0
  8. albert/capture_installer.py +1000 -0
  9. albert/capture_promotion.py +298 -0
  10. albert/capture_retention.py +72 -0
  11. albert/capture_sdk.py +558 -0
  12. albert/capture_security.py +79 -0
  13. albert/chunking.py +79 -0
  14. albert/classifier.py +263 -0
  15. albert/claude_adapter.py +357 -0
  16. albert/claude_lifecycle.py +418 -0
  17. albert/claude_package.json +19 -0
  18. albert/claude_plugin/.claude-plugin/plugin.json +11 -0
  19. albert/claude_plugin/.mcp.json +13 -0
  20. albert/claude_plugin/hooks/hooks.json +70 -0
  21. albert/clusters.py +140 -0
  22. albert/codex_adapter.py +308 -0
  23. albert/codex_hooks/hooks.json +49 -0
  24. albert/codex_lifecycle.py +485 -0
  25. albert/codex_package.json +19 -0
  26. albert/compatibility.py +121 -0
  27. albert/config.py +144 -0
  28. albert/console.py +508 -0
  29. albert/console_backends.py +236 -0
  30. albert/console_map.py +518 -0
  31. albert/console_ops.py +919 -0
  32. albert/credentials.py +616 -0
  33. albert/cursor_adapter.py +320 -0
  34. albert/cursor_hooks/hooks.json +11 -0
  35. albert/cursor_rules/albert-memory.mdc +11 -0
  36. albert/db.py +68 -0
  37. albert/embeddings.py +91 -0
  38. albert/graph.py +623 -0
  39. albert/graph_builders.py +879 -0
  40. albert/graph_cypher.py +669 -0
  41. albert/graph_store.py +376 -0
  42. albert/host_targets/claude-code.json +45 -0
  43. albert/host_targets/codex.json +45 -0
  44. albert/host_targets/openclaw.json +45 -0
  45. albert/host_targets.py +271 -0
  46. albert/links.py +428 -0
  47. albert/mcp_server.py +457 -0
  48. albert/memory_safety.py +111 -0
  49. albert/models.py +611 -0
  50. albert/openclaw_adapter.py +326 -0
  51. albert/openclaw_adapter_trust.json +5 -0
  52. albert/openclaw_package.json +22 -0
  53. albert/openclaw_plugin/index.js +135 -0
  54. albert/openclaw_plugin/openclaw.plugin.json +25 -0
  55. albert/openclaw_plugin/package.json +12 -0
  56. albert/portability.py +291 -0
  57. albert/provenance.py +105 -0
  58. albert/recorder.py +166 -0
  59. albert/release_gate.py +83 -0
  60. albert/schemas.py +617 -0
  61. albert/scope.py +26 -0
  62. albert/search.py +447 -0
  63. albert/security.py +150 -0
  64. albert/services.py +1316 -0
  65. albert/session_context.py +162 -0
  66. albert/trace_feed.py +165 -0
  67. albert/trace_writer.py +131 -0
  68. albert/tracing.py +75 -0
  69. albert/worker.py +202 -0
  70. albert/workspaces.py +256 -0
  71. albert_memory-0.4.0.dist-info/METADATA +554 -0
  72. albert_memory-0.4.0.dist-info/RECORD +74 -0
  73. albert_memory-0.4.0.dist-info/WHEEL +4 -0
  74. albert_memory-0.4.0.dist-info/entry_points.txt +14 -0
albert/credentials.py ADDED
@@ -0,0 +1,616 @@
1
+ """Issue and revoke agent credentials: scoped API keys and single-use connection links.
2
+
3
+ Managing credentials needs keys.manage, which is never part of console.read, so
4
+ a read-only console key (the one Albert Cloud holds, for example) cannot mint
5
+ anything. These routes live outside /v1/console for the same reason: the
6
+ console's read proxies forward that prefix.
7
+
8
+ A connection link is redeemed by an agent with no credential at all, so the
9
+ /onboard routes are unauthenticated and the token is the only secret. Only its
10
+ digest is stored, redemption is a single conditional UPDATE so a link can be
11
+ used once even under concurrent redeems, and an issued key can never carry more
12
+ than the link granted.
13
+
14
+ An issued credential is never scoped wider than its issuer: a workspace-scoped
15
+ manager sees, issues and revokes only its own workspace's credentials, cannot
16
+ grant memory.write.organization, and cannot create or rename workspaces.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import secrets
22
+ from datetime import UTC, datetime, timedelta
23
+ from uuid import UUID
24
+
25
+ from fastapi import APIRouter, Depends, HTTPException, Query, status
26
+ from pydantic import BaseModel, Field, field_validator
27
+ from sqlalchemy import func, select, update
28
+ from sqlalchemy.exc import IntegrityError
29
+ from sqlalchemy.orm import Session
30
+
31
+ from albert.config import get_settings
32
+ from albert.db import get_session
33
+ from albert.models import APIKey, ConnectionLink, Memory, Principal, Workspace
34
+ from albert.security import (
35
+ GRANTABLE_CAPABILITIES,
36
+ AuthContext,
37
+ _as_utc,
38
+ _digest,
39
+ issue_api_key,
40
+ require_capability,
41
+ )
42
+ from albert.services import audit
43
+ from albert.workspaces import MemoryOutcome, credential_counts, delete_workspace
44
+
45
+ settings_router = APIRouter(prefix="/v1/settings", tags=["settings"])
46
+ onboard_router = APIRouter(prefix="/onboard", tags=["onboarding"])
47
+
48
+ LINK_TTL_MIN_SECONDS = 60
49
+ LINK_TTL_MAX_SECONDS = 7 * 24 * 3600
50
+ LINK_TTL_DEFAULT_SECONDS = 3600
51
+
52
+ _manager = require_capability("keys.manage")
53
+
54
+
55
+ def _hash_link_token(token: str) -> bytes:
56
+ return _digest(f"onboard:{token}")
57
+
58
+
59
+ def _iso(value: datetime | None) -> str | None:
60
+ return _as_utc(value).isoformat() if value is not None else None
61
+
62
+
63
+ def _validated_capabilities(value: list[str]) -> list[str]:
64
+ requested = sorted({item.strip() for item in value if item.strip()})
65
+ if not requested:
66
+ raise ValueError("Choose at least one capability")
67
+ unknown = [item for item in requested if item not in GRANTABLE_CAPABILITIES]
68
+ if unknown:
69
+ raise ValueError(f"Capabilities cannot be granted: {', '.join(unknown)}")
70
+ return requested
71
+
72
+
73
+ class KeyCreate(BaseModel):
74
+ name: str = Field(min_length=1, max_length=200)
75
+ capabilities: list[str] = Field(max_length=32)
76
+ # None: the issuer's own scope (organization-wide for an organization-wide issuer).
77
+ workspace_id: UUID | None = None
78
+
79
+ _capabilities = field_validator("capabilities")(_validated_capabilities)
80
+
81
+
82
+ class LinkCreate(BaseModel):
83
+ name: str = Field(min_length=1, max_length=200)
84
+ capabilities: list[str] = Field(max_length=32)
85
+ expires_in_seconds: int = Field(
86
+ default=LINK_TTL_DEFAULT_SECONDS, ge=LINK_TTL_MIN_SECONDS, le=LINK_TTL_MAX_SECONDS
87
+ )
88
+ workspace_id: UUID | None = None
89
+
90
+ _capabilities = field_validator("capabilities")(_validated_capabilities)
91
+
92
+
93
+ class WorkspaceWrite(BaseModel):
94
+ name: str = Field(min_length=1, max_length=200)
95
+
96
+ @field_validator("name")
97
+ @classmethod
98
+ def _trimmed(cls, value: str) -> str:
99
+ value = value.strip()
100
+ if not value:
101
+ raise ValueError("Name a workspace")
102
+ return value
103
+
104
+
105
+ class Redeem(BaseModel):
106
+ agent_name: str = Field(min_length=1, max_length=200)
107
+ # Omitted means everything the link grants.
108
+ capabilities: list[str] | None = Field(default=None, max_length=32)
109
+
110
+
111
+ def _workspace_bound(auth: AuthContext) -> bool:
112
+ """A workspace-scoped key manages only its workspace; admin is never bound."""
113
+ return auth.workspace_id is not None and "admin" not in auth.capabilities
114
+
115
+
116
+ def _manages(auth: AuthContext, organization_id: UUID | None, workspace_id: UUID | None) -> bool:
117
+ """Whether a credential in this scope is one the manager may see and revoke."""
118
+ if organization_id != auth.organization_id:
119
+ return False
120
+ return not _workspace_bound(auth) or workspace_id == auth.workspace_id
121
+
122
+
123
+ def _issue_scope(
124
+ session: Session, auth: AuthContext, workspace_id: UUID | None, capabilities: list[str]
125
+ ) -> UUID | None:
126
+ """The workspace an issued credential is held to; never wider than the issuer's."""
127
+ if _workspace_bound(auth):
128
+ if workspace_id not in (None, auth.workspace_id):
129
+ raise HTTPException(
130
+ status_code=403, detail="A workspace-scoped key issues only into its workspace"
131
+ )
132
+ if "memory.write.organization" in capabilities:
133
+ raise HTTPException(
134
+ status_code=403,
135
+ detail="A workspace-scoped key cannot grant memory.write.organization",
136
+ )
137
+ return auth.workspace_id
138
+ if workspace_id is not None and _workspace(session, auth, workspace_id) is None:
139
+ raise HTTPException(status_code=404, detail="Workspace not found")
140
+ return workspace_id
141
+
142
+
143
+ def _workspace(session: Session, auth: AuthContext, workspace_id: UUID) -> Workspace | None:
144
+ workspace = session.get(Workspace, workspace_id)
145
+ if workspace is None or workspace.organization_id != auth.organization_id:
146
+ return None
147
+ return workspace
148
+
149
+
150
+ def _workspace_names(session: Session, organization_id: UUID) -> dict[UUID, str]:
151
+ return dict(
152
+ session.execute(
153
+ select(Workspace.id, Workspace.name).where(Workspace.organization_id == organization_id)
154
+ ).all()
155
+ )
156
+
157
+
158
+ def _scope_fields(workspace_id: UUID | None, names: dict[UUID, str]) -> dict:
159
+ return {
160
+ "workspace_id": str(workspace_id) if workspace_id else None,
161
+ "workspace_name": names.get(workspace_id) if workspace_id else None,
162
+ }
163
+
164
+
165
+ def _mint_key(
166
+ session: Session,
167
+ *,
168
+ organization_id: UUID,
169
+ workspace_id: UUID | None,
170
+ name: str,
171
+ capabilities: list[str],
172
+ ) -> tuple[APIKey, str]:
173
+ """One principal per credential, so revoking or auditing one agent never touches another."""
174
+ principal = Principal(
175
+ organization_id=organization_id,
176
+ workspace_id=workspace_id,
177
+ name=name,
178
+ principal_type="agent",
179
+ )
180
+ session.add(principal)
181
+ session.flush()
182
+ raw, prefix, digest = issue_api_key()
183
+ key = APIKey(
184
+ principal_id=principal.id,
185
+ prefix=prefix,
186
+ key_hash=digest,
187
+ name=name,
188
+ capabilities=capabilities,
189
+ )
190
+ session.add(key)
191
+ session.flush()
192
+ return key, raw
193
+
194
+
195
+ def _key_row(key: APIKey, auth: AuthContext, names: dict[UUID, str]) -> dict:
196
+ return {
197
+ **_scope_fields(key.principal.workspace_id, names),
198
+ "id": str(key.id),
199
+ "name": key.name,
200
+ "principal_name": key.principal.name,
201
+ "prefix": key.prefix,
202
+ "capabilities": sorted(key.capabilities or []),
203
+ "active": key.active,
204
+ "created_at": _iso(key.created_at),
205
+ "last_used_at": _iso(key.last_used_at),
206
+ "expires_at": _iso(key.expires_at),
207
+ "current": key.principal_id == auth.principal_id,
208
+ }
209
+
210
+
211
+ def _link_state(link: ConnectionLink, now: datetime) -> str:
212
+ if link.revoked_at is not None:
213
+ return "revoked"
214
+ if link.used_at is not None:
215
+ return "used"
216
+ if _as_utc(link.expires_at) <= now:
217
+ return "expired"
218
+ return "open"
219
+
220
+
221
+ def _link_row(link: ConnectionLink, now: datetime, names: dict[UUID, str]) -> dict:
222
+ return {
223
+ **_scope_fields(link.workspace_id, names),
224
+ "id": str(link.id),
225
+ "name": link.name,
226
+ "capabilities": sorted(link.capabilities or []),
227
+ "state": _link_state(link, now),
228
+ "created_at": _iso(link.created_at),
229
+ "expires_at": _iso(link.expires_at),
230
+ "used_at": _iso(link.used_at),
231
+ "api_key_id": str(link.api_key_id) if link.api_key_id else None,
232
+ }
233
+
234
+
235
+ @settings_router.get("/credentials")
236
+ def list_credentials(
237
+ auth: AuthContext = Depends(_manager), session: Session = Depends(get_session)
238
+ ) -> dict:
239
+ now = datetime.now(UTC)
240
+ names = _workspace_names(session, auth.organization_id)
241
+ key_scope = [Principal.organization_id == auth.organization_id]
242
+ link_scope = [ConnectionLink.organization_id == auth.organization_id]
243
+ if _workspace_bound(auth):
244
+ key_scope.append(Principal.workspace_id == auth.workspace_id)
245
+ link_scope.append(ConnectionLink.workspace_id == auth.workspace_id)
246
+ keys = session.scalars(
247
+ select(APIKey)
248
+ .join(Principal, APIKey.principal_id == Principal.id)
249
+ .where(*key_scope)
250
+ .order_by(APIKey.created_at.desc())
251
+ )
252
+ links = session.scalars(
253
+ select(ConnectionLink).where(*link_scope).order_by(ConnectionLink.created_at.desc())
254
+ )
255
+ grantable = [
256
+ capability
257
+ for capability in GRANTABLE_CAPABILITIES
258
+ if not (capability == "memory.write.organization" and _workspace_bound(auth))
259
+ ]
260
+ return {
261
+ "grantable_capabilities": grantable,
262
+ # The scope this console issues into: its own workspace, or the organization.
263
+ **_scope_fields(auth.workspace_id if _workspace_bound(auth) else None, names),
264
+ "api_keys": [_key_row(key, auth, names) for key in keys],
265
+ "connection_links": [_link_row(link, now, names) for link in links],
266
+ "rest_url": get_settings().public_base_url,
267
+ "mcp_url": get_settings().public_mcp_url,
268
+ }
269
+
270
+
271
+ @settings_router.post("/api-keys", status_code=201)
272
+ def create_key(
273
+ payload: KeyCreate,
274
+ auth: AuthContext = Depends(_manager),
275
+ session: Session = Depends(get_session),
276
+ ) -> dict:
277
+ workspace_id = _issue_scope(session, auth, payload.workspace_id, payload.capabilities)
278
+ key, raw = _mint_key(
279
+ session,
280
+ organization_id=auth.organization_id,
281
+ workspace_id=workspace_id,
282
+ name=payload.name,
283
+ capabilities=payload.capabilities,
284
+ )
285
+ audit(
286
+ session,
287
+ auth,
288
+ "api_key.create",
289
+ resource_type="api_key",
290
+ resource_id=str(key.id),
291
+ detail={
292
+ "name": payload.name,
293
+ "capabilities": payload.capabilities,
294
+ "workspace_id": str(workspace_id) if workspace_id else None,
295
+ },
296
+ )
297
+ session.commit()
298
+ session.refresh(key)
299
+ names = _workspace_names(session, auth.organization_id)
300
+ return {**_key_row(key, auth, names), "credential": raw}
301
+
302
+
303
+ @settings_router.delete("/api-keys/{key_id}", status_code=204)
304
+ def revoke_key(
305
+ key_id: UUID, auth: AuthContext = Depends(_manager), session: Session = Depends(get_session)
306
+ ) -> None:
307
+ key = session.get(APIKey, key_id)
308
+ if key is None or not _manages(auth, key.principal.organization_id, key.principal.workspace_id):
309
+ raise HTTPException(status_code=404, detail="API key not found")
310
+ if key.principal_id == auth.principal_id:
311
+ # Revoking the key that is making the request would lock the console out.
312
+ raise HTTPException(status_code=409, detail="This is the key the console is using")
313
+ key.active = False
314
+ audit(session, auth, "api_key.revoke", resource_type="api_key", resource_id=str(key.id))
315
+ session.commit()
316
+
317
+
318
+ @settings_router.post("/connection-links", status_code=201)
319
+ def create_link(
320
+ payload: LinkCreate,
321
+ auth: AuthContext = Depends(_manager),
322
+ session: Session = Depends(get_session),
323
+ ) -> dict:
324
+ workspace_id = _issue_scope(session, auth, payload.workspace_id, payload.capabilities)
325
+ token = secrets.token_urlsafe(32)
326
+ now = datetime.now(UTC)
327
+ link = ConnectionLink(
328
+ organization_id=auth.organization_id,
329
+ workspace_id=workspace_id,
330
+ created_by_principal_id=auth.principal_id,
331
+ token_hash=_hash_link_token(token),
332
+ name=payload.name,
333
+ capabilities=payload.capabilities,
334
+ expires_at=now + timedelta(seconds=payload.expires_in_seconds),
335
+ )
336
+ session.add(link)
337
+ session.flush()
338
+ audit(
339
+ session,
340
+ auth,
341
+ "connection_link.create",
342
+ resource_type="connection_link",
343
+ resource_id=str(link.id),
344
+ detail={
345
+ "name": payload.name,
346
+ "capabilities": payload.capabilities,
347
+ "workspace_id": str(workspace_id) if workspace_id else None,
348
+ },
349
+ )
350
+ session.commit()
351
+ session.refresh(link)
352
+ base = get_settings().public_base_url.rstrip("/")
353
+ names = _workspace_names(session, auth.organization_id)
354
+ return {**_link_row(link, now, names), "url": f"{base}/onboard/{token}"}
355
+
356
+
357
+ @settings_router.delete("/connection-links/{link_id}", status_code=204)
358
+ def revoke_link(
359
+ link_id: UUID, auth: AuthContext = Depends(_manager), session: Session = Depends(get_session)
360
+ ) -> None:
361
+ link = session.get(ConnectionLink, link_id)
362
+ if link is None or not _manages(auth, link.organization_id, link.workspace_id):
363
+ raise HTTPException(status_code=404, detail="Connection link not found")
364
+ if link.revoked_at is None and link.used_at is None:
365
+ link.revoked_at = datetime.now(UTC)
366
+ audit(
367
+ session,
368
+ auth,
369
+ "connection_link.revoke",
370
+ resource_type="connection_link",
371
+ resource_id=str(link.id),
372
+ )
373
+ session.commit()
374
+
375
+
376
+ def _workspace_row(
377
+ workspace: Workspace, memories: dict[UUID, int], credentials: dict[UUID, int] | None = None
378
+ ) -> dict:
379
+ return {
380
+ "id": str(workspace.id),
381
+ "name": workspace.name,
382
+ "memories": memories.get(workspace.id, 0),
383
+ "credentials": (credentials or {}).get(workspace.id, 0),
384
+ "created_at": _iso(workspace.created_at),
385
+ }
386
+
387
+
388
+ def _organization_manager(auth: AuthContext) -> None:
389
+ if _workspace_bound(auth):
390
+ raise HTTPException(
391
+ status_code=403, detail="Only an organization-wide key can manage workspaces"
392
+ )
393
+
394
+
395
+ def _memory_counts(session: Session, organization_id: UUID) -> dict[UUID | None, int]:
396
+ return dict(
397
+ session.execute(
398
+ select(Memory.workspace_id, func.count(Memory.id))
399
+ .where(Memory.organization_id == organization_id, Memory.status == "active")
400
+ .group_by(Memory.workspace_id)
401
+ ).all()
402
+ )
403
+
404
+
405
+ @settings_router.get("/workspaces")
406
+ def list_workspaces(
407
+ auth: AuthContext = Depends(_manager), session: Session = Depends(get_session)
408
+ ) -> dict:
409
+ """The workspaces this key can issue into, with the shared memories they all read."""
410
+ statement = select(Workspace).where(Workspace.organization_id == auth.organization_id)
411
+ if _workspace_bound(auth):
412
+ statement = statement.where(Workspace.id == auth.workspace_id)
413
+ counts = _memory_counts(session, auth.organization_id)
414
+ credentials = credential_counts(session, auth.organization_id)
415
+ return {
416
+ "items": [
417
+ _workspace_row(workspace, counts, credentials) # type: ignore[arg-type]
418
+ for workspace in session.scalars(statement.order_by(Workspace.name))
419
+ ],
420
+ "shared_memories": counts.get(None, 0),
421
+ "can_manage": not _workspace_bound(auth),
422
+ }
423
+
424
+
425
+ def _save_workspace(session: Session, workspace: Workspace) -> None:
426
+ try:
427
+ session.flush()
428
+ except IntegrityError as exc:
429
+ session.rollback()
430
+ raise HTTPException(
431
+ status_code=409, detail="A workspace with that name already exists"
432
+ ) from exc
433
+
434
+
435
+ @settings_router.post("/workspaces", status_code=201)
436
+ def create_workspace(
437
+ payload: WorkspaceWrite,
438
+ auth: AuthContext = Depends(_manager),
439
+ session: Session = Depends(get_session),
440
+ ) -> dict:
441
+ _organization_manager(auth)
442
+ workspace = Workspace(organization_id=auth.organization_id, name=payload.name)
443
+ session.add(workspace)
444
+ _save_workspace(session, workspace)
445
+ audit(
446
+ session,
447
+ auth,
448
+ "workspace.create",
449
+ resource_type="workspace",
450
+ resource_id=str(workspace.id),
451
+ detail={"name": payload.name},
452
+ )
453
+ session.commit()
454
+ session.refresh(workspace)
455
+ return _workspace_row(workspace, {})
456
+
457
+
458
+ @settings_router.patch("/workspaces/{workspace_id}")
459
+ def rename_workspace(
460
+ workspace_id: UUID,
461
+ payload: WorkspaceWrite,
462
+ auth: AuthContext = Depends(_manager),
463
+ session: Session = Depends(get_session),
464
+ ) -> dict:
465
+ _organization_manager(auth)
466
+ workspace = _workspace(session, auth, workspace_id)
467
+ if workspace is None:
468
+ raise HTTPException(status_code=404, detail="Workspace not found")
469
+ previous = workspace.name
470
+ workspace.name = payload.name
471
+ _save_workspace(session, workspace)
472
+ audit(
473
+ session,
474
+ auth,
475
+ "workspace.rename",
476
+ resource_type="workspace",
477
+ resource_id=str(workspace.id),
478
+ detail={"from": previous, "to": payload.name},
479
+ )
480
+ session.commit()
481
+ session.refresh(workspace)
482
+ return _workspace_row(
483
+ workspace,
484
+ _memory_counts(session, auth.organization_id), # type: ignore[arg-type]
485
+ credential_counts(session, auth.organization_id),
486
+ )
487
+
488
+
489
+ @settings_router.delete("/workspaces/{workspace_id}")
490
+ def remove_workspace(
491
+ workspace_id: UUID,
492
+ memories: MemoryOutcome = Query(
493
+ description="What happens to its memories: organization (shared), workspace (moved "
494
+ "to `to`) or delete (forgotten; needs memory.delete)"
495
+ ),
496
+ to: UUID | None = Query(default=None, description="The workspace memories move to"),
497
+ auth: AuthContext = Depends(_manager),
498
+ session: Session = Depends(get_session),
499
+ ) -> dict:
500
+ """Delete a workspace, first sharing, moving or forgetting its memories.
501
+
502
+ Its API keys and connection links stop working; its principals are kept,
503
+ deactivated, so the audit trail still names them.
504
+ """
505
+ _organization_manager(auth)
506
+ workspace = _workspace(session, auth, workspace_id)
507
+ if workspace is None:
508
+ raise HTTPException(status_code=404, detail="Workspace not found")
509
+ target = None
510
+ if to is not None:
511
+ target = _workspace(session, auth, to)
512
+ if target is None:
513
+ raise HTTPException(status_code=404, detail="Target workspace not found")
514
+ return delete_workspace(session, auth, workspace, memories, target)
515
+
516
+
517
+ def _open_link(session: Session, token: str) -> ConnectionLink:
518
+ link = session.scalar(
519
+ select(ConnectionLink).where(ConnectionLink.token_hash == _hash_link_token(token))
520
+ )
521
+ if link is None or _link_state(link, datetime.now(UTC)) != "open":
522
+ raise HTTPException(
523
+ status_code=status.HTTP_410_GONE,
524
+ detail="This connection link is expired, revoked, or already used",
525
+ )
526
+ return link
527
+
528
+
529
+ def _manifest(link: ConnectionLink, token: str) -> dict:
530
+ config = get_settings()
531
+ base = config.public_base_url.rstrip("/")
532
+ return {
533
+ "version": "1",
534
+ "name": link.name,
535
+ "expires_at": _iso(link.expires_at),
536
+ "capabilities": sorted(link.capabilities or []),
537
+ "redeem_url": f"{base}/onboard/{token}/redeem",
538
+ "connections": {
539
+ "mcp": {
540
+ "transport": "streamable-http",
541
+ "url": config.public_mcp_url,
542
+ "authorization": "Bearer <credential>",
543
+ },
544
+ "rest": {"base_url": base, "auth": "Bearer <credential>"},
545
+ },
546
+ }
547
+
548
+
549
+ @onboard_router.get("/{token}")
550
+ @onboard_router.get("/{token}/manifest")
551
+ def manifest(token: str, session: Session = Depends(get_session)) -> dict:
552
+ return _manifest(_open_link(session, token), token)
553
+
554
+
555
+ @onboard_router.post("/{token}/redeem", status_code=201)
556
+ def redeem(token: str, payload: Redeem, session: Session = Depends(get_session)) -> dict:
557
+ link = _open_link(session, token)
558
+ granted = set(link.capabilities or [])
559
+ requested = sorted(granted if payload.capabilities is None else set(payload.capabilities))
560
+ if not requested or not set(requested) <= granted:
561
+ raise HTTPException(
562
+ status_code=status.HTTP_403_FORBIDDEN,
563
+ detail=f"This link grants only: {', '.join(sorted(granted))}",
564
+ )
565
+ now = datetime.now(UTC)
566
+ # Claim the link atomically; a concurrent redeem of the same token updates nothing.
567
+ claimed = session.execute(
568
+ update(ConnectionLink)
569
+ .where(
570
+ ConnectionLink.id == link.id,
571
+ ConnectionLink.used_at.is_(None),
572
+ ConnectionLink.revoked_at.is_(None),
573
+ ConnectionLink.expires_at > now,
574
+ )
575
+ .values(used_at=now)
576
+ .execution_options(synchronize_session=False)
577
+ ).rowcount
578
+ if claimed != 1:
579
+ session.rollback()
580
+ raise HTTPException(
581
+ status_code=status.HTTP_410_GONE,
582
+ detail="This connection link is expired, revoked, or already used",
583
+ )
584
+ key, raw = _mint_key(
585
+ session,
586
+ organization_id=link.organization_id,
587
+ workspace_id=link.workspace_id,
588
+ name=payload.agent_name,
589
+ capabilities=requested,
590
+ )
591
+ session.execute(
592
+ update(ConnectionLink).where(ConnectionLink.id == link.id).values(api_key_id=key.id)
593
+ )
594
+ audit(
595
+ session,
596
+ AuthContext(
597
+ principal_id=key.principal_id,
598
+ organization_id=link.organization_id,
599
+ workspace_id=link.workspace_id,
600
+ capabilities=frozenset(requested),
601
+ ),
602
+ "connection_link.redeem",
603
+ resource_type="connection_link",
604
+ resource_id=str(link.id),
605
+ detail={"api_key_id": str(key.id), "capabilities": requested},
606
+ )
607
+ session.commit()
608
+ config = get_settings()
609
+ return {
610
+ "agent": {"id": str(key.principal_id), "name": payload.agent_name},
611
+ "capabilities": requested,
612
+ "credential": raw,
613
+ "credential_notice": "Shown once; store it in the client secret store.",
614
+ "rest_url": config.public_base_url.rstrip("/"),
615
+ "mcp_url": config.public_mcp_url,
616
+ }