Skip to content

feat: Share runs via Python SDK#667

Open
dima-aignostics wants to merge 8 commits into
mainfrom
feat/PYSDK-132-add-run-sharing-to-python-sdk
Open

feat: Share runs via Python SDK#667
dima-aignostics wants to merge 8 commits into
mainfrom
feat/PYSDK-132-add-run-sharing-to-python-sdk

Conversation

@dima-aignostics
Copy link
Copy Markdown
Contributor

No description provided.

Copilot AI review requested due to automatic review settings June 4, 2026 11:10
@dima-aignostics dima-aignostics requested a review from a team as a code owner June 4, 2026 11:10
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR aims to add “run sharing” capabilities to the Python SDK by introducing access-control resource wrappers (grants + share tokens), wiring them into the platform client, and exposing sharing workflows through the application service and CLI.

Changes:

  • Added new access-control resource layer (AccessGrant, ShareToken, ShareTokens) and new Run helpers (list_share_grants, grant_access).
  • Added new application service + CLI commands under run share ... to list/grant/revoke access and manage share tokens.
  • Regenerated codegen artifacts/docs for updated API parameters (e.g., grants relation filter, additional run filters, run organization_id field).

Reviewed changes

Copilot reviewed 8 out of 61 changed files in this pull request and generated 18 comments.

