pushary-langgraph 0.2.0__tar.gz → 0.4.0__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.
@@ -138,3 +138,6 @@ tsup.config.bundled_*.mjs
138
138
 
139
139
  # graphify knowledge-graph output (generated)
140
140
  graphify-out/
141
+
142
+ # eslint --cache, restored in CI from the build cache
143
+ .eslintcache
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.5
2
+ Name: pushary-langgraph
3
+ Version: 0.4.0
4
+ Summary: Human-in-the-loop for LangGraph and LangChain: a blocking ask_human, plus a durable interrupt()/Command resume that reaches your user on their phone.
5
+ Project-URL: Homepage, https://pushary.com
6
+ Project-URL: Repository, https://github.com/Pushary/pushary-langgraph
7
+ Project-URL: Documentation, https://pushary.com/docs/agents/adapters
8
+ Author-email: Pushary <business@pushary.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: ai-agents,approvals,human-in-the-loop,interrupt,langchain,langgraph
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: langgraph<2,>=1.0
25
+ Requires-Dist: pushary<3,>=2.1.0
26
+ Requires-Dist: pydantic<3,>=2
27
+ Provides-Extra: test
28
+ Requires-Dist: langgraph-checkpoint-sqlite<4,>=3; extra == 'test'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # pushary-langgraph
32
+
33
+ Native Pushary customer reviews for LangGraph: **confirm** for permission, **select**
34
+ for choices, **input** for missing details. Confirm supports lock-screen actions;
35
+ select/input open the app. The legacy web/PWA surface remains compatible.
36
+
37
+ ## Install and enroll
38
+
39
+ ```bash
40
+ pip install pushary-langgraph
41
+ ```
42
+
43
+ ```python
44
+ from pushary_langgraph import connect
45
+
46
+ invitation = connect(authenticated_customer.id)
47
+ ```
48
+
49
+ Give the invitation to that authenticated customer. They install the native app,
50
+ reopen the link, and allow notifications. They need no Pushary account/key/paid plan;
51
+ the developer needs Partner access. Bind `external_id` in trusted application code,
52
+ not in model-generated tool arguments.
53
+
54
+ ## Review a graph action
55
+
56
+ ```python
57
+ from pushary_langgraph import pushary_interrupt
58
+
59
+
60
+ def review_order(state):
61
+ answer = pushary_interrupt(
62
+ f"Submit order {state['order_id']}, revision {state['revision']}?",
63
+ external_id=state["customer_id"],
64
+ idempotency_key=state["review_operation_id"],
65
+ type="confirm",
66
+ node="submit-order",
67
+ parameters={"revision": state["revision"]},
68
+ tool_target=state["order_id"],
69
+ callback_url="https://your-app.example/pushary/callback",
70
+ )
71
+ return {"approved": answer == "yes"}
72
+ ```
73
+
74
+ Your graph must route to the protected write only when this confirm branch approved.
75
+ `ask_human` is a blocking helper, not a rule forcing an agent to call it. A choice or
76
+ text answer is data, not action authorization; use `type="select", options=["A", "B"]`
77
+ or `type="input"` for the tool that needs those values. Do not use the shared SDK's
78
+ `approved` convenience flag as permission for a select/input action.
79
+
80
+ The adapter accepts the existing subject/presentation parameters: `tool_target`,
81
+ `actor`, `environment`, `parameters`, `presentation`, `placeholder`,
82
+ `expires_in_seconds` and `require_reachable`. A callback parks a native interrupt;
83
+ without it, the function blocks for the configured timeout and returns `None` unless
84
+ a valid answered result exists. Local timeout does not cancel the remote decision.
85
+
86
+ ## Checkpoint and callback contract
87
+
88
+ Compile your graph with a persistent checkpointer and pass a stable, customer-scoped
89
+ `configurable.thread_id`. The whole node re-runs on resume; keep earlier work
90
+ idempotent. Same operation/recipient/request contents produce the same decision key;
91
+ changed contents produce a new key. Use an immutable reviewed business revision and
92
+ check that revision again before writing. Fingerprinting is not ownership validation.
93
+
94
+ The interrupt value includes `decisionId`, `correlationId`, `operationKey`, question,
95
+ type/options and recipient. Its enclosing LangGraph interrupt has a separate native
96
+ `id`. Your application must persist both IDs with its trusted thread/tenant mapping.
97
+
98
+ Verify callbacks with `resolve_pushary_callback(raw_body, signature, webhook_secret)`.
99
+ Persist verified callbacks before acknowledgement. Keep early answers queued until the
100
+ graph checkpoint and mapping exist. Your existing worker should serialize per thread,
101
+ reload the current checkpoint and match its exact pending interrupt. Completed
102
+ interrupts must not be resumed again on callback retries. After those checks:
103
+
104
+ ```python
105
+ from langgraph.types import Command
106
+
107
+ graph.invoke(
108
+ Command(resume={pending_interrupt.id: {
109
+ "correlationId": verified_callback["correlationId"],
110
+ "answer": verified_callback["answer"],
111
+ }}),
112
+ {"configurable": {"thread_id": trusted_thread_id}},
113
+ )
114
+ ```
115
+
116
+ This is the final worker action, not an HTTP handler. The adapter validates the
117
+ correlation envelope and question-specific answer. It rejects strings/booleans passed
118
+ as an entire resume payload, wrong correlations, arbitrary answer objects, invalid
119
+ options and non-yes/no confirm values. A trusted expiration reconciler can send
120
+ `{"correlationId": decision_id, "status": "expired", "answer": None}` (or cancelled).
121
+ It returns `None`, never approval.
122
+
123
+ Handle missed callbacks by querying durable decision status; account for a crash
124
+ between graph resume and callback acknowledgement. Callback replay and checkpoint
125
+ persistence do not make ERP writes exactly once. Use operation keys and reconcile
126
+ uncertain external writes. No callback inbox or new orchestration runtime is installed
127
+ by this package.
128
+
129
+ ## Upgrade and validation
130
+
131
+ Version 0.4 needs `pushary>=2.1`. Durable resumes now require the correlated object.
132
+ Finish already suspended 0.3 runs on their original adapter version; changing the
133
+ request fingerprint under a suspended checkpoint can invalidate its pending approval.
134
+
135
+ ```bash
136
+ pip install -e '.[test]'
137
+ python -m unittest discover -s tests -v
138
+ ```
139
+
140
+ [The restart test](tests/test_restart.py) uses the actual LangGraph graph and official
141
+ SQLite checkpointer, closes/reopens SQLite and rebuilds the graph for confirm yes/no,
142
+ select and input. HTTP is simulated; it does not deliver a phone notification or run
143
+ an ERP action. Tested with Python 3.12, LangGraph 1.2.11, SQLite checkpointer 3.1.1 and
144
+ Pydantic 2.13.5. These results do not certify every supported dependency version or
145
+ physical-device delivery.
146
+
147
+ [Official LangGraph interrupts](https://docs.langchain.com/oss/python/langgraph/interrupts)
148
+ describe persistence, replay and resuming by interrupt ID.
149
+
150
+ ## License
151
+
152
+ MIT
@@ -0,0 +1,122 @@
1
+ # pushary-langgraph
2
+
3
+ Native Pushary customer reviews for LangGraph: **confirm** for permission, **select**
4
+ for choices, **input** for missing details. Confirm supports lock-screen actions;
5
+ select/input open the app. The legacy web/PWA surface remains compatible.
6
+
7
+ ## Install and enroll
8
+
9
+ ```bash
10
+ pip install pushary-langgraph
11
+ ```
12
+
13
+ ```python
14
+ from pushary_langgraph import connect
15
+
16
+ invitation = connect(authenticated_customer.id)
17
+ ```
18
+
19
+ Give the invitation to that authenticated customer. They install the native app,
20
+ reopen the link, and allow notifications. They need no Pushary account/key/paid plan;
21
+ the developer needs Partner access. Bind `external_id` in trusted application code,
22
+ not in model-generated tool arguments.
23
+
24
+ ## Review a graph action
25
+
26
+ ```python
27
+ from pushary_langgraph import pushary_interrupt
28
+
29
+
30
+ def review_order(state):
31
+ answer = pushary_interrupt(
32
+ f"Submit order {state['order_id']}, revision {state['revision']}?",
33
+ external_id=state["customer_id"],
34
+ idempotency_key=state["review_operation_id"],
35
+ type="confirm",
36
+ node="submit-order",
37
+ parameters={"revision": state["revision"]},
38
+ tool_target=state["order_id"],
39
+ callback_url="https://your-app.example/pushary/callback",
40
+ )
41
+ return {"approved": answer == "yes"}
42
+ ```
43
+
44
+ Your graph must route to the protected write only when this confirm branch approved.
45
+ `ask_human` is a blocking helper, not a rule forcing an agent to call it. A choice or
46
+ text answer is data, not action authorization; use `type="select", options=["A", "B"]`
47
+ or `type="input"` for the tool that needs those values. Do not use the shared SDK's
48
+ `approved` convenience flag as permission for a select/input action.
49
+
50
+ The adapter accepts the existing subject/presentation parameters: `tool_target`,
51
+ `actor`, `environment`, `parameters`, `presentation`, `placeholder`,
52
+ `expires_in_seconds` and `require_reachable`. A callback parks a native interrupt;
53
+ without it, the function blocks for the configured timeout and returns `None` unless
54
+ a valid answered result exists. Local timeout does not cancel the remote decision.
55
+
56
+ ## Checkpoint and callback contract
57
+
58
+ Compile your graph with a persistent checkpointer and pass a stable, customer-scoped
59
+ `configurable.thread_id`. The whole node re-runs on resume; keep earlier work
60
+ idempotent. Same operation/recipient/request contents produce the same decision key;
61
+ changed contents produce a new key. Use an immutable reviewed business revision and
62
+ check that revision again before writing. Fingerprinting is not ownership validation.
63
+
64
+ The interrupt value includes `decisionId`, `correlationId`, `operationKey`, question,
65
+ type/options and recipient. Its enclosing LangGraph interrupt has a separate native
66
+ `id`. Your application must persist both IDs with its trusted thread/tenant mapping.
67
+
68
+ Verify callbacks with `resolve_pushary_callback(raw_body, signature, webhook_secret)`.
69
+ Persist verified callbacks before acknowledgement. Keep early answers queued until the
70
+ graph checkpoint and mapping exist. Your existing worker should serialize per thread,
71
+ reload the current checkpoint and match its exact pending interrupt. Completed
72
+ interrupts must not be resumed again on callback retries. After those checks:
73
+
74
+ ```python
75
+ from langgraph.types import Command
76
+
77
+ graph.invoke(
78
+ Command(resume={pending_interrupt.id: {
79
+ "correlationId": verified_callback["correlationId"],
80
+ "answer": verified_callback["answer"],
81
+ }}),
82
+ {"configurable": {"thread_id": trusted_thread_id}},
83
+ )
84
+ ```
85
+
86
+ This is the final worker action, not an HTTP handler. The adapter validates the
87
+ correlation envelope and question-specific answer. It rejects strings/booleans passed
88
+ as an entire resume payload, wrong correlations, arbitrary answer objects, invalid
89
+ options and non-yes/no confirm values. A trusted expiration reconciler can send
90
+ `{"correlationId": decision_id, "status": "expired", "answer": None}` (or cancelled).
91
+ It returns `None`, never approval.
92
+
93
+ Handle missed callbacks by querying durable decision status; account for a crash
94
+ between graph resume and callback acknowledgement. Callback replay and checkpoint
95
+ persistence do not make ERP writes exactly once. Use operation keys and reconcile
96
+ uncertain external writes. No callback inbox or new orchestration runtime is installed
97
+ by this package.
98
+
99
+ ## Upgrade and validation
100
+
101
+ Version 0.4 needs `pushary>=2.1`. Durable resumes now require the correlated object.
102
+ Finish already suspended 0.3 runs on their original adapter version; changing the
103
+ request fingerprint under a suspended checkpoint can invalidate its pending approval.
104
+
105
+ ```bash
106
+ pip install -e '.[test]'
107
+ python -m unittest discover -s tests -v
108
+ ```
109
+
110
+ [The restart test](tests/test_restart.py) uses the actual LangGraph graph and official
111
+ SQLite checkpointer, closes/reopens SQLite and rebuilds the graph for confirm yes/no,
112
+ select and input. HTTP is simulated; it does not deliver a phone notification or run
113
+ an ERP action. Tested with Python 3.12, LangGraph 1.2.11, SQLite checkpointer 3.1.1 and
114
+ Pydantic 2.13.5. These results do not certify every supported dependency version or
115
+ physical-device delivery.
116
+
117
+ [Official LangGraph interrupts](https://docs.langchain.com/oss/python/langgraph/interrupts)
118
+ describe persistence, replay and resuming by interrupt ID.
119
+
120
+ ## License
121
+
122
+ MIT
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pushary-langgraph"
7
- version = "0.2.0"
7
+ version = "0.4.0"
8
8
  description = "Human-in-the-loop for LangGraph and LangChain: a blocking ask_human, plus a durable interrupt()/Command resume that reaches your user on their phone."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -32,8 +32,9 @@ classifiers = [
32
32
  "Typing :: Typed",
33
33
  ]
34
34
  dependencies = [
35
- "pushary>=1.4.0",
35
+ "pushary>=2.1.0,<3",
36
36
  "langgraph>=1.0,<2",
37
+ "pydantic>=2,<3",
37
38
  ]
38
39
 
39
40
  [project.urls]
@@ -51,3 +52,6 @@ include = [
51
52
  "LICENSE",
52
53
  "tests",
53
54
  ]
55
+
56
+ [project.optional-dependencies]
57
+ test = ["langgraph-checkpoint-sqlite>=3,<4"]
@@ -17,7 +17,7 @@ durable path, so the blocking helpers work (and test) without it installed.
17
17
 
18
18
  from __future__ import annotations
19
19
 
20
- from typing import Any, Dict, List, Optional
20
+ from typing import Any, Dict, List, Literal, Optional
21
21
 
22
22
  from pushary import SIGNATURE_HEADER, deterministic_key
23
23
  from pushary.adapters import (
@@ -30,9 +30,12 @@ from pushary.adapters import (
30
30
  resolve_pushary_callback,
31
31
  )
32
32
 
33
- __version__ = "0.2.0"
33
+ from .review import CreatedDecision, ReviewRequest, ReviewResume, parse_answer, parse_resume
34
+
35
+ __version__ = "0.4.0"
34
36
 
35
37
  __all__ = [
38
+ "ReviewResume",
36
39
  "connect",
37
40
  "ask_human",
38
41
  "pushary_interrupt",
@@ -66,7 +69,8 @@ def pushary_interrupt(
66
69
  *,
67
70
  external_id: str,
68
71
  node: str = "hitl",
69
- type: str = "confirm",
72
+ idempotency_key: Optional[str] = None,
73
+ type: Literal["confirm", "select", "input"] = "confirm",
70
74
  options: Optional[List[str]] = None,
71
75
  callback_url: Optional[str] = None,
72
76
  context: Optional[str] = None,
@@ -74,48 +78,42 @@ def pushary_interrupt(
74
78
  timeout_seconds: Optional[float] = None,
75
79
  api_key: Optional[str] = None,
76
80
  base_url: Optional[str] = None,
81
+ tool_target: Optional[str] = None,
82
+ actor: Optional[str] = None,
83
+ environment: Optional[str] = None,
84
+ parameters: Optional[Dict[str, Any]] = None,
85
+ presentation: Optional[Dict[str, Any]] = None,
86
+ placeholder: Optional[str] = None,
87
+ expires_in_seconds: Optional[int] = None,
88
+ require_reachable: Optional[bool] = None,
77
89
  ) -> Optional[str]:
78
- """Ask a human from inside a LangGraph node.
79
-
80
- - ``callback_url`` omitted (Pattern A): blocks, polls durably, returns the answer
81
- (or None if fail-closed). Zero extra infra, holds the run open for the wait.
82
- - ``callback_url`` set (Pattern B): opens the decision, then calls LangGraph's
83
- ``interrupt()`` to park the graph in your checkpointer. Resume with
84
- ``Command(resume=answer)`` from the signed webhook. Holds no idle compute.
85
-
86
- The whole node re-runs on resume, so keep code before this call idempotent. The
87
- decision's idempotency key is derived from external_id + node + question, so the
88
- re-run lands on the same decision.
89
- """
90
-
91
- if not callback_url:
92
- decision: Dict[str, Any] = ask_human(
93
- question,
94
- external_id=external_id,
95
- type=type,
96
- options=options,
97
- node=node,
98
- context=context,
99
- agent_name=agent_name,
100
- timeout_seconds=timeout_seconds,
101
- api_key=api_key,
102
- base_url=base_url,
103
- )
104
- return decision.get("value") if decision.get("answered") else None
105
-
106
- _kernel.create_durable_decision(
107
- question,
108
- external_id=external_id,
109
- callback_url=callback_url,
110
- type=type,
111
- options=options,
112
- node=node,
113
- context=context,
114
- agent_name=agent_name,
115
- api_key=api_key,
116
- base_url=base_url,
90
+ review = ReviewRequest(
91
+ question=question, external_id=external_id, node=node, idempotency_key=idempotency_key,
92
+ type=type, options=options, callback_url=callback_url, context=context, agent_name=agent_name,
93
+ tool_target=tool_target, actor=actor, environment=environment, parameters=parameters,
94
+ presentation=presentation, placeholder=placeholder, expires_in_seconds=expires_in_seconds,
95
+ require_reachable=require_reachable,
117
96
  )
118
- # Lazy import: only the durable path needs LangGraph installed.
97
+ values = review.bound_input()
98
+ values.pop("question")
99
+ if not callback_url:
100
+ decision = ask_human(question, **values, timeout_seconds=timeout_seconds, api_key=api_key, base_url=base_url)
101
+ return parse_answer(decision.get("value"), review) if decision.get("status") == "answered" and decision.get("answered") else None
102
+
103
+ created = CreatedDecision.model_validate(_kernel.create_durable_decision(question, **values, api_key=api_key, base_url=base_url))
104
+ if created.status in ("expired", "cancelled"):
105
+ return None
119
106
  from langgraph.types import interrupt
120
107
 
121
- return interrupt({"pushary": "decision", "question": question, "external_id": external_id})
108
+ correlation_id = created.correlation_id
109
+ resumed = interrupt({
110
+ "pushary": "decision",
111
+ "decisionId": created.decision_id,
112
+ "correlationId": correlation_id,
113
+ "operationKey": values["idempotency_key"],
114
+ "question": question,
115
+ "type": review.type,
116
+ "options": review.options,
117
+ "external_id": external_id,
118
+ })
119
+ return parse_resume(resumed, correlation_id, review)
@@ -0,0 +1,84 @@
1
+ from typing import Any, Dict, List, Literal, Optional
2
+
3
+ from pydantic import BaseModel, ConfigDict, Field, StrictStr, TypeAdapter, model_validator
4
+ from pushary.adapters import decision_fingerprint
5
+
6
+
7
+ class ReviewRequest(BaseModel):
8
+ model_config = ConfigDict(strict=True)
9
+ question: str = Field(min_length=1)
10
+ external_id: str = Field(min_length=1)
11
+ node: str = "hitl"
12
+ idempotency_key: Optional[str] = Field(default=None, min_length=1)
13
+ type: Literal["confirm", "select", "input"] = "confirm"
14
+ options: Optional[List[str]] = None
15
+ callback_url: Optional[str] = None
16
+ context: Optional[str] = None
17
+ agent_name: Optional[str] = None
18
+ tool_target: Optional[str] = None
19
+ actor: Optional[str] = None
20
+ environment: Optional[str] = None
21
+ parameters: Optional[Dict[str, Any]] = None
22
+ presentation: Optional[Dict[str, Any]] = None
23
+ placeholder: Optional[str] = None
24
+ expires_in_seconds: Optional[int] = Field(default=None, ge=1)
25
+ require_reachable: Optional[bool] = None
26
+
27
+ @model_validator(mode="after")
28
+ def validate_review(self) -> "ReviewRequest":
29
+ if not self.external_id.strip() or not self.question.strip():
30
+ raise ValueError("Pushary: question and recipient must not be blank.")
31
+ if len(self.external_id.encode("utf-16-le", errors="surrogatepass")) // 2 > 256:
32
+ raise ValueError("Pushary: recipient must not exceed 256 UTF-16 code units.")
33
+ if self.idempotency_key is not None and not self.idempotency_key.strip():
34
+ raise ValueError("Pushary: operation idempotency_key must not be blank.")
35
+ if self.type == "select" and (not self.options or any(not option for option in self.options)):
36
+ raise ValueError("Pushary: select requires options.")
37
+ if self.callback_url and (not self.idempotency_key or not self.idempotency_key.strip()):
38
+ raise ValueError("Pushary: durable review requires an operation idempotency_key.")
39
+ return self
40
+
41
+ def bound_input(self) -> Dict[str, Any]:
42
+ values = self.model_dump(exclude_none=True)
43
+ if self.idempotency_key:
44
+ values["idempotency_key"] = decision_fingerprint(values)
45
+ return values
46
+
47
+
48
+ class CreatedDecision(BaseModel):
49
+ model_config = ConfigDict(strict=True)
50
+ decision_id: str = Field(alias="decisionId", min_length=1)
51
+ correlation_id: str = Field(alias="correlationId", min_length=1)
52
+ status: Literal["pending", "answered", "expired", "cancelled"]
53
+
54
+
55
+ class ReviewResume(BaseModel):
56
+ model_config = ConfigDict(strict=True)
57
+ correlation_id: str = Field(alias="correlationId", min_length=1)
58
+ answer: Optional[str] = Field(max_length=5000)
59
+ status: Literal["answered", "expired", "cancelled"] = "answered"
60
+
61
+
62
+ _answer = TypeAdapter(StrictStr)
63
+
64
+
65
+ def parse_answer(value: Any, review: ReviewRequest) -> str:
66
+ answer = _answer.validate_python(value)
67
+ if not answer or len(answer) > 5000:
68
+ raise ValueError("Pushary: answer must contain 1 to 5000 characters.")
69
+ if review.type == "confirm" and answer not in ("yes", "no"):
70
+ raise ValueError("Pushary: confirm answer must be yes or no.")
71
+ if review.type == "select" and answer not in (review.options or []):
72
+ raise ValueError("Pushary: answer must match an offered option.")
73
+ return answer
74
+
75
+
76
+ def parse_resume(value: Any, correlation_id: str, review: ReviewRequest) -> Optional[str]:
77
+ resumed = ReviewResume.model_validate(value)
78
+ if resumed.correlation_id != correlation_id:
79
+ raise ValueError("Pushary: resumed answer belongs to another decision.")
80
+ if resumed.status != "answered":
81
+ if resumed.answer is not None:
82
+ raise ValueError("Pushary: an expired or cancelled review cannot carry an answer.")
83
+ return None
84
+ return parse_answer(resumed.answer, review)
@@ -8,6 +8,7 @@ import hmac
8
8
  import json
9
9
  import os
10
10
  import unittest
11
+ from unittest.mock import patch
11
12
 
12
13
  import pushary_langgraph as plg
13
14
  from pushary import adapters
@@ -83,19 +84,19 @@ class AskHumanTests(unittest.TestCase):
83
84
  def test_ask_human_forwards_deterministic_idempotency_key(self):
84
85
  decisions = FakeDecisions(ask_result={"status": "answered", "answered": True, "value": "yes", "approved": True})
85
86
  with WithFakeClient(FakeClient(decisions=decisions)):
86
- out = plg.ask_human("Approve?", external_id="user_1", node="approval")
87
+ out = plg.ask_human("Approve?", external_id="user_1", node="approval", idempotency_key="operation-1")
87
88
  self.assertTrue(out["approved"])
88
89
  call = decisions.ask_calls[0]
89
90
  self.assertEqual(call["external_id"], "user_1")
90
91
  self.assertTrue(call["idempotency_key"])
91
92
  # same input -> same key (re-run safe)
92
- expected = plg.deterministic_key(["user_1", "approval", "Approve?"])
93
+ expected = "operation-1"
93
94
  self.assertEqual(call["idempotency_key"], expected)
94
95
 
95
96
 
96
97
  class PusharyInterruptTests(unittest.TestCase):
97
98
  def test_blocking_pattern_returns_value_when_answered(self):
98
- decisions = FakeDecisions(ask_result={"answered": True, "value": "yes"})
99
+ decisions = FakeDecisions(ask_result={"status": "answered", "answered": True, "value": "yes"})
99
100
  with WithFakeClient(FakeClient(decisions=decisions)):
100
101
  answer = plg.pushary_interrupt("Approve?", external_id="user_1", node="n")
101
102
  self.assertEqual(answer, "yes")
@@ -107,15 +108,12 @@ class PusharyInterruptTests(unittest.TestCase):
107
108
  self.assertIsNone(answer)
108
109
 
109
110
  def test_durable_pattern_opens_decision_with_callback(self):
110
- # callback_url set -> Pattern B calls create() then imports langgraph.interrupt.
111
- # langgraph is not installed in this test env, so we assert the create call happened
112
- # and that the lazy import is what raises (not our code path).
113
111
  decisions = FakeDecisions(create_result={"decisionId": "d1", "status": "pending"})
114
- with WithFakeClient(FakeClient(decisions=decisions)):
115
- with self.assertRaises(ImportError):
116
- plg.pushary_interrupt(
117
- "Approve?", external_id="user_1", node="n", callback_url="https://x/cb"
118
- )
112
+ with WithFakeClient(FakeClient(decisions=decisions)), patch("langgraph.types.interrupt", return_value={"correlationId": "d1", "answer": "yes"}) as interrupted:
113
+ self.assertEqual(plg.pushary_interrupt(
114
+ "Approve?", external_id="user_1", node="n", callback_url="https://x/cb", idempotency_key="operation-1"
115
+ ), "yes")
116
+ self.assertEqual(interrupted.call_args.args[0]["correlationId"], "d1")
119
117
  create = decisions.create_calls[0]
120
118
  self.assertEqual(create["callback_url"], "https://x/cb")
121
119
  self.assertEqual(create["wait"], False)
@@ -0,0 +1,90 @@
1
+ import os
2
+ import tempfile
3
+ import unittest
4
+ from typing import Optional, TypedDict
5
+
6
+ from langgraph.checkpoint.sqlite import SqliteSaver
7
+ from langgraph.graph import END, START, StateGraph
8
+ from langgraph.types import Command
9
+ from pushary_langgraph import pushary_interrupt
10
+ from pushary_langgraph.review import ReviewRequest, parse_resume
11
+ from test_langgraph import FakeClient, FakeDecisions, WithFakeClient
12
+
13
+
14
+ class State(TypedDict):
15
+ answer: Optional[str]
16
+
17
+
18
+ class RestartTests(unittest.TestCase):
19
+ def test_sqlite_reopen_resumes_each_native_answer_without_a_new_decision(self):
20
+ with tempfile.TemporaryDirectory() as directory:
21
+ for kind, answer in [("confirm", "yes"), ("confirm", "no"), ("select", "B"), ("input", "Dock 2")]:
22
+ with self.subTest(kind=kind, answer=answer):
23
+ decisions = FakeDecisions(create_result={"decisionId": "decision-1", "status": "pending"})
24
+ def build(saver):
25
+ def review(_state):
26
+ return {"answer": pushary_interrupt(
27
+ "Review order", external_id="customer", type=kind,
28
+ options=["A", "B"] if kind == "select" else None,
29
+ idempotency_key="order-1", parameters={"revision": 1},
30
+ callback_url="https://test.invalid/callback",
31
+ )}
32
+ return StateGraph(State).add_node("review", review).add_edge(START, "review").add_edge("review", END).compile(checkpointer=saver)
33
+ path = os.path.join(directory, f"{kind}-{answer}.sqlite")
34
+ thread = {"configurable": {"thread_id": "customer-thread"}}
35
+ with WithFakeClient(FakeClient(decisions=decisions)):
36
+ with SqliteSaver.from_conn_string(path) as saver:
37
+ first = build(saver).invoke({}, thread)
38
+ pending = first["__interrupt__"][0]
39
+ self.assertEqual(pending.value["correlationId"], "decision-1")
40
+ self.assertEqual(pending.value["type"], kind)
41
+ with SqliteSaver.from_conn_string(path) as reopened:
42
+ graph = build(reopened)
43
+ result = graph.invoke(Command(resume={pending.id: {"correlationId": "decision-1", "answer": answer}}), thread)
44
+ self.assertEqual(result["answer"], answer)
45
+ self.assertEqual(graph.get_state(thread).next, ())
46
+ self.assertEqual(len({call["idempotency_key"] for call in decisions.create_calls}), 1)
47
+ self.assertEqual(decisions.create_calls[-1]["parameters"], {"revision": 1})
48
+
49
+ def test_terminal_decision_replay_returns_no_approval(self):
50
+ for status in ["expired", "cancelled"]:
51
+ with self.subTest(status=status):
52
+ decisions = FakeDecisions(create_result={"decisionId": "decision-1", "status": status})
53
+ with WithFakeClient(FakeClient(decisions=decisions)):
54
+ self.assertIsNone(pushary_interrupt(
55
+ "Approve?", external_id="customer", idempotency_key="order-1",
56
+ callback_url="https://test.invalid/callback",
57
+ ))
58
+
59
+ def test_preserves_opaque_identity_and_rejects_invalid_recipient_before_http(self):
60
+ decisions = FakeDecisions(create_result={"decisionId": "decision-1", "status": "expired"})
61
+ with WithFakeClient(FakeClient(decisions=decisions)):
62
+ for key in [" operation ", "operation"]:
63
+ pushary_interrupt("Approve?", external_id=" customer ", idempotency_key=key, callback_url="https://test.invalid/callback")
64
+ self.assertEqual([call["external_id"] for call in decisions.create_calls], [" customer ", " customer "])
65
+ self.assertNotEqual(decisions.create_calls[0]["idempotency_key"], decisions.create_calls[1]["idempotency_key"])
66
+ pushary_interrupt("Approve?", external_id="😀" * 128, idempotency_key="operation", callback_url="https://test.invalid/callback")
67
+ for recipient in [" ", "a" * 257, "😀" * 129]:
68
+ with self.assertRaises(ValueError):
69
+ pushary_interrupt("Approve?", external_id=recipient, idempotency_key="operation", callback_url="https://test.invalid/callback")
70
+ with self.assertRaises(ValueError):
71
+ pushary_interrupt("Approve?", external_id="customer", idempotency_key=" ")
72
+ self.assertEqual(len(decisions.create_calls), 3)
73
+ self.assertEqual(decisions.ask_calls, [])
74
+
75
+ def test_resume_validation_and_trusted_identity(self):
76
+ review = ReviewRequest(question="Approve?", external_id="customer", callback_url="https://test.invalid/cb", idempotency_key="order-1", parameters={"revision": 1})
77
+ original = review.bound_input()["idempotency_key"]
78
+ self.assertEqual(review.bound_input()["idempotency_key"], original)
79
+ for changed in [{"external_id": "other"}, {"parameters": {"revision": 2}}]:
80
+ self.assertNotEqual(ReviewRequest(**(review.model_dump() | changed)).bound_input()["idempotency_key"], original)
81
+ for value in ["yes", True, {}, {"correlationId": "wrong", "answer": "yes"}, {"correlationId": "d", "answer": {"approved": True}}, {"correlationId": "d", "answer": "anything"}]:
82
+ with self.assertRaises(ValueError):
83
+ parse_resume(value, "d", review)
84
+ self.assertIsNone(parse_resume({"correlationId": "d", "answer": None, "status": "expired"}, "d", review))
85
+ with self.assertRaises(ValueError):
86
+ parse_resume({"correlationId": "d", "answer": "yes", "status": "expired"}, "d", review)
87
+
88
+
89
+ if __name__ == "__main__":
90
+ unittest.main()
@@ -1,116 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: pushary-langgraph
3
- Version: 0.2.0
4
- Summary: Human-in-the-loop for LangGraph and LangChain: a blocking ask_human, plus a durable interrupt()/Command resume that reaches your user on their phone.
5
- Project-URL: Homepage, https://pushary.com
6
- Project-URL: Repository, https://github.com/Pushary/pushary-langgraph
7
- Project-URL: Documentation, https://pushary.com/docs/agents/adapters
8
- Author-email: Pushary <business@pushary.com>
9
- License: MIT
10
- License-File: LICENSE
11
- Keywords: ai-agents,approvals,human-in-the-loop,interrupt,langchain,langgraph
12
- Classifier: Development Status :: 4 - Beta
13
- Classifier: Intended Audience :: Developers
14
- Classifier: License :: OSI Approved :: MIT License
15
- Classifier: Operating System :: OS Independent
16
- Classifier: Programming Language :: Python :: 3
17
- Classifier: Programming Language :: Python :: 3.10
18
- Classifier: Programming Language :: Python :: 3.11
19
- Classifier: Programming Language :: Python :: 3.12
20
- Classifier: Programming Language :: Python :: 3.13
21
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
- Classifier: Typing :: Typed
23
- Requires-Python: >=3.10
24
- Requires-Dist: langgraph<2,>=1.0
25
- Requires-Dist: pushary>=1.4.0
26
- Description-Content-Type: text/markdown
27
-
28
- # pushary-langgraph
29
-
30
- Human-in-the-loop for [LangGraph](https://langchain-ai.github.io/langgraph/) and
31
- LangChain. Ask a real human to approve, and get the answer on their phone. Two seams:
32
-
33
- - **A blocking `ask_human`** you call from inside a node.
34
- - **A durable `pushary_interrupt`** that parks the graph with LangGraph's native
35
- `interrupt()` and resumes on a signed webhook, so a long wait holds no compute and
36
- survives a restart.
37
-
38
- Requires the Pushary [Partner plan](https://pushary.com/agent-notifications-integration?utm_source=github&utm_medium=oss-adapter&utm_campaign=pushary-langgraph&utm_content=python-readme).
39
-
40
- ## Install
41
-
42
- ```bash
43
- pip install pushary-langgraph
44
- ```
45
-
46
- Set `PUSHARY_API_KEY` (get it in your [dashboard](https://pushary.com/dashboard/settings)).
47
-
48
- ## Connect a phone once
49
-
50
- ```python
51
- from pushary_langgraph import connect
52
-
53
- link = connect("user_123") # show this to your end-user; one tap connects their phone
54
- ```
55
-
56
- ## Ask a human inside a node
57
-
58
- ```python
59
- from pushary_langgraph import ask_human
60
-
61
- def approval_node(state):
62
- d = ask_human("Approve this transfer?", external_id=state["user_id"], node="approval")
63
- return {"approved": d["approved"]}
64
- ```
65
-
66
- `ask_human` blocks, polls durably, and fails closed. The idempotency key is derived
67
- from `external_id + node + question`, so a node that re-runs on resume hits the same
68
- decision instead of paging the human twice.
69
-
70
- ## Durable interrupt
71
-
72
- ```python
73
- from pushary_langgraph import pushary_interrupt
74
-
75
- def approval_node(state):
76
- answer = pushary_interrupt(
77
- "Approve this transfer?",
78
- external_id=state["user_id"],
79
- node="approval",
80
- callback_url=os.environ["PUSHARY_CALLBACK_URL"], # omit to block instead of park
81
- )
82
- return {"approved": answer == "yes"}
83
- ```
84
-
85
- With a `callback_url`, the node opens the decision and calls LangGraph's `interrupt()`
86
- to park the graph (a checkpointer is required). Keep any code before the call
87
- idempotent, the whole node re-runs on resume.
88
-
89
- ### Resume from the webhook
90
-
91
- ```python
92
- from pushary_langgraph import resolve_pushary_callback, SIGNATURE_HEADER
93
- from langgraph.types import Command
94
-
95
- # POST /pushary/callback
96
- def callback(request):
97
- raw = request.body
98
- cb = resolve_pushary_callback(raw, request.headers.get(SIGNATURE_HEADER), os.environ["PUSHARY_WEBHOOK_SECRET"])
99
- if not cb:
100
- return ("bad signature", 401)
101
- thread_id = lookup_thread(cb["correlationId"]) # your own correlationId -> thread_id map
102
- graph.invoke(Command(resume=cb["answer"]), {"configurable": {"thread_id": thread_id}})
103
- return ("ok", 200)
104
- ```
105
-
106
- ## API
107
-
108
- - `connect(external_id, *, api_key=None, base_url=None)` — enroll an end-user's phone, returns the link.
109
- - `ask_human(question, *, external_id, type="confirm", options=None, node=..., ...)` — blocking, returns the decision dict.
110
- - `pushary_interrupt(question, *, external_id, node=..., callback_url=None, ...)` — blocking, or durable when `callback_url` is set.
111
- - `resolve_pushary_callback(raw_body, signature, secret)` — verify + parse a callback into `{correlationId, answer, approved, ...}`.
112
- - `describe_answer(type, result)`, `is_affirmative(answer)`, `deterministic_key(parts)`, `SIGNATURE_HEADER`.
113
-
114
- ## License
115
-
116
- MIT
@@ -1,89 +0,0 @@
1
- # pushary-langgraph
2
-
3
- Human-in-the-loop for [LangGraph](https://langchain-ai.github.io/langgraph/) and
4
- LangChain. Ask a real human to approve, and get the answer on their phone. Two seams:
5
-
6
- - **A blocking `ask_human`** you call from inside a node.
7
- - **A durable `pushary_interrupt`** that parks the graph with LangGraph's native
8
- `interrupt()` and resumes on a signed webhook, so a long wait holds no compute and
9
- survives a restart.
10
-
11
- Requires the Pushary [Partner plan](https://pushary.com/agent-notifications-integration?utm_source=github&utm_medium=oss-adapter&utm_campaign=pushary-langgraph&utm_content=python-readme).
12
-
13
- ## Install
14
-
15
- ```bash
16
- pip install pushary-langgraph
17
- ```
18
-
19
- Set `PUSHARY_API_KEY` (get it in your [dashboard](https://pushary.com/dashboard/settings)).
20
-
21
- ## Connect a phone once
22
-
23
- ```python
24
- from pushary_langgraph import connect
25
-
26
- link = connect("user_123") # show this to your end-user; one tap connects their phone
27
- ```
28
-
29
- ## Ask a human inside a node
30
-
31
- ```python
32
- from pushary_langgraph import ask_human
33
-
34
- def approval_node(state):
35
- d = ask_human("Approve this transfer?", external_id=state["user_id"], node="approval")
36
- return {"approved": d["approved"]}
37
- ```
38
-
39
- `ask_human` blocks, polls durably, and fails closed. The idempotency key is derived
40
- from `external_id + node + question`, so a node that re-runs on resume hits the same
41
- decision instead of paging the human twice.
42
-
43
- ## Durable interrupt
44
-
45
- ```python
46
- from pushary_langgraph import pushary_interrupt
47
-
48
- def approval_node(state):
49
- answer = pushary_interrupt(
50
- "Approve this transfer?",
51
- external_id=state["user_id"],
52
- node="approval",
53
- callback_url=os.environ["PUSHARY_CALLBACK_URL"], # omit to block instead of park
54
- )
55
- return {"approved": answer == "yes"}
56
- ```
57
-
58
- With a `callback_url`, the node opens the decision and calls LangGraph's `interrupt()`
59
- to park the graph (a checkpointer is required). Keep any code before the call
60
- idempotent, the whole node re-runs on resume.
61
-
62
- ### Resume from the webhook
63
-
64
- ```python
65
- from pushary_langgraph import resolve_pushary_callback, SIGNATURE_HEADER
66
- from langgraph.types import Command
67
-
68
- # POST /pushary/callback
69
- def callback(request):
70
- raw = request.body
71
- cb = resolve_pushary_callback(raw, request.headers.get(SIGNATURE_HEADER), os.environ["PUSHARY_WEBHOOK_SECRET"])
72
- if not cb:
73
- return ("bad signature", 401)
74
- thread_id = lookup_thread(cb["correlationId"]) # your own correlationId -> thread_id map
75
- graph.invoke(Command(resume=cb["answer"]), {"configurable": {"thread_id": thread_id}})
76
- return ("ok", 200)
77
- ```
78
-
79
- ## API
80
-
81
- - `connect(external_id, *, api_key=None, base_url=None)` — enroll an end-user's phone, returns the link.
82
- - `ask_human(question, *, external_id, type="confirm", options=None, node=..., ...)` — blocking, returns the decision dict.
83
- - `pushary_interrupt(question, *, external_id, node=..., callback_url=None, ...)` — blocking, or durable when `callback_url` is set.
84
- - `resolve_pushary_callback(raw_body, signature, secret)` — verify + parse a callback into `{correlationId, answer, approved, ...}`.
85
- - `describe_answer(type, result)`, `is_affirmative(answer)`, `deterministic_key(parts)`, `SIGNATURE_HEADER`.
86
-
87
- ## License
88
-
89
- MIT