replyonce 0.1.3__tar.gz → 0.2.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.
Files changed (32) hide show
  1. replyonce-0.2.0/AGENTS.md +12 -0
  2. {replyonce-0.1.3 → replyonce-0.2.0}/PKG-INFO +7 -6
  3. {replyonce-0.1.3 → replyonce-0.2.0}/README.md +2 -2
  4. {replyonce-0.1.3 → replyonce-0.2.0}/pyproject.toml +5 -4
  5. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/__init__.py +1 -1
  6. replyonce-0.2.0/src/replyonce/_key.py +167 -0
  7. {replyonce-0.1.3 → replyonce-0.2.0}/tests/test_key.py +19 -0
  8. {replyonce-0.1.3 → replyonce-0.2.0}/uv.lock +1 -1
  9. replyonce-0.1.3/src/replyonce/_key.py +0 -89
  10. {replyonce-0.1.3 → replyonce-0.2.0}/.gitignore +0 -0
  11. {replyonce-0.1.3 → replyonce-0.2.0}/LICENSE +0 -0
  12. {replyonce-0.1.3 → replyonce-0.2.0}/NOTICE +0 -0
  13. {replyonce-0.1.3 → replyonce-0.2.0}/scripts/interop.py +0 -0
  14. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/__main__.py +0 -0
  15. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/_core.py +0 -0
  16. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/_logic.py +0 -0
  17. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/adapters.py +0 -0
  18. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/cli.py +0 -0
  19. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/demo.py +0 -0
  20. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/py.typed +0 -0
  21. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/stores/__init__.py +0 -0
  22. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/stores/memory.py +0 -0
  23. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/stores/postgres.py +0 -0
  24. {replyonce-0.1.3 → replyonce-0.2.0}/src/replyonce/stores/redis.py +0 -0
  25. {replyonce-0.1.3 → replyonce-0.2.0}/tests/__init__.py +0 -0
  26. {replyonce-0.1.3 → replyonce-0.2.0}/tests/conftest.py +0 -0
  27. {replyonce-0.1.3 → replyonce-0.2.0}/tests/test_adapters.py +0 -0
  28. {replyonce-0.1.3 → replyonce-0.2.0}/tests/test_demo.py +0 -0
  29. {replyonce-0.1.3 → replyonce-0.2.0}/tests/test_migrate.py +0 -0
  30. {replyonce-0.1.3 → replyonce-0.2.0}/tests/test_once.py +0 -0
  31. {replyonce-0.1.3 → replyonce-0.2.0}/tests/test_race.py +0 -0
  32. {replyonce-0.1.3 → replyonce-0.2.0}/tests/test_runs.py +0 -0
@@ -0,0 +1,12 @@
1
+ # python
2
+
3
+ The root `AGENTS.md` applies.
4
+
5
+ Async port of the same state machine and state format, so a Node worker and
6
+ a Python worker can share one store. Dependencies live in the image via
7
+ `uv sync --frozen`. Run `docker compose run --build --rm python`. Do not
8
+ create `.venv` here.
9
+
10
+ ## Root contract
11
+
12
+ This file narrows the root `AGENTS.md`; the root file still applies. Repository-wide commands, safety rules and the definition of done live there.
@@ -1,10 +1,11 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: replyonce
3
- Version: 0.1.3
3
+ Version: 0.2.0
4
4
  Summary: Stop your agent from replying, refunding or ticketing twice. Idempotency keys, per-conversation write fencing and an effect ledger for tool-calling agents, webhooks and workers.
5
- Project-URL: Homepage, https://github.com/shmindmaster/replyonce
6
- Project-URL: Source, https://github.com/shmindmaster/replyonce/tree/main/python
7
- Project-URL: Issues, https://github.com/shmindmaster/replyonce/issues
5
+ Project-URL: Homepage, https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce#readme
6
+ Project-URL: Source, https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce/python
7
+ Project-URL: Issues, https://github.com/shmindmaster/fakeplane/issues
8
+ Project-URL: Author, https://saroshhussain.com
8
9
  Author: Sarosh Hussain
9
10
  License-Expression: Apache-2.0
10
11
  License-File: LICENSE
@@ -29,10 +30,10 @@ Description-Content-Type: text/markdown
29
30
 
30
31
  **Stop your agent from replying, refunding or ticketing twice.**
31
32
 