Show a summary per file
File Description
src/aignostics/platform/resources/access.py New access-control resource models and share-token listing/creation logic.
src/aignostics/platform/resources/runs.py Adds run-level grant listing/creation helpers with caching/retry integration.
src/aignostics/platform/_client.py Exposes a share_tokens resource on Client.
src/aignostics/application/_service.py Adds service methods for run sharing and token management.
src/aignostics/application/_cli.py Adds run share ... CLI command group.
tests/aignostics/platform/resources/access_test.py Unit tests for access resources.
tests/aignostics/platform/resources/run_sharing_test.py Unit tests for run-sharing workflows (currently mismatched with implementation).
codegen/in/openapi.json + codegen/out/** Codegen updates reflecting API spec changes.

Comment thread src/aignostics/platform/resources/access.py
Comment thread src/aignostics/platform/resources/access.py
Comment thread src/aignostics/platform/resources/access.py Outdated
Comment thread src/aignostics/platform/resources/runs.py
Comment thread src/aignostics/platform/resources/runs.py Outdated
Comment thread src/aignostics/platform/_client.py Outdated
Comment thread src/aignostics/platform/resources/access.py Outdated
Comment thread tests/aignostics/platform/resources/run_sharing_test.py
Comment thread tests/aignostics/platform/resources/access_test.py Outdated
Comment thread src/aignostics/platform/resources/runs.py
@codecov
Copy link
Copy Markdown

codecov Bot commented Jun 4, 2026

Codecov Report

❌ Patch coverage is 35.23132% with 182 lines in your changes missing coverage. Please review.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/aignostics/application/_cli.py 16.03% 110 Missing ⚠️
src/aignostics/application/_service.py 13.33% 65 Missing ⚠️
src/aignostics/platform/resources/access.py 88.13% 7 Missing ⚠️
Files with missing lines Coverage Δ
src/aignostics/platform/_client.py 93.18% <100.00%> (+0.15%) ⬆️
src/aignostics/platform/resources/runs.py 85.41% <100.00%> (+0.74%) ⬆️
src/aignostics/platform/resources/access.py 88.13% <88.13%> (ø)
src/aignostics/application/_service.py 55.76% <13.33%> (-8.43%) ⬇️
src/aignostics/application/_cli.py 64.49% <16.03%> (-11.06%) ⬇️

... and 5 files with indirect coverage changes

Copilot AI review requested due to automatic review settings June 4, 2026 14:41
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 61 changed files in this pull request and generated 20 comments.

Comment thread src/aignostics/platform/resources/access.py Outdated
Comment thread src/aignostics/platform/resources/access.py Outdated
Comment thread src/aignostics/platform/resources/runs.py Outdated
Comment on lines +708 to +713
lambda **kw: fetch_grant_page(
nocache=nocache,
subject_type=subject_type,
subject_id=subject_id,
**kw,
),
Comment thread src/aignostics/platform/resources/runs.py Outdated
Comment thread src/aignostics/application/_cli.py
Comment thread tests/aignostics/platform/resources/access_test.py Outdated
Comment thread tests/aignostics/platform/resources/access_test.py Outdated
Comment thread tests/aignostics/platform/resources/access_test.py Outdated
Comment thread tests/aignostics/platform/resources/access_test.py Outdated
Copilot AI review requested due to automatic review settings June 4, 2026 18:45
dima-aignostics and others added 6 commits June 4, 2026 20:47
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Wraps the create_grant API call in a Retrying block with exponential
backoff and jitter, consistent with list_share_grants and other methods.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
… grants

- Add --expires-at option to `application run share token create` CLI command;
  accepts ISO 8601 string, defaults to UTC if no timezone given
- Add expires_at parameter to Service.application_run_create_share_token()
- Promote organization_id from --option to positional [ORGANIZATION_ID] argument
  in both `share organization grant` and `share organization revoke` commands
- Add organization_id parameter to application_run_unshare_with_organization()
  so revoke filters grants by org (defaults to authenticated user's own org)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 61 changed files in this pull request and generated 9 comments.

Comment thread src/aignostics/platform/resources/access.py
Comment thread src/aignostics/platform/resources/runs.py
Comment thread src/aignostics/platform/resources/runs.py Outdated
Comment thread src/aignostics/platform/resources/runs.py Outdated
Comment thread src/aignostics/application/_service.py
Comment thread src/aignostics/application/_service.py
Comment thread src/aignostics/application/_service.py
Comment thread src/aignostics/application/_cli.py
Comment thread src/aignostics/platform/resources/access.py
@dima-aignostics dima-aignostics force-pushed the feat/PYSDK-132-add-run-sharing-to-python-sdk branch from 3bbec8d to 1131c91 Compare June 4, 2026 18:53
Copilot AI review requested due to automatic review settings June 4, 2026 18:55
@dima-aignostics dima-aignostics force-pushed the feat/PYSDK-132-add-run-sharing-to-python-sdk branch from 1131c91 to fa0f3b9 Compare June 4, 2026 18:55
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 9 out of 63 changed files in this pull request and generated 7 comments.

Comment thread src/aignostics/platform/resources/access.py Outdated
Comment thread src/aignostics/platform/resources/runs.py
Comment thread src/aignostics/platform/resources/runs.py
Comment thread src/aignostics/application/_service.py Outdated
Comment thread src/aignostics/application/_service.py
Comment thread src/aignostics/application/_service.py
Comment thread src/aignostics/application/_cli.py
@dima-aignostics dima-aignostics force-pushed the feat/PYSDK-132-add-run-sharing-to-python-sdk branch from fa0f3b9 to c4e64be Compare June 4, 2026 19:26
Copilot AI review requested due to automatic review settings June 5, 2026 13:41
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented Jun 5, 2026

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 10 out of 64 changed files in this pull request and generated 4 comments.

Comment on lines +382 to +396
for t in self._api.list_share_tokens_v1_access_share_tokens_get(
run_id=run_id,
revoked=False,
_request_timeout=settings().run_timeout,
_headers={"User-Agent": user_agent()},
**kwargs, # pyright: ignore[reportArgumentType]
)
]
)

return paginate(
lambda **kwargs: list_data_with_retry(
nocache=nocache,
**kwargs,
),
Comment on lines +1469 to +1474
if expires_at is not None:
try:
expires_at_dt = datetime.fromisoformat(expires_at)
if expires_at_dt.tzinfo is None:
expires_at_dt = expires_at_dt.replace(tzinfo=UTC)
except ValueError:
Comment on lines +1328 to +1390
def application_run_organization_grants(
self,
run_id: str,
page_size: int = LIST_APPLICATION_RUNS_MAX_PAGE_SIZE,
) -> Iterator[AccessGrant]:
"""List active organization grants for a run.

Args:
run_id (str): The ID of the run.
page_size (int): Number of grants per page. Defaults to max (100).

Returns:
Iterator[AccessGrant]: Active grants for this run.

Raises:
NotFoundException: If the run is not found.
RuntimeError: If the request fails unexpectedly.
"""
try:
return self.application_run(run_id).list_share_grants(
subject_type=SubjectType.ORGANIZATION_USER,
relation=[GrantRelation.VIEWER],
page_size=page_size,
)
except NotFoundException as e:
message = f"Application run with ID '{run_id}' not found: {e}"
logger.warning(message)
raise NotFoundException(message) from e
except Exception as e:
message = f"Failed to list organization grants for run '{run_id}': {e}"
logger.exception(message)
raise RuntimeError(message) from e

def application_run_share_tokens(
self,
run_id: str,
page_size: int = LIST_APPLICATION_RUNS_MAX_PAGE_SIZE,
) -> Iterator[ShareToken]:
"""List active share tokens for a run.

Args:
run_id (str): The ID of the run.
page_size (int): Number of tokens per page. Defaults to max (100).

Returns:
Iterator[ShareToken]: Active share tokens.

Raises:
NotFoundException: If the run is not found.
RuntimeError: If the request fails unexpectedly.
"""
try:
return self._get_platform_client().share_tokens.list(run_id=run_id, page_size=page_size)
except NotFoundException as e:
message = f"Application run with ID '{run_id}' not found: {e}"
logger.warning(message)
raise NotFoundException(message) from e
except Exception as e:
message = f"Failed to list share tokens for run '{run_id}': {e}"
logger.exception(message)
raise RuntimeError(message) from e

def application_run_share_with_organization(
Comment on lines +1316 to +1509
@share_app.command("status")
def run_share_status(
run_id: Annotated[str, typer.Argument(..., help="Id of the run")],
format: Annotated[str, typer.Option(help="Output format: 'text' (default) or 'json'")] = "text", # noqa: A002
) -> None:
"""Show sharing status: active organization grants and share tokens."""
try:
org_grants = list(Service().application_run_organization_grants(run_id))
tokens = list(Service().application_run_share_tokens(run_id))

if format == "json":
print(
json.dumps(
{
"organization_grants": [g.model_dump() for g in org_grants],
"share_tokens": [t.model_dump() for t in tokens],
},
indent=2,
default=str,
),
)
else:
console.print(f"[bold]Organization grants[/bold] ({len(org_grants)}):")
for g in org_grants:
console.print(f" {g.grant_id} subject={g.subject_id} relation={g.relation.value}")

console.print(f"[bold]Share tokens[/bold] ({len(tokens)}):")
for t in tokens:
expires = t.expires_at.isoformat() if t.expires_at else "never"
created = t.created_at.isoformat()
console.print(f" {t.share_token_id} created={created} expires={expires}")
except NotFoundException:
console.print(f"[warning]Warning:[/warning] Run with ID '{run_id}' not found.")
sys.exit(2)
except Exception as e:
logger.exception("Failed to retrieve share status for run '{}'", run_id)
console.print(f"[error]Error:[/error] Failed to retrieve share status for run '{run_id}': {e}")
sys.exit(1)


@share_organization_app.command("list")
def run_share_organization_list(
run_id: Annotated[str, typer.Argument(..., help="Id of the run")],
format: Annotated[str, typer.Option(help="Output format: 'text' (default) or 'json'")] = "text", # noqa: A002
) -> None:
"""List active organization grants for a run."""
try:
grants = list(Service().application_run_organization_grants(run_id))
if format == "json":
print(json.dumps([g.model_dump() for g in grants], indent=2, default=str))
else:
if not grants:
console.print("No active organization grants.")
for g in grants:
console.print(
f"{g.grant_id} subject={g.subject_id}"
f" relation={g.relation.value} created={g.created_at.isoformat()}",
)
except NotFoundException:
console.print(f"[warning]Warning:[/warning] Run with ID '{run_id}' not found.")
sys.exit(2)
except Exception as e:
logger.exception("Failed to list organization grants for run '{}'", run_id)
console.print(f"[error]Error:[/error] Failed to list organization grants for run '{run_id}': {e}")
sys.exit(1)


@share_organization_app.command("grant")
def run_share_organization_grant(
run_id: Annotated[str, typer.Argument(..., help="Id of the run to share")],
organization_id: Annotated[
str | None,
typer.Argument(help="Organization ID to share with (defaults to your own organization)"),
] = None,
format: Annotated[str, typer.Option(help="Output format: 'text' (default) or 'json'")] = "text", # noqa: A002
) -> None:
"""Share a run with all users in an organization."""
try:
grant = Service().application_run_share_with_organization(run_id, organization_id=organization_id)
if format == "json":
print(json.dumps(grant.model_dump(), indent=2, default=str))
else:
console.print(f"Run '{run_id}' is now shared with organization (grant {grant.grant_id}).")
except NotFoundException:
console.print(f"[warning]Warning:[/warning] Run with ID '{run_id}' not found.")
sys.exit(2)
except Exception as e:
logger.exception("Failed to share run '{}' with organization", run_id)
console.print(f"[error]Error:[/error] Failed to share run '{run_id}' with organization: {e}")
sys.exit(1)


@share_organization_app.command("revoke")
def run_share_organization_revoke(
run_id: Annotated[str, typer.Argument(..., help="Id of the run to unshare")],
organization_id: Annotated[
str | None,
typer.Argument(help="Organization ID to revoke access for (defaults to your own organization)"),
] = None,
) -> None:
"""Revoke organization grants for a run."""
try:
Service().application_run_unshare_with_organization(run_id, organization_id=organization_id)
console.print(f"Organization access revoked for run '{run_id}'.")
except NotFoundException:
console.print(f"[warning]Warning:[/warning] Run with ID '{run_id}' not found.")
sys.exit(2)
except Exception as e:
logger.exception("Failed to revoke organization access for run '{}'", run_id)
console.print(f"[error]Error:[/error] Failed to revoke organization access for run '{run_id}': {e}")
sys.exit(1)


@share_token_app.command("list")
def run_share_token_list(
run_id: Annotated[str, typer.Argument(..., help="Id of the run")],
format: Annotated[str, typer.Option(help="Output format: 'text' (default) or 'json'")] = "text", # noqa: A002
) -> None:
"""List active share tokens for a run."""
try:
tokens = list(Service().application_run_share_tokens(run_id))

if format == "json":
print(json.dumps([t.model_dump() for t in tokens], indent=2, default=str))
else:
if not tokens:
console.print("No active share tokens.")
for t in tokens:
expires = t.expires_at.isoformat() if t.expires_at else "never"
created = t.created_at.isoformat() if t.created_at else "unknown"
console.print(f"{t.share_token_id} created={created} expires={expires}")
except NotFoundException:
console.print(f"[warning]Warning:[/warning] Run with ID '{run_id}' not found.")
sys.exit(2)
except Exception as e:
logger.exception("Failed to list share tokens for run '{}'", run_id)
console.print(f"[error]Error:[/error] Failed to list share tokens for run '{run_id}': {e}")
sys.exit(1)


@share_token_app.command("create")
def run_share_token_create(
run_id: Annotated[str, typer.Argument(..., help="Id of the run to create a share token for")],
expires_at: Annotated[
str | None,
typer.Option(
help="Expiry datetime in ISO 8601 format, e.g. '2026-12-31T23:59:59Z'. Omit for a non-expiring token.",
),
] = None,
format: Annotated[str, typer.Option(help="Output format: 'text' (default) or 'json'")] = "text", # noqa: A002
) -> None:
"""Create a share token for a run. The token value is shown only once."""
expires_at_dt: datetime | None = None
if expires_at is not None:
try:
expires_at_dt = datetime.fromisoformat(expires_at)
if expires_at_dt.tzinfo is None:
expires_at_dt = expires_at_dt.replace(tzinfo=UTC)
except ValueError:
console.print(
f"[error]Error:[/error] Invalid --expires-at value '{expires_at}'. "
"Use ISO 8601 format, e.g. '2026-12-31T23:59:59Z'."
)
sys.exit(1)
try:
token = Service().application_run_create_share_token(run_id, expires_at=expires_at_dt)
if format == "json":
print(json.dumps(token.model_dump(), indent=2, default=str))
else:
expires = token.expires_at.isoformat() if token.expires_at else "never"
console.print(f"Share token created for run '{run_id}'.")
console.print(f" Token ID : {token.share_token_id}")
console.print(f" Token : [bold]{token.share_token}[/bold]")
console.print(f" Expires : {expires}")
console.print("[yellow]Save the token value — it will not be shown again.[/yellow]")
except NotFoundException:
console.print(f"[warning]Warning:[/warning] Run with ID '{run_id}' not found.")
sys.exit(2)
except Exception as e:
logger.exception("Failed to create share token for run '{}'", run_id)
console.print(f"[error]Error:[/error] Failed to create share token for run '{run_id}': {e}")
sys.exit(1)


@share_token_app.command("revoke")
def run_share_token_revoke(
run_id: Annotated[str, typer.Argument(..., help="Id of the run")],
token_id: Annotated[str, typer.Argument(..., help="Id of the share token to revoke")],
) -> None:
"""Revoke a share token."""
try:
Service().application_run_revoke_share_token(run_id, token_id)
console.print(f"Share token '{token_id}' revoked for run '{run_id}'.")
except NotFoundException:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants