pulse-agent-sdk 0.1.1__tar.gz

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 (36) hide show
  1. pulse_agent_sdk-0.1.1/.gitignore +13 -0
  2. pulse_agent_sdk-0.1.1/CHANGELOG.md +15 -0
  3. pulse_agent_sdk-0.1.1/CONTRIBUTING.md +16 -0
  4. pulse_agent_sdk-0.1.1/LICENSE +21 -0
  5. pulse_agent_sdk-0.1.1/Makefile +18 -0
  6. pulse_agent_sdk-0.1.1/PKG-INFO +67 -0
  7. pulse_agent_sdk-0.1.1/README.md +32 -0
  8. pulse_agent_sdk-0.1.1/SECURITY.md +5 -0
  9. pulse_agent_sdk-0.1.1/docs/production.md +26 -0
  10. pulse_agent_sdk-0.1.1/docs/protocol-parity.md +31 -0
  11. pulse_agent_sdk-0.1.1/docs/quickstart.md +50 -0
  12. pulse_agent_sdk-0.1.1/docs/releasing.md +15 -0
  13. pulse_agent_sdk-0.1.1/examples/scout.py +151 -0
  14. pulse_agent_sdk-0.1.1/fixtures/agent-session-created.json +39 -0
  15. pulse_agent_sdk-0.1.1/fixtures/resource-webhook-key.json +1 -0
  16. pulse_agent_sdk-0.1.1/fixtures/resource-webhook.json +12 -0
  17. pulse_agent_sdk-0.1.1/pyproject.toml +75 -0
  18. pulse_agent_sdk-0.1.1/scripts/check_release.py +87 -0
  19. pulse_agent_sdk-0.1.1/scripts/generate_types.py +179 -0
  20. pulse_agent_sdk-0.1.1/scripts/smoke_install.py +24 -0
  21. pulse_agent_sdk-0.1.1/specs/SHA256SUMS +6 -0
  22. pulse_agent_sdk-0.1.1/specs/SOURCES.md +13 -0
  23. pulse_agent_sdk-0.1.1/specs/agent-app-manifest.schema.json +156 -0
  24. pulse_agent_sdk-0.1.1/specs/agent-sessions.yaml +1072 -0
  25. pulse_agent_sdk-0.1.1/specs/pulse-api.agent-sdk.yaml +4050 -0
  26. pulse_agent_sdk-0.1.1/src/pulse_agent_sdk/__init__.py +137 -0
  27. pulse_agent_sdk-0.1.1/src/pulse_agent_sdk/_generated.py +180 -0
  28. pulse_agent_sdk-0.1.1/src/pulse_agent_sdk/_generated_api.py +928 -0
  29. pulse_agent_sdk-0.1.1/src/pulse_agent_sdk/client.py +404 -0
  30. pulse_agent_sdk-0.1.1/src/pulse_agent_sdk/errors.py +62 -0
  31. pulse_agent_sdk-0.1.1/src/pulse_agent_sdk/handler.py +199 -0
  32. pulse_agent_sdk-0.1.1/src/pulse_agent_sdk/oauth.py +381 -0
  33. pulse_agent_sdk-0.1.1/src/pulse_agent_sdk/py.typed +1 -0
  34. pulse_agent_sdk-0.1.1/src/pulse_agent_sdk/stop.py +82 -0
  35. pulse_agent_sdk-0.1.1/src/pulse_agent_sdk/webhooks.py +295 -0
  36. pulse_agent_sdk-0.1.1/tests/test_protocol.py +735 -0
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ .pytest_cache/
3
+ .ruff_cache/
4
+ .mypy_cache/
5
+ .venv/
6
+ *.egg-info/
7
+ dist/
8
+ build/
9
+ .env
10
+ .env.*
11
+ !.env.example
12
+ *.tokens.json
13
+ .DS_Store
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1
4
+
5
+ First PyPI release. Updates Trusted Publishing to support core metadata 2.5 and
6
+ validates distributions in CI with the same Twine and packaging versions as the publisher.
7
+
8
+ ## 0.1.0
9
+
10
+ Initial GitHub beta for Pulse Agent Apps.
11
+
12
+ - Async OAuth installation with S256 PKCE, shared refresh locking, revocation handling, and credential-operation draining.
13
+ - Signed webhook verification, post-ack callbacks, durable inbox intake and restart-safe event restoration, scoped deduplication, Stop signals, and permission events.
14
+ - Typed Agent Sessions, activities, signals, issue operations and pagination generated from pinned OpenAPI, with typed failures and bounded retries.
15
+ - Python 3.11–3.14 CI, wheel and source distribution checks, a deterministic Scout example, and PyPI Trusted Publishing.
@@ -0,0 +1,16 @@
1
+ # Contributing
2
+
3
+ Use Python 3.11–3.14 and a virtual environment.
4
+
5
+ ```bash
6
+ python -m venv .venv
7
+ source .venv/bin/activate
8
+ python -m pip install -e '.[dev]'
9
+ make -j3 check
10
+ ```
11
+
12
+ Use `make test` for the fast mocked suite. Tests and the Scout example run without Pulse credentials. The [README](README.md#development) lists equivalent commands for Windows and other environments without Make.
13
+
14
+ Open a pull request with a focused change and the checks you ran. Add a mocked regression test for protocol changes and preserve the public Python API where possible. Review [contract sources](specs/SOURCES.md) before updating a spec and regenerate the wire types with `python scripts/generate_types.py`. Keep changes to generated files tied to the generator or pinned spec.
15
+
16
+ Maintainers use the [release runbook](docs/releasing.md). Report vulnerabilities privately using the instructions in [SECURITY.md](SECURITY.md).
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pulse
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,18 @@
1
+ PYTHON ?= python
2
+
3
+ .PHONY: check contract lint types test
4
+
5
+ check: contract lint types test
6
+
7
+ contract:
8
+ shasum -a 256 -c specs/SHA256SUMS
9
+ $(PYTHON) scripts/generate_types.py --check
10
+
11
+ lint:
12
+ $(PYTHON) -m ruff check src tests scripts examples
13
+
14
+ types:
15
+ $(PYTHON) -m mypy
16
+
17
+ test:
18
+ $(PYTHON) -m pytest -q
@@ -0,0 +1,67 @@
1
+ Metadata-Version: 2.5
2
+ Name: pulse-agent-sdk
3
+ Version: 0.1.1
4
+ Summary: Python SDK for building Pulse Agent Apps
5
+ Project-URL: Documentation, https://trypulse.tech/docs/developers/agents
6
+ Project-URL: Repository, https://github.com/try-pulse/pulse-agent-sdk-python
7
+ Project-URL: Issues, https://github.com/try-pulse/pulse-agent-sdk-python/issues
8
+ Project-URL: Changelog, https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/CHANGELOG.md
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: agent,oauth,pulse,sdk,webhooks
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: httpx<1,>=0.26
23
+ Provides-Extra: dev
24
+ Requires-Dist: mypy<3,>=1.19; extra == 'dev'
25
+ Requires-Dist: pytest-asyncio<2,>=1; extra == 'dev'
26
+ Requires-Dist: pytest<10,>=8; extra == 'dev'
27
+ Requires-Dist: pyyaml<7,>=6; extra == 'dev'
28
+ Requires-Dist: ruff<1,>=0.11; extra == 'dev'
29
+ Requires-Dist: types-pyyaml<7,>=6; extra == 'dev'
30
+ Provides-Extra: release
31
+ Requires-Dist: build<2,>=1.2; extra == 'release'
32
+ Requires-Dist: packaging<27,>=24; extra == 'release'
33
+ Requires-Dist: twine<8,>=7; extra == 'release'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # Pulse Agent SDK for Python
37
+
38
+ Build a Pulse Agent App with Python 3.11–3.14. The SDK handles OAuth installation, signed webhooks, Agent Sessions, and activities through an async `httpx` client.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ python -m pip install pulse-agent-sdk
44
+ ```
45
+
46
+ For an unpublished build, install the supplied wheel or run `python -m pip install .` from the source checkout.
47
+
48
+ ## Get started
49
+
50
+ - [Python quickstart](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/docs/quickstart.md) covers installation, webhook intake, and sending an activity.
51
+ - [Scout example](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/examples/scout.py) runs OAuth, signed deliveries, deduplication, and Stop entirely offline.
52
+ - [Production integration](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/docs/production.md) covers durable storage, access changes, cancellation, and retries.
53
+
54
+ From a checkout or unpacked source distribution, run `python examples/scout.py` after installing the package. It needs no credentials or model.
55
+
56
+ ## Development
57
+
58
+ ```bash
59
+ python -m pip install -e '.[dev]'
60
+ make -j3 check
61
+ ```
62
+
63
+ `make test` runs the mocked suite by itself. On systems without Make, run `python -m pytest`, `python -m ruff check src tests scripts examples`, `python -m mypy`, and `python scripts/generate_types.py --check`. The release toolchain is available separately with `.[release]`.
64
+
65
+ See [CONTRIBUTING.md](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/CONTRIBUTING.md) for pull requests and [SECURITY.md](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/SECURITY.md) for private reporting.
66
+
67
+ The [pinned contracts](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/specs/SOURCES.md) come from the [TypeScript SDK](https://github.com/try-pulse/pulse-agent-sdk). The [parity audit](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/docs/protocol-parity.md) records wire behavior and implementation differences.
@@ -0,0 +1,32 @@
1
+ # Pulse Agent SDK for Python
2
+
3
+ Build a Pulse Agent App with Python 3.11–3.14. The SDK handles OAuth installation, signed webhooks, Agent Sessions, and activities through an async `httpx` client.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ python -m pip install pulse-agent-sdk
9
+ ```
10
+
11
+ For an unpublished build, install the supplied wheel or run `python -m pip install .` from the source checkout.
12
+
13
+ ## Get started
14
+
15
+ - [Python quickstart](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/docs/quickstart.md) covers installation, webhook intake, and sending an activity.
16
+ - [Scout example](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/examples/scout.py) runs OAuth, signed deliveries, deduplication, and Stop entirely offline.
17
+ - [Production integration](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/docs/production.md) covers durable storage, access changes, cancellation, and retries.
18
+
19
+ From a checkout or unpacked source distribution, run `python examples/scout.py` after installing the package. It needs no credentials or model.
20
+
21
+ ## Development
22
+
23
+ ```bash
24
+ python -m pip install -e '.[dev]'
25
+ make -j3 check
26
+ ```
27
+
28
+ `make test` runs the mocked suite by itself. On systems without Make, run `python -m pytest`, `python -m ruff check src tests scripts examples`, `python -m mypy`, and `python scripts/generate_types.py --check`. The release toolchain is available separately with `.[release]`.
29
+
30
+ See [CONTRIBUTING.md](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/CONTRIBUTING.md) for pull requests and [SECURITY.md](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/SECURITY.md) for private reporting.
31
+
32
+ The [pinned contracts](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/specs/SOURCES.md) come from the [TypeScript SDK](https://github.com/try-pulse/pulse-agent-sdk). The [parity audit](https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/docs/protocol-parity.md) records wire behavior and implementation differences.
@@ -0,0 +1,5 @@
1
+ # Security policy
2
+
3
+ Report SDK vulnerabilities privately using **Security → Report a vulnerability** in the [Python SDK repository](https://github.com/try-pulse/pulse-agent-sdk-python/security). Include the package version, a minimal reproduction using synthetic data, and the impact.
4
+
5
+ If private reporting is unavailable, contact a Pulse maintainer privately for a secure channel. Keep credentials, signing secrets, personal data, and vulnerability details out of public issues and pull requests.
@@ -0,0 +1,26 @@
1
+ # Production integration
2
+
3
+ ## OAuth and HTTP lifecycle
4
+
5
+ - Keep the install route administrator-only. Bind the callback to the initiating browser session and consume OAuth state atomically with a short TTL. Protect and expire stored PKCE verifiers and keep registration and environment namespaces separate.
6
+ - Encrypt token records with a managed key. Implement `AuthStore.lock_installation` across all replicas for one installation, covering the refresh exchange and atomic write of both returned tokens. A lease must remain valid through the write. If a process dies during exchange, reauthorization may be required. Pulse rotates refresh tokens and the SDK leaves ambiguous OAuth exchanges to the operator or consumer.
7
+ - Give the SDK a dedicated HTTP client and configure its timeouts and TLS there. Reuse it across requests. During shutdown stop accepting deliveries, settle workers or `await handler.idle()`, then `await auth.drain()` before closing HTTP. Never log token records via serialization, signed bodies, Basic or Bearer headers, callback URLs, or raw error details.
8
+ - `revoke_token` calls Pulse's OAuth endpoint, which returns 200 even for unknown tokens. On a verified `OAuthApp/revoked` event, fence work for the installation and call `forget_installation`. A refresh with `invalid_grant` removes the stored grant. An API `401 INSTALLATION_REVOKED` removes the matching cached credential under the installation lock.
9
+
10
+ ## Webhook inbox
11
+
12
+ Read raw bytes with an ingress size limit. Pass all headers to `WebhookReceiver.receive`, preserving duplicates where your framework permits it. It checks the raw-body HMAC, the signed timestamp, routing fields, and workspace. Return 2xx within five seconds once the inbox commits. Map `WebhookError.status` to the HTTP response and return a retryable 5xx when the inbox transaction fails. Ping is verified and acknowledged without an inbox row.
13
+
14
+ Put a unique constraint on `(installation_id, occurrence)` per app and environment. Insert atomically and retain the key beyond Pulse's last retry, at least 24 hours for ordinary delivery. Store the verified `event.payload` and its key from trusted ingress. Restore it with `WebhookEvent.from_verified_payload` from trusted storage only. In a worker, use a lease or transaction to claim work and fence stale runners. Persist a separate `idempotency_key` for each activity so worker retries and restarts can replay that step safely. `for_event` checks that the installation and event agree on workspace and app user. Apply your own policy and check current access before side effects.
15
+
16
+ `WebhookHandler` is for in-process callbacks. Pass `workspace_id`, and share `handler.stops` with `PulseAgentClient.for_event(..., stops=handler.stops)`. `handle` returns before dispatch, so use `on_error` for callback failures. A custom `DedupeStore` atomically claims a compact JSON string holding `[installation_id, occurrence]`. Callback dispatch can be lost on process exit. Use the inbox when work must survive restarts.
17
+
18
+ ## Stop and access changes
19
+
20
+ - A `prompted` event with `agent_activity.signal == "stop"` is an explicit Stop, including undelegation. Prioritize it over queued work, cancel the running task, and fence any late writes. Send one final `response` or `error` with a stable key during the 60-second grace period. A normal human prompt can open a new run.
21
+ - A `SessionEndedError` is terminal for the current run. Stop and make no more writes. Uninstallation, team removal, and issue deletion can end a session immediately and have no grace period.
22
+ - `event.permission_change` gives the new team coverage and removed IDs. Invalidate cached authorization and fence work that lost access. Handle issue removals similarly when subscribed. The SDK leaves team-to-run mapping and cancellation policy with the worker. In callback mode a `StopSignal` wakes cooperative tasks, and the application calls `task.cancel()` where needed and releases entries with `SessionStops.release` after settlement.
23
+
24
+ ## Retries
25
+
26
+ The SDK retries rate limits and honors `Retry-After` up to 60 seconds. Transport errors, 408s, and transient 5xx responses are retried for repeatable operations, including activity creates carrying a key. The initial delay is up to 250 ms with jitter. Proactive creation on an issue has no idempotency key on the wire, so reconcile an ambiguous outcome before issuing a second create. Use `PulseApiError.code`, `.status`, and `.retry_after` (seconds), `PulseTransportError.timed_out`, and the separate terminal `InstallationRevokedError` and `SessionEndedError`. Treat `.details` as sensitive application data.
@@ -0,0 +1,31 @@
1
+ # Protocol parity
2
+
3
+ Audited against the TypeScript SDK at `b2c37dc` and the local working-tree receiver, client, and OAuth changes. The [pinned OpenAPI snapshots](../specs/SOURCES.md) govern the HTTP contract. The tests exercise mocked HTTP and replay the shared signed delivery and resource-key vectors.
4
+
5
+ | Wire operation or event | Python behavior and evidence |
6
+ | --- | --- |
7
+ | `GET /oauth/authorize` | `start_install` builds an `actor=app` URL with comma-separated scopes, single-use state and S256 PKCE. Tests check the challenge against the exchanged verifier. |
8
+ | `POST /oauth/token`, code grant | Sends form data and raw Basic credentials. Validates app identity, token type and workspace before saving. Tests cover mismatched workspace, expired or reused state, and cancelled callers. |
9
+ | `POST /oauth/token`, refresh grant | Atomically stores the rotated pair under the installation lock. Concurrent rejected-token callers reuse a winning refresh. Tests cover shared stores, caller cancellation, missing rotation, and `invalid_grant`. |
10
+ | `POST /oauth/revoke` | Sends `client_id` and `token` with an optional `token_type_hint`. A 200 is best effort per spec. |
11
+ | Webhook verification and dispatch | Lowercase hex HMAC over raw bytes, freshness from signed milliseconds, workspace scoping, Ping handling, callback acknowledgment before dispatch, and durable enqueue before acknowledgment. Dedupe uses an installation/event pair or a stable hash of signed resource fields. |
12
+ | `prompted`, `revoked`, `teamAccessChanged` | Stop is identified by the signal. A new human prompt resets the process-local signal. Revocation stops work for the installation. Permission callbacks expose team coverage and removed IDs for application fencing. |
13
+ | `GET /agent-sessions` | Repeated `state` parameters, issue filters, limit, and opaque `next_cursor`. `iter_sessions` rejects missing or repeated cursors. |
14
+ | `POST /agent-sessions` | Issue and comment helpers send exactly one target. The issue form skips ambiguous retries. The comment form retries using Pulse's reuse of open thread sessions. |
15
+ | `GET/PATCH /agent-sessions/{id}` | Reads the session and updates plan, replacement URLs, or incremental URL additions and removals. A write's `409 SESSION_ENDED` stops the run. |
16
+ | `GET /agent-sessions/{id}/activities` | Single-page requests use the server defaults when filters are omitted. Async iteration requests up to 200 rows and follows `last_seq` across gaps. Human prompts and superseded ephemeral entries remain in the returned history. |
17
+ | `POST /agent-sessions/{id}/activities` | One key per call, stable across retries. Helpers cover thought, nullable action parameter, response, error, and elicitation with `select` or `auth`. Ephemeral helpers cover thought and action. |
18
+ | `GET /auth/me`, `GET/PUT /issues/{id}` | Uses app Bearer auth and `X-Workspace-ID`. Issue status helper accepts `in_progress` and `qa`. Generated types describe the actual response objects. |
19
+ | HTTP failures | One authentication recovery for ordinary 401s, no retry on `SESSION_ENDED` or explicit installation revocation, and capped transient retries with typed failures and retry delays. |
20
+
21
+ ## Exact contract differences
22
+
23
+ - The token endpoint description says refresh returns a **new** `refresh_token` every time, and app responses include `actor`, `installation_id`, `workspace_id`, and `app_user_id`. TypeScript's refresh fallback keeps the old token when the field is absent and carries forward identity without validating a returned identity. Python checks the app identity and requires a rotated token. The common token schema marks those app-only fields optional because it also covers user grants.
24
+ - TypeScript's `ActivityOptions` exposes `ephemeral` on `elicit`, but the helper silently ignores it. The spec restricts it to thought and action. Python applies that restriction at the helper surface. Pulse enforces field combinations on lower-level typed activity input.
25
+ - TypeScript's `ElicitOptions` and agent session filters behave similarly on the wire. Python iterates lazily and detects repeating cursors; TypeScript's activity collector stops when an empty page has `has_more` and has no cursor-progress guard. Python follows a valid advancing `last_seq` and surfaces malformed pages as a typed error.
26
+ - The envelope description broadly says to deduplicate on `data.event_id`. The referenced Issue, Comment, and Project schemas omit that field. The TypeScript durable receiver and Python both derive the fallback hash from signed fields, excluding the per-attempt `webhook_timestamp`. Python also uses that scoped key in callback mode. TypeScript callbacks claim only a bare `event_id`. Neither SDK uses unsigned delivery headers as identity.
27
+ - TypeScript's error comment says explicit API revocation drops stored tokens, but its client branch only throws. Python compares the refused credential before removing the cached record, preserving a replacement installed during the request. Permission changes remain application callbacks in both SDKs.
28
+
29
+ ## Python surface
30
+
31
+ The Python SDK uses async tasks for cancellation, `TypedDict` wire data, and a consumer-owned async HTTP pool and storage. Its client exposes the pinned operations and helpers. The TypeScript client additionally exposes a generic request method, a standalone token provider, framework-specific webhook adapters, and a local JSON token store. Python's `AuthStore` provides a shared locking contract; its in-package store is in memory. Typed response models preserve JSON keys and describe the pinned schema; runtime checks focus on identity, routing, response shape, and pagination.
@@ -0,0 +1,50 @@
1
+ # Python quickstart
2
+
3
+ Install the SDK with `python -m pip install pulse-agent-sdk` after the PyPI release, or install the built wheel. Use Python 3.11–3.14.
4
+
5
+ From a checkout or unpacked sdist, run `python examples/scout.py` for a complete offline run. It exchanges a mocked OAuth code, verifies signed deliveries, commits them to a SQLite inbox, and answers a delegation and Stop. You should see a thought, an issue summary, and `Stopped.`
6
+
7
+ ## Install your Pulse app
8
+
9
+ Register the app in Pulse and set its OAuth redirect URI and webhook URL. Keep the OAuth client secret and webhook signing secret in your app's secret store. Use the developer workspace ID for the registration and grant.
10
+
11
+ ```python
12
+ import os
13
+
14
+ import httpx
15
+ from pulse_agent_sdk import AgentAppAuth, MemoryAuthStore, OAuthConfig
16
+
17
+ config = OAuthConfig(
18
+ client_id=os.environ["PULSE_CLIENT_ID"],
19
+ client_secret=os.environ["PULSE_CLIENT_SECRET"],
20
+ redirect_uri=os.environ["PULSE_REDIRECT_URI"],
21
+ workspace_id=os.environ["PULSE_WORKSPACE_ID"],
22
+ )
23
+ ```
24
+
25
+ Create one `httpx.AsyncClient(timeout=10.0)` and one `AgentAppAuth(config, http, store)` in your app's lifespan. Use `MemoryAuthStore()` for local development and a shared [production store](production.md) for deployment.
26
+
27
+ - In an administrator-authorized route, redirect the browser to `await auth.start_install()`. It generates single-use state and an S256 PKCE challenge. If you configure `install_secret`, pass the supplied secret directly from your app's request handling.
28
+ - In the registered callback, call `await auth.complete_install(state=state, code=code, error=error)` with the callback query parameters. It consumes the state and stores the app installation. Render your own success or failure page.
29
+ - On shutdown, finish ingress and worker tasks, then call `await auth.drain()` before closing HTTP. A cancelled caller can leave a credential exchange finishing in the background.
30
+
31
+ ## Receive work and answer
32
+
33
+ ```python
34
+ from pulse_agent_sdk import PulseAgentClient, WebhookReceiver
35
+
36
+ receiver = WebhookReceiver(
37
+ os.environ["PULSE_WEBHOOK_SECRET"], inbox.enqueue, workspace_id=config.workspace_id,
38
+ )
39
+
40
+ # In the webhook route, use the original request bytes and headers.
41
+ await receiver.receive(raw_body, headers)
42
+ # Return 2xx after enqueue commits.
43
+
44
+ # In the worker, restore the verified event from the inbox.
45
+ if event.created is not None and event.session_id is not None:
46
+ client = await PulseAgentClient.for_event(auth, event)
47
+ await client.thought(event.session_id, "Reading the issue", idempotency_key=stored_activity_key)
48
+ ```
49
+
50
+ `inbox.enqueue` is an async function supplied by your app. The worker owns execution, authorization, and any activity keys that survive a restart. For a single-process agent, `WebhookHandler` can dispatch callbacks after returning its acknowledgment. See [production integration](production.md) for Stop and permission handling.
@@ -0,0 +1,15 @@
1
+ # Releasing the Python SDK
2
+
3
+ 1. Update the version in `pyproject.toml` and add a matching first entry in `CHANGELOG.md`. Run CI on the release commit and use an exact `v<version>` tag.
4
+ 2. Run the **Release SDK** workflow against that tag with **Publish** off. It checks the tag, runs the full Python matrix, builds both distributions, validates metadata, and installs and exercises each artifact.
5
+ 3. Before the first upload, configure GitHub's `pypi` environment to accept version tags and enable private vulnerability reporting. Set up a pending [PyPI Trusted Publisher](https://docs.pypi.org/trusted-publishers/creating-a-project-through-oidc/) for project `pulse-agent-sdk`, owner `try-pulse`, repository `pulse-agent-sdk-python`, workflow `release.yml`, environment `pypi`.
6
+ 4. Dispatch the workflow on the matching tag with **Publish** on. Only the final job has OIDC permission. It publishes that run's verified wheel and sdist with PyPI attestations. Confirm the published files and use the matching changelog entry for the GitHub release notes.
7
+
8
+ For local validation, use a fresh output directory.
9
+
10
+ ```bash
11
+ python -m pip install '.[release]'
12
+ python -m build --outdir dist/release-check
13
+ python -m twine check --strict dist/release-check/*
14
+ python scripts/check_release.py --tag v0.1.1 --dist dist/release-check
15
+ ```
@@ -0,0 +1,151 @@
1
+ """Run a small, deterministic Scout against mocked Pulse endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import hmac
8
+ import json
9
+ import sqlite3
10
+ from contextlib import closing
11
+ from pathlib import Path
12
+ from tempfile import TemporaryDirectory
13
+ from urllib.parse import parse_qs, urlsplit
14
+
15
+ import httpx
16
+
17
+ from pulse_agent_sdk import (
18
+ AgentAppAuth,
19
+ MemoryAuthStore,
20
+ OAuthConfig,
21
+ PulseAgentClient,
22
+ WebhookEvent,
23
+ WebhookReceiver,
24
+ )
25
+
26
+ NOW = 1_790_327_523
27
+ SECRET = "mock-webhook-secret"
28
+ WORKSPACE = "demo"
29
+
30
+
31
+ class Inbox:
32
+ def __init__(self, database: sqlite3.Connection) -> None:
33
+ self.db = database
34
+ self.db.execute(
35
+ "CREATE TABLE inbox (id INTEGER PRIMARY KEY, installation TEXT, occurrence TEXT, "
36
+ "payload TEXT, processed INTEGER DEFAULT 0, UNIQUE(installation, occurrence))"
37
+ )
38
+
39
+ async def enqueue(self, event: WebhookEvent) -> None:
40
+ key = event.dedupe_key
41
+ assert key is not None
42
+ with self.db:
43
+ self.db.execute(
44
+ "INSERT INTO inbox (installation, occurrence, payload) VALUES (?, ?, ?) "
45
+ "ON CONFLICT(installation, occurrence) DO NOTHING",
46
+ (*key, json.dumps(event.payload)),
47
+ )
48
+
49
+ async def drain(self, auth: AgentAppAuth) -> None:
50
+ rows = self.db.execute("SELECT id, payload FROM inbox WHERE processed = 0 ORDER BY id").fetchall()
51
+ for row_id, payload in rows:
52
+ await answer(auth, WebhookEvent.from_verified_payload(json.loads(payload)))
53
+ with self.db:
54
+ self.db.execute("UPDATE inbox SET processed = 1 WHERE id = ?", (row_id,))
55
+
56
+
57
+ async def answer(auth: AgentAppAuth, event: WebhookEvent) -> None:
58
+ if event.is_revoked and event.installation_id is not None:
59
+ await auth.forget_installation(event.installation_id)
60
+ return
61
+ session = event.session
62
+ if session is None:
63
+ return
64
+ client = await PulseAgentClient.for_event(auth, event)
65
+ session_id = session["id"]
66
+
67
+ def activity_key(step: str) -> str:
68
+ occurrence = json.dumps((event.dedupe_key, step), separators=(",", ":"))
69
+ return hashlib.sha256(occurrence.encode()).hexdigest()
70
+
71
+ if event.is_stop:
72
+ # This demo processes serially. A real worker must cancel and fence existing work first.
73
+ await client.respond(session_id, "Stopped.", idempotency_key=activity_key("stop"))
74
+ elif event.created is not None and (issue := session["issue"]) is not None:
75
+ await client.thought(session_id, "Reading the issue.", idempotency_key=activity_key("start"))
76
+ await client.set_plan(session_id, [{"content": "Summarize the issue", "status": "inProgress"}])
77
+ details = await client.get_issue(issue["id"])
78
+ message = f"Reviewed **{issue['identifier']}** ({details['title']})."
79
+ await client.set_plan(session_id, [{"content": "Summarize the issue", "status": "completed"}])
80
+ await client.respond(session_id, message, idempotency_key=activity_key("summary"))
81
+
82
+
83
+ def delivery(action: str, occurrence: str) -> tuple[bytes, dict[str, str]]:
84
+ data = {
85
+ "event_id": occurrence,
86
+ "agent_session": {
87
+ "id": "session",
88
+ "issue": {"id": "issue", "identifier": "DEMO-1"},
89
+ },
90
+ }
91
+ if action == "prompted":
92
+ data["agent_activity"] = {"signal": "stop"}
93
+ payload = {
94
+ "type": "AgentSessionEvent", "action": action, "workspace_id": WORKSPACE,
95
+ "installation_id": "installation", "app_user_id": "scout",
96
+ "webhook_timestamp": NOW * 1000, "data": data,
97
+ }
98
+ raw = json.dumps(payload).encode()
99
+ return raw, {"Pulse-Signature": hmac.digest(SECRET.encode(), raw, "sha256").hex()}
100
+
101
+
102
+ async def main() -> None:
103
+ messages: list[str] = []
104
+ activities: dict[str, dict[str, str]] = {}
105
+
106
+ def pulse(request: httpx.Request) -> httpx.Response:
107
+ path = request.url.path.removeprefix("/api/v1")
108
+ if path == "/oauth/token":
109
+ form = parse_qs(request.content.decode())
110
+ assert form["grant_type"] == ["authorization_code"] and len(form["code_verifier"][0]) == 43
111
+ return httpx.Response(200, json={
112
+ "token_type": "Bearer", "actor": "app", "access_token": "mock-access",
113
+ "refresh_token": "mock-refresh", "expires_in": 3600, "workspace_id": WORKSPACE,
114
+ "app_user_id": "scout", "installation_id": "installation",
115
+ })
116
+ assert request.headers["Authorization"] == "Bearer mock-access"
117
+ assert request.headers["X-Workspace-ID"] == WORKSPACE
118
+ if path == "/issues/issue":
119
+ return httpx.Response(200, json={"id": "issue", "title": "Check the webhook inbox"})
120
+ if path == "/agent-sessions/session" and request.method == "PATCH":
121
+ return httpx.Response(200, json={"id": "session", **json.loads(request.content)})
122
+ assert path == "/agent-sessions/session/activities"
123
+ key = request.headers["Idempotency-Key"]
124
+ if key not in activities:
125
+ content = json.loads(request.content)["content"]
126
+ messages.append(content["body"])
127
+ activities[key] = {"id": f"activity-{len(messages)}"}
128
+ return httpx.Response(201, json=activities[key])
129
+
130
+ async with httpx.AsyncClient(transport=httpx.MockTransport(pulse)) as http:
131
+ with TemporaryDirectory() as directory, closing(sqlite3.connect(Path(directory) / "inbox.db")) as db:
132
+ config = OAuthConfig("scout", "mock-client-secret", "https://scout.example/callback", WORKSPACE)
133
+ store = MemoryAuthStore(now=lambda: NOW)
134
+ auth = AgentAppAuth(config, http, store, now=lambda: NOW)
135
+ install_url = await auth.start_install()
136
+ state = parse_qs(urlsplit(install_url).query)["state"][0]
137
+ await auth.complete_install(state=state, code="mock-code")
138
+
139
+ inbox = Inbox(db)
140
+ receiver = WebhookReceiver(SECRET, inbox.enqueue, workspace_id=WORKSPACE, now_ms=lambda: NOW * 1000)
141
+ for action, occurrence in (("created", "created-1"), ("created", "created-1"), ("prompted", "stop-1")):
142
+ await receiver.receive(*delivery(action, occurrence))
143
+ assert db.execute("SELECT COUNT(*) FROM inbox").fetchone() == (2,)
144
+ await inbox.drain(auth)
145
+ await auth.drain()
146
+ assert messages == ["Reading the issue.", "Reviewed **DEMO-1** (Check the webhook inbox).", "Stopped."]
147
+ print("\n".join(messages))
148
+
149
+
150
+ if __name__ == "__main__":
151
+ asyncio.run(main())
@@ -0,0 +1,39 @@
1
+ {
2
+ "action": "created",
3
+ "type": "AgentSessionEvent",
4
+ "actor": {"id": "u1", "type": "user", "name": "Sara Ahmadi"},
5
+ "created_at": "2026-09-25T09:12:03.120Z",
6
+ "url": "https://app.trypulse.tech/pulse/issues/i1",
7
+ "workspace_id": "ws1",
8
+ "webhook_id": "wh1",
9
+ "webhook_timestamp": 1790327523120,
10
+ "installation_id": "inst1",
11
+ "app_user_id": "app-user-1",
12
+ "data": {
13
+ "event_id": "ase_s1_created",
14
+ "agent_session": {
15
+ "id": "sess_1",
16
+ "state": "pending",
17
+ "unresponsive_since": null,
18
+ "issue": {
19
+ "id": "i1",
20
+ "identifier": "PUL-1",
21
+ "title": "T",
22
+ "url": "https://app.trypulse.tech/pulse/issues/i1",
23
+ "team": {"id": "t1", "key": "PUL", "name": "Pulse"}
24
+ },
25
+ "comment": null,
26
+ "creator": {"id": "u1", "name": "Sara Ahmadi"},
27
+ "app_user_id": "app-user-1",
28
+ "plan": [],
29
+ "external_urls": [],
30
+ "created_at": "2026-09-25T09:12:03.120Z",
31
+ "updated_at": "2026-09-25T09:12:03.120Z",
32
+ "ended_at": null,
33
+ "end_reason": null
34
+ },
35
+ "previous_comments": [],
36
+ "guidance": [],
37
+ "prompt_context": "<issue identifier=\"PUL-1\" url=\"u\"><title>T</title></issue>"
38
+ }
39
+ }
@@ -0,0 +1 @@
1
+ ["inst1", "body:b7c9ed0f41094bdc2ff202ae46c3069f24ed0bdab1f8a3ccabadf3e3576b8ed3"]
@@ -0,0 +1,12 @@
1
+ {
2
+ "type": "Issue",
3
+ "action": "update",
4
+ "workspace_id": "ws1",
5
+ "webhook_id": "wh1",
6
+ "installation_id": "inst1",
7
+ "app_user_id": "app-user-1",
8
+ "created_at": "2026-09-25T09:12:03.120Z",
9
+ "webhook_timestamp": 1790327523120,
10
+ "data": {"id": "i1", "label_ids": ["ready"], "title": "محصول"},
11
+ "updated_from": {"label_ids": []}
12
+ }
@@ -0,0 +1,75 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pulse-agent-sdk"
7
+ version = "0.1.1"
8
+ description = "Python SDK for building Pulse Agent Apps"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = ["httpx>=0.26,<1"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Typing :: Typed",
24
+ ]
25
+ keywords = ["pulse", "agent", "sdk", "oauth", "webhooks"]
26
+
27
+ [project.optional-dependencies]
28
+ dev = [
29
+ "mypy>=1.19,<3",
30
+ "pytest>=8,<10",
31
+ "pytest-asyncio>=1,<2",
32
+ "PyYAML>=6,<7",
33
+ "ruff>=0.11,<1",
34
+ "types-PyYAML>=6,<7",
35
+ ]
36
+ release = [
37
+ "build>=1.2,<2",
38
+ "packaging>=24,<27",
39
+ "twine>=7,<8",
40
+ ]
41
+
42
+ [project.urls]
43
+ Documentation = "https://trypulse.tech/docs/developers/agents"
44
+ Repository = "https://github.com/try-pulse/pulse-agent-sdk-python"
45
+ Issues = "https://github.com/try-pulse/pulse-agent-sdk-python/issues"
46
+ Changelog = "https://github.com/try-pulse/pulse-agent-sdk-python/blob/main/CHANGELOG.md"
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ packages = ["src/pulse_agent_sdk"]
50
+
51
+ [tool.hatch.build.targets.sdist]
52
+ include = [
53
+ "/src", "/tests", "/fixtures", "/specs", "/scripts", "/docs", "/examples",
54
+ "/CHANGELOG.md", "/CONTRIBUTING.md", "/LICENSE", "/Makefile", "/README.md", "/SECURITY.md", "/pyproject.toml",
55
+ ]
56
+
57
+ [tool.pytest.ini_options]
58
+ asyncio_mode = "auto"
59
+ asyncio_default_fixture_loop_scope = "function"
60
+
61
+ [tool.ruff]
62
+ target-version = "py311"
63
+
64
+ [tool.ruff.lint]
65
+ select = ["E4", "E7", "E9", "F", "I"]
66
+
67
+ [tool.ruff.lint.isort]
68
+ known-first-party = ["pulse_agent_sdk"]
69
+
70
+ [tool.ruff.lint.per-file-ignores]
71
+ "src/pulse_agent_sdk/_generated_api.py" = ["E741"] # The upstream logo field is named l.
72
+
73
+ [tool.mypy]
74
+ strict = true
75
+ files = ["src", "examples", "scripts"]