32
- The Python port of [replyonce](https://github.com/shmindmaster/replyonce). It uses the same
33
+ The Python port of [replyonce](https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce). It uses the same
33
34
  state machine and stores the same JSON state as the TypeScript package, so Python and
34
35
  Node workers can share one Postgres table or Redis prefix. The full guide, design notes,
35
- guarantees and limits are in the [main README](https://github.com/shmindmaster/replyonce#readme).
36
+ guarantees and limits are in the [main README](https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce#readme).
36
37
 
37
38
  ```sh
38
39
  pip install replyonce # memory store
@@ -2,10 +2,10 @@
2
2
 
3
3
  **Stop your agent from replying, refunding or ticketing twice.**
4
4
 
5
- The Python port of [replyonce](https://github.com/shmindmaster/replyonce). It uses the same
5
+ The Python port of [replyonce](https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce). It uses the same
6
6
  state machine and stores the same JSON state as the TypeScript package, so Python and
7
7
  Node workers can share one Postgres table or Redis prefix. The full guide, design notes,
8
- guarantees and limits are in the [main README](https://github.com/shmindmaster/replyonce#readme).
8
+ guarantees and limits are in the [main README](https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce#readme).
9
9
 
10
10
  ```sh
11
11
  pip install replyonce # memory store
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "replyonce"
7
- version = "0.1.3"
7
+ version = "0.2.0"
8
8
  description = "Stop your agent from replying, refunding or ticketing twice. Idempotency keys, per-conversation write fencing and an effect ledger for tool-calling agents, webhooks and workers."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -28,9 +28,10 @@ postgres = ["psycopg[binary]>=3.1", "psycopg-pool>=3.2"]
28
28
  redis = ["redis>=5.0"]
29
29
 
30
30
  [project.urls]
31
- Homepage = "https://github.com/shmindmaster/replyonce"
32
- Source = "https://github.com/shmindmaster/replyonce/tree/main/python"
33
- Issues = "https://github.com/shmindmaster/replyonce/issues"
31
+ Homepage = "https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce#readme"
32
+ Source = "https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce/python"
33
+ Issues = "https://github.com/shmindmaster/fakeplane/issues"
34
+ Author = "https://saroshhussain.com"
34
35
 
35
36
  [project.scripts]
36
37
  replyonce = "replyonce.cli:main"
@@ -16,7 +16,7 @@ from ._core import (
16
16
  from ._key import MISSING, canonical_json, effect_key, hash_payload, provider_idempotency_key
17
17
  from .stores.memory import MemoryStore
18
18
 
19
- __version__ = "0.1.3"
19
+ __version__ = "0.2.0"
20
20
 
21
21
  __all__ = [
22
22
  "CheckResult",
@@ -0,0 +1,167 @@
1
+ """Keys and canonical hashing, byte-compatible with the TypeScript package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import datetime as _dt
7
+ import hashlib
8
+ import json
9
+ import math
10
+ import re
11
+ from typing import Any
12
+
13
+ MISSING: Any = object()
14
+ """Sentinel for "no payload" (distinct from a ``None`` payload, which hashes as JSON null)."""
15
+
16
+
17
+ class _RawNumber:
18
+ """A number whose ECMAScript text form must be emitted without JSON quoting."""
19
+
20
+ __slots__ = ("text",)
21
+
22
+ def __init__(self, text: str) -> None:
23
+ self.text = text
24
+
25
+
26
+ def _sort_key(k: str) -> bytes:
27
+ # JavaScript sorts object keys by UTF-16 code units.
28
+ return k.encode("utf-16-be")
29
+
30
+
31
+ def _iso(value: _dt.datetime) -> str:
32
+ if value.tzinfo is None:
33
+ value = value.replace(tzinfo=_dt.timezone.utc)
34
+ value = value.astimezone(_dt.timezone.utc)
35
+ return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}Z"
36
+
37
+
38
+ def _js_number(value: float) -> str:
39
+ """Render a float the way ECMAScript Number::toString does.
40
+
41
+ Python's repr uses different thresholds and pads exponents (``1e-07``,
42
+ ``1e-06``), while JSON.stringify emits ``1e-7``, ``0.000001`` and switches
43
+ to exponent notation only at 1e21. Keys must be byte-identical across the
44
+ Python and TypeScript packages or the two runtimes cannot share a ledger.
45
+ """
46
+ if value == 0:
47
+ return "0" # includes -0.0, which JSON.stringify renders as 0
48
+ negative = value < 0
49
+ text = repr(abs(value)) # shortest round-trip digits
50
+ if "e" in text:
51
+ mantissa, exponent_text = text.split("e")
52
+ exponent = int(exponent_text)
53
+ else:
54
+ mantissa, exponent = text, 0
55
+ integer_part, _, fraction_part = mantissa.partition(".")
56
+ digits = integer_part + fraction_part
57
+ point = len(integer_part) + exponent
58
+ leading = len(digits) - len(digits.lstrip("0"))
59
+ digits = digits.lstrip("0")
60
+ point -= leading
61
+ digits = digits.rstrip("0") or "0"
62
+ k = len(digits)
63
+ n = point
64
+ if k <= n <= 21:
65
+ body = digits + "0" * (n - k)
66
+ elif 0 < n <= 21:
67
+ body = digits[:n] + "." + digits[n:]
68
+ elif -6 < n <= 0:
69
+ body = "0." + "0" * (-n) + digits
70
+ else:
71
+ exp = n - 1
72
+ sign = "+" if exp >= 0 else "-"
73
+ body = digits[0] + ("." + digits[1:] if k > 1 else "") + "e" + sign + str(abs(exp))
74
+ return "-" + body if negative else body
75
+
76
+
77
+ def _normalize(value: Any, seen: set[int]) -> Any:
78
+ if value is None or isinstance(value, (bool, str)):
79
+ return value
80
+ if isinstance(value, int):
81
+ # JSON.parse in JS produces a double for every number token; Python
82
+ # keeps an int. Above 2**53 the two runtimes must agree on the JS
83
+ # shortest round-trip form or one payload gets two ledger keys.
84
+ if abs(value) <= 2**53:
85
+ return value
86
+ return _RawNumber(_js_number(float(value)))
87
+ if isinstance(value, float):
88
+ if math.isnan(value):
89
+ return "NaN"
90
+ if math.isinf(value):
91
+ return "Infinity" if value > 0 else "-Infinity"
92
+ # Even integral doubles must use the JS shortest round-trip form:
93
+ # int(2**60) is 1152921504606846976 in Python but JSON.stringify
94
+ # emits 1152921504606847000. _js_number handles both forms.
95
+ return _RawNumber(_js_number(value))
96
+ if isinstance(value, _dt.datetime):
97
+ return _iso(value)
98
+ if isinstance(value, _dt.date):
99
+ return _iso(_dt.datetime(value.year, value.month, value.day, tzinfo=_dt.timezone.utc))
100
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
101
+ value = dataclasses.asdict(value)
102
+ elif hasattr(value, "model_dump") and callable(value.model_dump):
103
+ value = value.model_dump()
104
+ if id(value) in seen:
105
+ raise TypeError("replyonce: cannot hash a circular payload")
106
+ if isinstance(value, (list, tuple)):
107
+ seen.add(id(value))
108
+ out = [_normalize(v, seen) for v in value]
109
+ seen.discard(id(value))
110
+ return out
111
+ if isinstance(value, dict):
112
+ seen.add(id(value))
113
+ items = sorted(((str(k), v) for k, v in value.items()), key=lambda kv: _sort_key(kv[0]))
114
+ obj = {k: _normalize(v, seen) for k, v in items}
115
+ seen.discard(id(value))
116
+ return obj
117
+ raise TypeError(f"replyonce: cannot hash a payload of type {type(value).__name__}")
118
+
119
+
120
+ def _encode(value: Any) -> str:
121
+ if value is None:
122
+ return "null"
123
+ if value is True:
124
+ return "true"
125
+ if value is False:
126
+ return "false"
127
+ if isinstance(value, str):
128
+ return json.dumps(value, ensure_ascii=False)
129
+ if isinstance(value, int):
130
+ return int.__repr__(value) # IntEnum str() is "Class.MEMBER" on Python 3.10
131
+ if isinstance(value, _RawNumber):
132
+ return value.text
133
+ if isinstance(value, list):
134
+ return "[" + ",".join(_encode(item) for item in value) + "]"
135
+ if isinstance(value, dict):
136
+ return "{" + ",".join(
137
+ json.dumps(k, ensure_ascii=False) + ":" + _encode(v) for k, v in value.items()
138
+ ) + "}"
139
+ raise TypeError(f"replyonce: cannot hash a payload of type {type(value).__name__}")
140
+
141
+
142
+ def canonical_json(value: Any) -> str:
143
+ """Deterministic JSON: keys sorted, no whitespace. Matches the TypeScript ``canonicalJson``."""
144
+ return _encode(_normalize(value, set()))
145
+
146
+
147
+ def sha256_hex(text: str) -> str:
148
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
149
+
150
+
151
+ def hash_payload(payload: Any) -> str:
152
+ return sha256_hex(canonical_json(payload))[:32]
153
+
154
+
155
+ _SAFE_INTENT = re.compile(r"^[A-Za-z0-9_.:-]{1,100}$")
156
+
157
+
158
+ def effect_key(intent: str, payload: Any = MISSING) -> str:
159
+ """Ledger key for an intent plus the business identity of the payload."""
160
+ if not isinstance(intent, str) or not _SAFE_INTENT.match(intent):
161
+ raise TypeError(f"replyonce: intent must match {_SAFE_INTENT.pattern} (got {intent!r})")
162
+ return intent if payload is MISSING else f"{intent}:{hash_payload(payload)}"
163
+
164
+
165
+ def provider_idempotency_key(scope: str, key: str) -> str:
166
+ """Stable idempotency key to hand to a provider (Stripe-style ``Idempotency-Key``)."""
167
+ return "ro_" + sha256_hex(f"{scope}\u0000{key}")[:40]
@@ -21,6 +21,20 @@ VECTORS = [
21
21
  "x:578a211449377e723fbdd7fbf2dbb389",
22
22
  ),
23
23
  ("x", None, "null", "x:74234e98afe7498fb5daf1f36ac2d78a"),
24
+ # ECMAScript Number::toString thresholds and exponent formatting.
25
+ ("x", {"n": 1e-7}, '{"n":1e-7}', "x:747d6d23b64d1b2d579adb832b44de31"),
26
+ ("x", {"n": 1.5e-7}, '{"n":1.5e-7}', "x:ca0289a96d48abcb7088cf5581aadc70"),
27
+ ("x", {"n": 1e-6}, '{"n":0.000001}', "x:28343867a0be00aee19f81aa90cfd6c6"),
28
+ ("x", {"n": 1e-5}, '{"n":0.00001}', "x:694af9772b95df9403774a048bc7b0d7"),
29
+ ("x", {"n": 1e20}, '{"n":100000000000000000000}', "x:58d2d5b8dd4228ab5775ce84f996718f"),
30
+ ("x", {"n": 1e21}, '{"n":1e+21}', "x:f1ee2b60ee95a3170fdc07a577e5f351"),
31
+ ("x", {"n": -1e21}, '{"n":-1e+21}', "x:fd33685f4e2a11dbebb3fd9717ea6449"),
32
+ ("x", {"n": 0.0001}, '{"n":0.0001}', "x:eb596b9a807e0fbf971473088cea777f"),
33
+ ("x", {"n": 1.2345678901234567e-8}, '{"n":1.2345678901234567e-8}', "x:74e069581ed661b8a161c255ae0fac95"),
34
+ ("x", {"n": 1e-300}, '{"n":1e-300}', "x:8261d4fe2fd3eeb3dbea954ff257a6bc"),
35
+ ("x", {"n": 2.0**60}, '{"n":1152921504606847000}', "x:730c537ef7e20d832661f6619b9b9be4"),
36
+ ("x", {"n": 1000000000000000100.0}, '{"n":1000000000000000100}', "x:135ffdd59049a5e11240ffb79e442f05"),
37
+ ("x", {"n": 10**21}, '{"n":1e+21}', "x:f1ee2b60ee95a3170fdc07a577e5f351"),
24
38
  ]
25
39
 
26
40
 
@@ -36,6 +50,11 @@ def test_no_payload_and_provider_key_match_typescript():
36
50
  assert provider_idempotency_key("conv-1", "refund:abc") == "ro_1387614e87a828dd8b7faf70276f1dce87f7ee1d"
37
51
 
38
52
 
53
+ def test_boolean_values_remain_json_literals():
54
+ assert canonical_json(True) == "true"
55
+ assert canonical_json(False) == "false"
56
+
57
+
39
58
  def test_key_order_does_not_matter():
40
59
  assert hash_payload({"a": 1, "b": 2}) == hash_payload({"b": 2, "a": 1})
41
60
 
@@ -203,7 +203,7 @@ wheels = [
203
203
 
204
204
  [[package]]
205
205
  name = "replyonce"
206
- version = "0.1.3"
206
+ version = "0.2.0"
207
207
  source = { editable = "." }
208
208
 
209
209
  [package.optional-dependencies]
@@ -1,89 +0,0 @@
1
- """Keys and canonical hashing, byte-compatible with the TypeScript package."""
2
-
3
- from __future__ import annotations
4
-
5
- import dataclasses
6
- import datetime as _dt
7
- import hashlib
8
- import json
9
- import math
10
- import re
11
- from typing import Any
12
-
13
- MISSING: Any = object()
14
- """Sentinel for "no payload" (distinct from a ``None`` payload, which hashes as JSON null)."""
15
-
16
-
17
- def _sort_key(k: str) -> bytes:
18
- # JavaScript sorts object keys by UTF-16 code units.
19
- return k.encode("utf-16-be")
20
-
21
-
22
- def _iso(value: _dt.datetime) -> str:
23
- if value.tzinfo is None:
24
- value = value.replace(tzinfo=_dt.timezone.utc)
25
- value = value.astimezone(_dt.timezone.utc)
26
- return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}Z"
27
-
28
-
29
- def _normalize(value: Any, seen: set[int]) -> Any:
30
- if value is None or isinstance(value, (bool, str)):
31
- return value
32
- if isinstance(value, int):
33
- return value
34
- if isinstance(value, float):
35
- if math.isnan(value):
36
- return "NaN"
37
- if math.isinf(value):
38
- return "Infinity" if value > 0 else "-Infinity"
39
- return int(value) if value.is_integer() else value
40
- if isinstance(value, _dt.datetime):
41
- return _iso(value)
42
- if isinstance(value, _dt.date):
43
- return _iso(_dt.datetime(value.year, value.month, value.day, tzinfo=_dt.timezone.utc))
44
- if dataclasses.is_dataclass(value) and not isinstance(value, type):
45
- value = dataclasses.asdict(value)
46
- elif hasattr(value, "model_dump") and callable(value.model_dump):
47
- value = value.model_dump()
48
- if id(value) in seen:
49
- raise TypeError("replyonce: cannot hash a circular payload")
50
- if isinstance(value, (list, tuple)):
51
- seen.add(id(value))
52
- out = [_normalize(v, seen) for v in value]
53
- seen.discard(id(value))
54
- return out
55
- if isinstance(value, dict):
56
- seen.add(id(value))
57
- items = sorted(((str(k), v) for k, v in value.items()), key=lambda kv: _sort_key(kv[0]))
58
- obj = {k: _normalize(v, seen) for k, v in items}
59
- seen.discard(id(value))
60
- return obj
61
- raise TypeError(f"replyonce: cannot hash a payload of type {type(value).__name__}")
62
-
63
-
64
- def canonical_json(value: Any) -> str:
65
- """Deterministic JSON: keys sorted, no whitespace. Matches the TypeScript ``canonicalJson``."""
66
- return json.dumps(_normalize(value, set()), separators=(",", ":"), ensure_ascii=False, sort_keys=False)
67
-
68
-
69
- def sha256_hex(text: str) -> str:
70
- return hashlib.sha256(text.encode("utf-8")).hexdigest()
71
-
72
-
73
- def hash_payload(payload: Any) -> str:
74
- return sha256_hex(canonical_json(payload))[:32]
75
-
76
-
77
- _SAFE_INTENT = re.compile(r"^[A-Za-z0-9_.:-]{1,100}$")
78
-
79
-
80
- def effect_key(intent: str, payload: Any = MISSING) -> str:
81
- """Ledger key for an intent plus the business identity of the payload."""
82
- if not isinstance(intent, str) or not _SAFE_INTENT.match(intent):
83
- raise TypeError(f"replyonce: intent must match {_SAFE_INTENT.pattern} (got {intent!r})")
84
- return intent if payload is MISSING else f"{intent}:{hash_payload(payload)}"
85
-
86
-
87
- def provider_idempotency_key(scope: str, key: str) -> str:
88
- """Stable idempotency key to hand to a provider (Stripe-style ``Idempotency-Key``)."""
89
- return "ro_" + sha256_hex(f"{scope}\u0000{key}")[:40]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes