purra-interaction 0.5.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lybrands
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,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: purra-interaction
3
+ Version: 0.5.0
4
+ Summary: Durable pre-execution user clarification for PurrA
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: purra==0.5.0
10
+ Provides-Extra: sqlite
11
+ Requires-Dist: purra-sqlite==0.5.0; extra == "sqlite"
12
+ Dynamic: license-file
13
+
14
+ # purra-interaction · Python
15
+
16
+ English | [简体中文](README.zh-CN.md)
17
+
18
+ Persist structured questions, wait for user input, and continue execution.
19
+ Requires Python 3.11+.
20
+
21
+ | API | Use |
22
+ | --- | --- |
23
+ | `SqliteClarification` | Suspend and resume the same Run using `purra-sqlite` checkpoints |
24
+ | `ClarificationStore` + `ClarificationWorkflow` | Collect input before execution, then create a Run through an application callback |
25
+
26
+ ## Install
27
+
28
+ For same-Run clarification, run from the repository root:
29
+
30
+ ```sh
31
+ python -m pip install . ./integrations/sqlite/python './integrations/interaction/python[sqlite]'
32
+ ```
33
+
34
+ ## Configure a Run
35
+
36
+ Given a model `gateway`:
37
+
38
+ ```python
39
+ from purra.api import AgentCore, AgentPreset
40
+ from purra.contracts import RuntimeLimits
41
+ from purra.tools import InMemoryToolCatalog
42
+ from purra_sqlite import SqliteAgentAdapters
43
+ from purra_interaction import SqliteClarification
44
+
45
+ storage = SqliteAgentAdapters("agent.db", scope="user-1/project-1")
46
+ interaction = SqliteClarification(storage)
47
+ core = AgentCore(
48
+ model_gateway=gateway,
49
+ preset=AgentPreset(
50
+ id="assistant", revision="1",
51
+ runtime_limits=RuntimeLimits(max_run_generation_tokens=8192),
52
+ tool_catalog=InMemoryToolCatalog((interaction.registration,)),
53
+ ),
54
+ run_repository=storage.runs,
55
+ output_repository=storage.outputs,
56
+ output_publisher=storage.publisher,
57
+ execution_lease_store=storage.leases,
58
+ )
59
+ ```
60
+
61
+ Submit an `AgentRunRequest` with `tools_enabled=True` through
62
+ `await interaction.submit(core, request)`. When the Agent asks a question,
63
+ `handle.wait()` raises `purra.api.UserInputRequired`. Use its `request_id` with
64
+ `await interaction.get(request_id)` to obtain the public question data.
65
+
66
+ The Run remains waiting, with no worker or model call kept alive. After the user
67
+ answers, provide the question revision, a stable command key, and answers keyed
68
+ by question ID:
69
+
70
+ ```python
71
+ async def answer_and_resume(request_id, revision, answer_key, answers):
72
+ ready = await interaction.answer(
73
+ request_id, revision=revision, key=answer_key, answers=answers,
74
+ )
75
+ return await interaction.resume(core, ready["id"])
76
+ ```
77
+
78
+ The returned handle continues the same Run with its spent budget and deadline.
79
+ It may request input again. Answers provide task data and do not grant tool permissions.
80
+
81
+ ## Reload and cancel
82
+
83
+ Recreate the same storage, Agent preset, gateway, and interaction objects after
84
+ restart. `list_pending()` includes waiting and answered requests; resume those
85
+ in `ready` state. Use `cancel(request_id)` while waiting, or the Run handle after
86
+ execution resumes.
87
+
88
+ For Agent trees, bind the same Run-tree repository and answer all pending questions
89
+ under a Root before resuming. Auto, Reactive, and Planned execution are supported.
90
+ Pauses occur at completed tool-round boundaries. Uncertain external writes require
91
+ reconciliation. Close Core before closing storage.
92
+
93
+ ## Pre-execution input
94
+
95
+ `ClarificationStore.ask(...)` saves questions and an application checkpoint.
96
+ Expose `store.public(saved)` to the UI, then call `store.answer(...)`.
97
+ `ClarificationWorkflow.resume(..., submit=callback)` invokes
98
+ `callback(snapshot, continuation_key)` to create a new Run and return its ID.
99
+
100
+ Persist the continuation key on that Run. If submission is interrupted, reconcile
101
+ against the existing Run before retrying. The application restores credentials,
102
+ permissions, and remaining task budgets. Close the store on shutdown.
@@ -0,0 +1,89 @@
1
+ # purra-interaction · Python
2
+
3
+ English | [简体中文](README.zh-CN.md)
4
+
5
+ Persist structured questions, wait for user input, and continue execution.
6
+ Requires Python 3.11+.
7
+
8
+ | API | Use |
9
+ | --- | --- |
10
+ | `SqliteClarification` | Suspend and resume the same Run using `purra-sqlite` checkpoints |
11
+ | `ClarificationStore` + `ClarificationWorkflow` | Collect input before execution, then create a Run through an application callback |
12
+
13
+ ## Install
14
+
15
+ For same-Run clarification, run from the repository root:
16
+
17
+ ```sh
18
+ python -m pip install . ./integrations/sqlite/python './integrations/interaction/python[sqlite]'
19
+ ```
20
+
21
+ ## Configure a Run
22
+
23
+ Given a model `gateway`:
24
+
25
+ ```python
26
+ from purra.api import AgentCore, AgentPreset
27
+ from purra.contracts import RuntimeLimits
28
+ from purra.tools import InMemoryToolCatalog
29
+ from purra_sqlite import SqliteAgentAdapters
30
+ from purra_interaction import SqliteClarification
31
+
32
+ storage = SqliteAgentAdapters("agent.db", scope="user-1/project-1")
33
+ interaction = SqliteClarification(storage)
34
+ core = AgentCore(
35
+ model_gateway=gateway,
36
+ preset=AgentPreset(
37
+ id="assistant", revision="1",
38
+ runtime_limits=RuntimeLimits(max_run_generation_tokens=8192),
39
+ tool_catalog=InMemoryToolCatalog((interaction.registration,)),
40
+ ),
41
+ run_repository=storage.runs,
42
+ output_repository=storage.outputs,
43
+ output_publisher=storage.publisher,
44
+ execution_lease_store=storage.leases,
45
+ )
46
+ ```
47
+
48
+ Submit an `AgentRunRequest` with `tools_enabled=True` through
49
+ `await interaction.submit(core, request)`. When the Agent asks a question,
50
+ `handle.wait()` raises `purra.api.UserInputRequired`. Use its `request_id` with
51
+ `await interaction.get(request_id)` to obtain the public question data.
52
+
53
+ The Run remains waiting, with no worker or model call kept alive. After the user
54
+ answers, provide the question revision, a stable command key, and answers keyed
55
+ by question ID:
56
+
57
+ ```python
58
+ async def answer_and_resume(request_id, revision, answer_key, answers):
59
+ ready = await interaction.answer(
60
+ request_id, revision=revision, key=answer_key, answers=answers,
61
+ )
62
+ return await interaction.resume(core, ready["id"])
63
+ ```
64
+
65
+ The returned handle continues the same Run with its spent budget and deadline.
66
+ It may request input again. Answers provide task data and do not grant tool permissions.
67
+
68
+ ## Reload and cancel
69
+
70
+ Recreate the same storage, Agent preset, gateway, and interaction objects after
71
+ restart. `list_pending()` includes waiting and answered requests; resume those
72
+ in `ready` state. Use `cancel(request_id)` while waiting, or the Run handle after
73
+ execution resumes.
74
+
75
+ For Agent trees, bind the same Run-tree repository and answer all pending questions
76
+ under a Root before resuming. Auto, Reactive, and Planned execution are supported.
77
+ Pauses occur at completed tool-round boundaries. Uncertain external writes require
78
+ reconciliation. Close Core before closing storage.
79
+
80
+ ## Pre-execution input
81
+
82
+ `ClarificationStore.ask(...)` saves questions and an application checkpoint.
83
+ Expose `store.public(saved)` to the UI, then call `store.answer(...)`.
84
+ `ClarificationWorkflow.resume(..., submit=callback)` invokes
85
+ `callback(snapshot, continuation_key)` to create a new Run and return its ID.
86
+
87
+ Persist the continuation key on that Run. If submission is interrupted, reconcile
88
+ against the existing Run before retrying. The application restores credentials,
89
+ permissions, and remaining task budgets. Close the store on shutdown.
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "purra-interaction"
7
+ version = "0.5.0"
8
+ description = "Durable pre-execution user clarification for PurrA"
9
+ requires-python = ">=3.11"
10
+ dependencies = ["purra==0.5.0"]
11
+ readme = "README.md"
12
+ license = "MIT"
13
+
14
+ [project.optional-dependencies]
15
+ sqlite = ["purra-sqlite==0.5.0"]
16
+
17
+ [tool.setuptools.packages.find]
18
+ where = ["src"]
19
+
20
+ [tool.pytest.ini_options]
21
+ pythonpath = ["src", "../../../src"]
22
+ testpaths = ["tests"]
23
+ addopts = "-ra -q"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,202 @@
1
+ """Durable pre-execution clarification, with an explicit host continuation."""
2
+
3
+ import json
4
+ import math
5
+ import sqlite3
6
+ import time
7
+ from uuid import uuid4
8
+
9
+ from purra.task_admission import TaskAdmissionDecision, ExecutionMode
10
+
11
+
12
+ def _text(value, limit=512):
13
+ if not isinstance(value, str) or not value.strip() or len(value) > limit:
14
+ raise ValueError("expected bounded non-empty text")
15
+ return value
16
+
17
+
18
+ def _json(value):
19
+ def normalize(v):
20
+ if v is None or type(v) in (str, bool):
21
+ return v
22
+ if type(v) in (int, float):
23
+ if not math.isfinite(v) or abs(v) > 2**53 - 1:
24
+ raise ValueError("checkpoint numbers must be finite and safely representable")
25
+ return int(v) if v == int(v) else v
26
+ if isinstance(v, (tuple, list)):
27
+ return [normalize(i) for i in v]
28
+ if isinstance(v, dict) and all(isinstance(k, str) for k in v):
29
+ return {k: normalize(i) for k, i in v.items()}
30
+ raise ValueError("checkpoint must be JSON data")
31
+ result = json.dumps(normalize(value), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
32
+ if len(result.encode()) > 131072:
33
+ raise ValueError("clarification exceeds 128 KiB")
34
+ return result
35
+
36
+
37
+ def _questions(values):
38
+ if not isinstance(values, (list, tuple)) or not 1 <= len(values) <= 3:
39
+ raise ValueError("clarification requires 1 to 3 questions")
40
+ result = []
41
+ for row in values:
42
+ if not isinstance(row, dict) or set(row) - {"id", "prompt", "choices", "allowFreeform"}:
43
+ raise ValueError("invalid question")
44
+ choices = row.get("choices", [])
45
+ if not isinstance(choices, (list, tuple)) or len(choices) > 8 or len(set(choices)) != len(choices):
46
+ raise ValueError("invalid choices")
47
+ choices = [_text(v, 128) for v in choices]
48
+ free = row.get("allowFreeform", True)
49
+ if type(free) is not bool or (not free and not choices):
50
+ raise ValueError("question needs a valid answer mode")
51
+ result.append(dict(id=_text(row.get("id"), 128), prompt=_text(row.get("prompt"), 8000), choices=choices, allowFreeform=free))
52
+ if len({q["id"] for q in result}) != len(result):
53
+ raise ValueError("question ids must be unique")
54
+ return result
55
+
56
+
57
+ class ClarificationStore:
58
+ """SQLite adapter scoped to a host-authorized owner/tenant namespace.
59
+
60
+ This database stores clarification checkpoints, not the Core Run journal.
61
+ Never put credentials or executable objects in a checkpoint.
62
+ """
63
+
64
+ def __init__(self, path: str, *, scope: str):
65
+ self.scope = _text(scope)
66
+ self._db = sqlite3.connect(path, timeout=5)
67
+ self._db.execute("PRAGMA journal_mode=WAL")
68
+ self._db.execute("PRAGMA synchronous=FULL")
69
+ self._db.execute("""CREATE TABLE IF NOT EXISTS purra_clarifications (
70
+ scope TEXT NOT NULL, id TEXT NOT NULL, request_key TEXT NOT NULL,
71
+ request_json TEXT NOT NULL, state TEXT NOT NULL, revision INTEGER NOT NULL,
72
+ answer_key TEXT, answers_json TEXT, resume_token TEXT, run_id TEXT,
73
+ PRIMARY KEY(scope, id), UNIQUE(scope, request_key))""")
74
+ self._db.commit()
75
+
76
+ def ask(self, *, key, questions, checkpoint, source_run_id=None, expires_at_ms=None):
77
+ _text(key)
78
+ if source_run_id is not None:
79
+ _text(source_run_id)
80
+ if expires_at_ms is not None and (type(expires_at_ms) is not int or not 0 < expires_at_ms <= 2**53 - 1):
81
+ raise ValueError("expires_at_ms must be a positive integer")
82
+ body = _json(dict(questions=_questions(questions), checkpoint=checkpoint,
83
+ sourceRunId=source_run_id, expiresAtMs=expires_at_ms))
84
+ with self._db:
85
+ self._db.execute("BEGIN IMMEDIATE")
86
+ existing = self._db.execute("SELECT id,request_json FROM purra_clarifications WHERE scope=? AND request_key=?", (self.scope, key)).fetchone()
87
+ if existing:
88
+ if json.loads(existing[1]) != json.loads(body):
89
+ raise ValueError("clarification_idempotency_conflict")
90
+ identifier = existing[0]
91
+ else:
92
+ identifier = uuid4().hex
93
+ self._db.execute("INSERT INTO purra_clarifications(scope,id,request_key,request_json,state,revision) VALUES(?,?,?,?,'waiting',1)", (self.scope, identifier, key, body))
94
+ return self.get(identifier)
95
+
96
+ def get(self, identifier):
97
+ row = self._db.execute("SELECT request_json,state,revision,answers_json,run_id,resume_token FROM purra_clarifications WHERE scope=? AND id=?", (self.scope, _text(identifier))).fetchone()
98
+ if row is None:
99
+ raise KeyError("clarification_not_found")
100
+ body = json.loads(row[0])
101
+ return dict(id=identifier, **body, state=row[1], revision=row[2],
102
+ answers=None if row[3] is None else json.loads(row[3]), runId=row[4], resumeToken=row[5])
103
+
104
+ def answer(self, identifier, *, revision, key, answers):
105
+ _text(key)
106
+ encoded = _json(answers)
107
+ with self._db:
108
+ self._db.execute("BEGIN IMMEDIATE")
109
+ saved = self.get(identifier)
110
+ previous = self._db.execute("SELECT answer_key,answers_json FROM purra_clarifications WHERE scope=? AND id=?", (self.scope, identifier)).fetchone()
111
+ if previous[0] == key:
112
+ if json.loads(previous[1]) != json.loads(encoded):
113
+ raise ValueError("clarification_idempotency_conflict")
114
+ return saved
115
+ self._require(saved, "waiting", revision)
116
+ if not isinstance(answers, dict) or set(answers) != {q["id"] for q in saved["questions"]}:
117
+ raise ValueError("answers must cover exactly the requested questions")
118
+ for q in saved["questions"]:
119
+ answer = _text(answers[q["id"]], 8000)
120
+ if not q["allowFreeform"] and answer not in q["choices"]:
121
+ raise ValueError("answer is not one of the offered choices")
122
+ self._db.execute("UPDATE purra_clarifications SET state='ready',revision=revision+1,answer_key=?,answers_json=? WHERE scope=? AND id=?", (key, encoded, self.scope, identifier))
123
+ return self.get(identifier)
124
+
125
+ def claim(self, identifier, *, revision):
126
+ with self._db:
127
+ self._db.execute("BEGIN IMMEDIATE")
128
+ self._require(self.get(identifier), "ready", revision)
129
+ token = uuid4().hex
130
+ self._db.execute("UPDATE purra_clarifications SET state='resuming',revision=revision+1,resume_token=? WHERE scope=? AND id=?", (token, self.scope, identifier))
131
+ return token, self.get(identifier)
132
+
133
+ def reconcile(self, identifier, *, token, run_id=None, not_submitted=False):
134
+ """Resolve an interrupted submission from authoritative host evidence.
135
+
136
+ Supply its existing Run id, or assert it was never submitted. This is
137
+ never called automatically after an ambiguous transport/process error.
138
+ """
139
+ if type(not_submitted) is not bool or (run_id is None) == (not_submitted is False):
140
+ raise ValueError("provide an existing Run id or not_submitted=True")
141
+ if run_id is not None:
142
+ _text(run_id)
143
+ with self._db:
144
+ self._db.execute("BEGIN IMMEDIATE")
145
+ row = self._db.execute("SELECT state,resume_token,run_id FROM purra_clarifications WHERE scope=? AND id=?", (self.scope, identifier)).fetchone()
146
+ if row is None or row[1] != token:
147
+ raise ValueError("clarification_claim_conflict")
148
+ if row[0] == "resumed" and run_id == row[2]:
149
+ return self.get(identifier)
150
+ if row[0] != "resuming":
151
+ raise ValueError("clarification_state_conflict")
152
+ self._db.execute("UPDATE purra_clarifications SET state=?,revision=revision+1,run_id=? WHERE scope=? AND id=?", ("ready" if not_submitted else "resumed", run_id, self.scope, identifier))
153
+ return self.get(identifier)
154
+
155
+ def cancel(self, identifier, *, revision):
156
+ with self._db:
157
+ self._db.execute("BEGIN IMMEDIATE")
158
+ saved = self.get(identifier)
159
+ if saved["revision"] != revision or saved["state"] not in ("waiting", "ready"):
160
+ raise ValueError("clarification_state_conflict")
161
+ self._db.execute("UPDATE purra_clarifications SET state='canceled',revision=revision+1 WHERE scope=? AND id=?", (self.scope, identifier))
162
+ return self.get(identifier)
163
+
164
+ @staticmethod
165
+ def public(saved):
166
+ return {k: v for k, v in saved.items() if k not in ("checkpoint", "resumeToken")}
167
+
168
+ @staticmethod
169
+ def _require(saved, state, revision):
170
+ if type(revision) is not int or saved["state"] != state or saved["revision"] != revision:
171
+ raise ValueError("clarification_state_conflict")
172
+ if saved["expiresAtMs"] is not None and saved["expiresAtMs"] <= int(time.time() * 1000):
173
+ raise ValueError("clarification_expired")
174
+
175
+ def close(self):
176
+ self._db.close()
177
+
178
+
179
+ class ClarificationWorkflow:
180
+ def __init__(self, store: ClarificationStore):
181
+ self.store = store
182
+
183
+ def admission(self, **request):
184
+ saved = self.store.ask(**request)
185
+ return TaskAdmissionDecision(mode=ExecutionMode.CLARIFY, reason_code="user_input_required",
186
+ message="\n".join(q["prompt"] for q in saved["questions"]), metadata={"inputRequestId": saved["id"]})
187
+
188
+ async def resume(self, identifier, *, revision, submit):
189
+ """submit(snapshot, continuation_key) must return the new Run's id.
190
+
191
+ The host reconstructs authorized options and revalidates permissions.
192
+ A failed/ambiguous submit retains the claim for explicit reconciliation.
193
+ """
194
+ token, saved = self.store.claim(identifier, revision=revision)
195
+ run_id = await submit(saved, "clarification:" + identifier)
196
+ return self.store.reconcile(identifier, token=token, run_id=run_id)
197
+
198
+
199
+ __all__ = ["ClarificationStore", "ClarificationWorkflow"]
200
+
201
+ from .native import SqliteClarification
202
+ __all__ += ["SqliteClarification"]
@@ -0,0 +1,153 @@
1
+ """Checkpoint-based user interaction over the optional SQLite adapters."""
2
+ from dataclasses import replace
3
+ from datetime import datetime, timezone
4
+ from hashlib import sha256
5
+ import json
6
+
7
+ from purra.api import AgentCoreRunOptions, UserInputRequired
8
+ from purra.contracts import AgentMessage, ToolHandlerResult, ToolSchema, ToolPolicy
9
+ from purra.output import AgentOutputEventDraft, RunLifecycleOutputDraft
10
+ from purra.events import AgentEvent
11
+ from purra.ports import ToolRegistration
12
+ from purra.ports.run_lifecycle import RunCommit
13
+ from . import _questions, _json, _text
14
+
15
+
16
+ QUESTION_SCHEMA = {"type": "object", "properties": {"questions": {
17
+ "type": "array", "minItems": 1, "maxItems": 3, "items": {"type": "object", "properties": {
18
+ "id": {"type": "string"}, "prompt": {"type": "string"},
19
+ "choices": {"type": "array", "items": {"type": "string"}, "maxItems": 8},
20
+ "allowFreeform": {"type": "boolean"}}, "required": ["id", "prompt"], "additionalProperties": False}}},
21
+ "required": ["questions"], "additionalProperties": False}
22
+
23
+
24
+ class SqliteClarification:
25
+ def __init__(self, storage, *, options=None):
26
+ self.storage, self.options = storage, options or AgentCoreRunOptions()
27
+ self.registration = ToolRegistration(
28
+ schema=ToolSchema("request_user_input", "Ask the user for missing task information. Execution waits for the answer.", QUESTION_SCHEMA),
29
+ handler=self._tool, policy=ToolPolicy(mode="read", title="Ask the user"),
30
+ )
31
+
32
+ async def _tool(self, state, arguments, signal=None):
33
+ return ToolHandlerResult(json.dumps({"purraInputRequest": _questions(arguments["questions"])}), effect_state="not_started")
34
+
35
+ async def submit(self, core, request):
36
+ async def checkpoint(saved):
37
+ return await self._checkpoint(saved, request)
38
+ return await core.submit(request, options=replace(self.options, checkpoint_handler=checkpoint))
39
+
40
+ async def _checkpoint(self, checkpoint, request):
41
+ pending = []
42
+ question_calls = {call.id for message in checkpoint.messages for call in message.tool_calls
43
+ if call.name == "request_user_input"}
44
+ for message in checkpoint.messages:
45
+ if message.role.value != "tool" or message.tool_call_id not in question_calls: continue
46
+ try: value = json.loads(message.content)
47
+ except (TypeError, ValueError): continue
48
+ if isinstance(value, dict) and "purraInputRequest" in value:
49
+ pending.append((message.tool_call_id, _questions(value["purraInputRequest"])))
50
+ async with self.storage.transaction() as adapters:
51
+ self.storage._guard(checkpoint.run_id)
52
+ tree = adapters.run_tree._runs.get(checkpoint.run_id)
53
+ root_id = tree.root_run_id if tree is not None else checkpoint.run_id
54
+ rows = self.storage.extra.setdefault("clarifications", {})
55
+ for call_id, questions in pending:
56
+ identifier = sha256((checkpoint.run_id + "\0" + call_id).encode()).hexdigest()
57
+ if identifier not in rows:
58
+ rows[identifier] = dict(id=identifier, runId=checkpoint.run_id, rootRunId=root_id, questions=questions,
59
+ state="waiting", revision=1, answers=None, request=request, answerKey=None)
60
+ await self._event(adapters, rows[identifier], "input.required")
61
+ descendants = {run.run_id for run in await adapters.run_tree.list_descendants(checkpoint.run_id)} if tree is not None else set()
62
+ waiting = [row for row in rows.values() if row["runId"] in {checkpoint.run_id, *descendants}
63
+ and row["state"] == "waiting" and adapters.runs._state.runs[row["runId"]].status.value == "running"]
64
+ if waiting:
65
+ raise UserInputRequired(checkpoint.run_id, waiting[0]["id"])
66
+ return checkpoint
67
+
68
+ async def get(self, identifier):
69
+ async with self.storage.transaction() as adapters:
70
+ row = self.storage.extra.get("clarifications", {})[identifier]
71
+ result = {key: row[key] for key in ("id", "runId", "rootRunId", "questions", "state", "revision", "answers")}
72
+ status = adapters.runs._state.runs[row["runId"]].status.value
73
+ if status != "running": result["state"] = "completed" if status == "done" else status
74
+ lease = self.storage._leases.get(row["runId"])
75
+ if status == "running" and row["state"] == "ready" and lease is not None and lease.owner_id is not None and (lease.expires_at_ms or 0) > int(datetime.now().timestamp() * 1000):
76
+ result["state"] = "running"
77
+ return result
78
+
79
+ async def list_pending(self):
80
+ async with self.storage.transaction() as adapters:
81
+ identifiers = tuple(row["id"] for row in self.storage.extra.get("clarifications", {}).values()
82
+ if adapters.runs._state.runs[row["runId"]].status.value == "running")
83
+ return tuple([await self.get(identifier) for identifier in identifiers])
84
+
85
+ async def list_waiting(self):
86
+ async with self.storage.transaction() as adapters:
87
+ return tuple({key: row[key] for key in ("id", "runId", "questions", "state", "revision")}
88
+ for row in self.storage.extra.get("clarifications", {}).values() if row["state"] == "waiting"
89
+ and adapters.runs._state.runs[row["runId"]].status.value == "running")
90
+
91
+ async def answer(self, identifier, *, revision, key, answers):
92
+ _text(key); _json(answers)
93
+ async with self.storage.transaction() as adapters:
94
+ row = self.storage.extra["clarifications"][identifier]
95
+ if row["answerKey"] == key:
96
+ if row["answers"] != answers: raise ValueError("clarification_idempotency_conflict")
97
+ else:
98
+ if row["state"] != "waiting" or row["revision"] != revision: raise ValueError("clarification_revision_conflict")
99
+ if not isinstance(answers, dict) or set(answers) != {q["id"] for q in row["questions"]}: raise ValueError("answers must cover the questions")
100
+ for q in row["questions"]:
101
+ value = _text(answers[q["id"]], 8000)
102
+ if not q["allowFreeform"] and value not in q["choices"]: raise ValueError("invalid answer choice")
103
+ run = adapters.runs._state.runs[row["runId"]]
104
+ if run.status.value != "running": raise ValueError("clarification_run_terminal")
105
+ if run.params.deadline_at_ms is not None and run.params.deadline_at_ms <= int(datetime.now().timestamp() * 1000): raise ValueError("clarification_expired")
106
+ checkpoint = run.execution_checkpoint
107
+ if checkpoint is None: raise ValueError("clarification_checkpoint_missing")
108
+ message = AgentMessage("user", "Answers to requested task information:\n" + _json(answers), attributes={"inputRequestId": identifier})
109
+ await adapters.runs.commit(row["runId"], RunCommit(execution_checkpoint=replace(checkpoint, input_revision=checkpoint.input_revision + 1, messages=(*checkpoint.messages, message))))
110
+ row.update(state="ready", revision=revision + 1, answers=answers, answerKey=key)
111
+ await self._event(adapters, row, "input.answered")
112
+ return await self.get(identifier)
113
+
114
+ async def resume(self, core, identifier):
115
+ async with self.storage.transaction() as adapters:
116
+ row = self.storage.extra["clarifications"][identifier]
117
+ if row["state"] != "ready": raise ValueError("clarification_not_ready")
118
+ if any(r["rootRunId"] == row["rootRunId"] and r["state"] == "waiting"
119
+ and adapters.runs._state.runs[r["runId"]].status.value == "running"
120
+ for r in self.storage.extra["clarifications"].values()): raise ValueError("clarification_answers_incomplete")
121
+ request, run_id = row["request"], row["rootRunId"]
122
+ async def checkpoint(saved): return await self._checkpoint(saved, request)
123
+ return await core.resume(run_id, request, options=replace(self.options, checkpoint_handler=checkpoint))
124
+
125
+ async def cancel(self, identifier):
126
+ async with self.storage.transaction() as adapters:
127
+ row = self.storage.extra["clarifications"][identifier]
128
+ run = adapters.runs._state.runs[row["rootRunId"]]
129
+ if run.status.value != "running": return False
130
+ root_id = row["rootRunId"]
131
+ tree = adapters.run_tree._runs.get(root_id)
132
+ run_ids = [root_id, *(r.run_id for r in await adapters.run_tree.list_descendants(root_id))] if tree else [root_id]
133
+ if any((lease := self.storage._leases.get(rid)) is not None and lease.owner_id is not None for rid in run_ids):
134
+ raise ValueError("cancel the active Run through its handle")
135
+ for rid in run_ids:
136
+ canonical = adapters.runs._state.runs.get(rid)
137
+ if canonical is None or canonical.status.value != "running": continue
138
+ await adapters.outputs.commit_run_lifecycle(rid, RunCommit(
139
+ terminal_status="canceled", events=(AgentEvent("run.canceled", {"reason": "user_input_canceled"}, rid),)),
140
+ RunLifecycleOutputDraft(source_event_key=f"input:{identifier}:{rid}:canceled", status="canceled",
141
+ payload={"status": "canceled", "reason": "user_input_canceled"}, occurred_at=datetime.now(timezone.utc)))
142
+ if tree: await adapters.run_tree.cancel_subtree(root_id)
143
+ return True
144
+
145
+ @staticmethod
146
+ async def _event(adapters, row, kind):
147
+ await adapters.outputs.append_event(AgentOutputEventDraft(
148
+ run_id=row["runId"], turn_id=None, output_stream_id=None, invocation_id=None,
149
+ source_event_key=f"input:{row['id']}:{kind}", source="runtime", kind="runtime.event",
150
+ channel="lifecycle", visibility="public", payload={"type": kind,
151
+ **{k: row[k] for k in ("id", "runId", "questions", "state", "revision")}},
152
+ occurred_at=datetime.now(timezone.utc),
153
+ ))
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: purra-interaction
3
+ Version: 0.5.0
4
+ Summary: Durable pre-execution user clarification for PurrA
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: purra==0.5.0
10
+ Provides-Extra: sqlite
11
+ Requires-Dist: purra-sqlite==0.5.0; extra == "sqlite"
12
+ Dynamic: license-file
13
+
14
+ # purra-interaction · Python
15
+
16
+ English | [简体中文](README.zh-CN.md)
17
+
18
+ Persist structured questions, wait for user input, and continue execution.
19
+ Requires Python 3.11+.
20
+
21
+ | API | Use |
22
+ | --- | --- |
23
+ | `SqliteClarification` | Suspend and resume the same Run using `purra-sqlite` checkpoints |
24
+ | `ClarificationStore` + `ClarificationWorkflow` | Collect input before execution, then create a Run through an application callback |
25
+
26
+ ## Install
27
+
28
+ For same-Run clarification, run from the repository root:
29
+
30
+ ```sh
31
+ python -m pip install . ./integrations/sqlite/python './integrations/interaction/python[sqlite]'
32
+ ```
33
+
34
+ ## Configure a Run
35
+
36
+ Given a model `gateway`:
37
+
38
+ ```python
39
+ from purra.api import AgentCore, AgentPreset
40
+ from purra.contracts import RuntimeLimits
41
+ from purra.tools import InMemoryToolCatalog
42
+ from purra_sqlite import SqliteAgentAdapters
43
+ from purra_interaction import SqliteClarification
44
+
45
+ storage = SqliteAgentAdapters("agent.db", scope="user-1/project-1")
46
+ interaction = SqliteClarification(storage)
47
+ core = AgentCore(
48
+ model_gateway=gateway,
49
+ preset=AgentPreset(
50
+ id="assistant", revision="1",
51
+ runtime_limits=RuntimeLimits(max_run_generation_tokens=8192),
52
+ tool_catalog=InMemoryToolCatalog((interaction.registration,)),
53
+ ),
54
+ run_repository=storage.runs,
55
+ output_repository=storage.outputs,
56
+ output_publisher=storage.publisher,
57
+ execution_lease_store=storage.leases,
58
+ )
59
+ ```
60
+
61
+ Submit an `AgentRunRequest` with `tools_enabled=True` through
62
+ `await interaction.submit(core, request)`. When the Agent asks a question,
63
+ `handle.wait()` raises `purra.api.UserInputRequired`. Use its `request_id` with
64
+ `await interaction.get(request_id)` to obtain the public question data.
65
+
66
+ The Run remains waiting, with no worker or model call kept alive. After the user
67
+ answers, provide the question revision, a stable command key, and answers keyed
68
+ by question ID:
69
+
70
+ ```python
71
+ async def answer_and_resume(request_id, revision, answer_key, answers):
72
+ ready = await interaction.answer(
73
+ request_id, revision=revision, key=answer_key, answers=answers,
74
+ )
75
+ return await interaction.resume(core, ready["id"])
76
+ ```
77
+
78
+ The returned handle continues the same Run with its spent budget and deadline.
79
+ It may request input again. Answers provide task data and do not grant tool permissions.
80
+
81
+ ## Reload and cancel
82
+
83
+ Recreate the same storage, Agent preset, gateway, and interaction objects after
84
+ restart. `list_pending()` includes waiting and answered requests; resume those
85
+ in `ready` state. Use `cancel(request_id)` while waiting, or the Run handle after
86
+ execution resumes.
87
+
88
+ For Agent trees, bind the same Run-tree repository and answer all pending questions
89
+ under a Root before resuming. Auto, Reactive, and Planned execution are supported.
90
+ Pauses occur at completed tool-round boundaries. Uncertain external writes require
91
+ reconciliation. Close Core before closing storage.
92
+
93
+ ## Pre-execution input
94
+
95
+ `ClarificationStore.ask(...)` saves questions and an application checkpoint.
96
+ Expose `store.public(saved)` to the UI, then call `store.answer(...)`.
97
+ `ClarificationWorkflow.resume(..., submit=callback)` invokes
98
+ `callback(snapshot, continuation_key)` to create a new Run and return its ID.
99
+
100
+ Persist the continuation key on that Run. If submission is interrupted, reconcile
101
+ against the existing Run before retrying. The application restores credentials,
102
+ permissions, and remaining task budgets. Close the store on shutdown.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/purra_interaction/__init__.py
5
+ src/purra_interaction/native.py
6
+ src/purra_interaction.egg-info/PKG-INFO
7
+ src/purra_interaction.egg-info/SOURCES.txt
8
+ src/purra_interaction.egg-info/dependency_links.txt
9
+ src/purra_interaction.egg-info/requires.txt
10
+ src/purra_interaction.egg-info/top_level.txt
11
+ tests/test_interaction.py
12
+ tests/test_modes.py
13
+ tests/test_native.py
@@ -0,0 +1,4 @@
1
+ purra==0.5.0
2
+
3
+ [sqlite]
4
+ purra-sqlite==0.5.0
@@ -0,0 +1 @@
1
+ purra_interaction
@@ -0,0 +1,73 @@
1
+ import asyncio
2
+ import pytest
3
+ from purra_interaction import ClarificationStore, ClarificationWorkflow
4
+
5
+
6
+ def ask(store, **changes):
7
+ return store.ask(key="draft-1", questions=[dict(id="length", prompt="选择篇幅", choices=["短篇", "长篇"], allowFreeform=False)],
8
+ checkpoint={"messages": [{"role": "user", "content": "写故事"}], "task": "draft-1"}, **changes)
9
+
10
+
11
+ @pytest.mark.asyncio
12
+ async def test_restart_answer_claim_and_continue_exactly_once(tmp_path):
13
+ path = str(tmp_path / "interaction.db")
14
+ first = ClarificationStore(path, scope="user/project")
15
+ pending = ask(first)
16
+ assert pending["state"] == "waiting"
17
+ first.close()
18
+ store = ClarificationStore(path, scope="user/project")
19
+ competitor = ClarificationStore(path, scope="user/project")
20
+ ready = store.answer(pending["id"], revision=1, key="answer-1", answers={"length": "短篇"})
21
+ assert competitor.answer(pending["id"], revision=1, key="answer-1", answers={"length": "短篇"}) == ready
22
+ calls = []
23
+ async def submit(snapshot, key):
24
+ calls.append(key)
25
+ assert snapshot["answers"] == {"length": "短篇"}
26
+ with pytest.raises(ValueError, match="state_conflict"):
27
+ competitor.claim(snapshot["id"], revision=ready["revision"])
28
+ return "continued-run"
29
+ resumed = await ClarificationWorkflow(store).resume(pending["id"], revision=ready["revision"], submit=submit)
30
+ assert resumed["runId"] == "continued-run" and len(calls) == 1
31
+ assert "checkpoint" not in store.public(resumed) and "resumeToken" not in store.public(resumed)
32
+ assert ask(store)["id"] == pending["id"]
33
+ store.close(); competitor.close()
34
+
35
+
36
+ @pytest.mark.asyncio
37
+ async def test_ambiguous_submission_is_not_repeated_and_can_be_reconciled_after_restart(tmp_path):
38
+ path = str(tmp_path / "interaction.db")
39
+ store = ClarificationStore(path, scope="owner")
40
+ pending = ask(store)
41
+ ready = store.answer(pending["id"], revision=1, key="a", answers={"length": "长篇"})
42
+ async def disconnected(snapshot, key):
43
+ raise ConnectionError("lost receipt")
44
+ with pytest.raises(ConnectionError):
45
+ await ClarificationWorkflow(store).resume(pending["id"], revision=ready["revision"], submit=disconnected)
46
+ store.close()
47
+ store = ClarificationStore(path, scope="owner")
48
+ saved = store.get(pending["id"])
49
+ assert saved["state"] == "resuming"
50
+ with pytest.raises(ValueError, match="state_conflict"):
51
+ store.claim(saved["id"], revision=saved["revision"])
52
+ resolved = store.reconcile(saved["id"], token=saved["resumeToken"], run_id="existing-run")
53
+ assert resolved["state"] == "resumed"
54
+ store.close()
55
+
56
+
57
+ def test_scope_validation_expiry_and_cancellation(tmp_path):
58
+ path = str(tmp_path / "interaction.db")
59
+ store = ClarificationStore(path, scope="one")
60
+ other = ClarificationStore(path, scope="two")
61
+ pending = ask(store)
62
+ with pytest.raises(KeyError):
63
+ other.get(pending["id"])
64
+ for answers in ({"length": "unknown"}, {"extra": "短篇"}, {}):
65
+ with pytest.raises(ValueError):
66
+ store.answer(pending["id"], revision=1, key="a", answers=answers)
67
+ store.cancel(pending["id"], revision=1)
68
+ with pytest.raises(ValueError, match="state_conflict"):
69
+ store.answer(pending["id"], revision=2, key="a", answers={"length": "短篇"})
70
+ expired = ask(other, expires_at_ms=1)
71
+ with pytest.raises(ValueError, match="expired"):
72
+ other.answer(expired["id"], revision=1, key="a", answers={"length": "短篇"})
73
+ store.close(); other.close()
@@ -0,0 +1,235 @@
1
+ import asyncio
2
+ import json
3
+ from dataclasses import replace
4
+ import pytest
5
+ from purra.api import (
6
+ AgentComponentBinding,
7
+ AgentCore,
8
+ AgentPreset,
9
+ ExecutionProfile,
10
+ UserInputRequired,
11
+ )
12
+ from purra.contracts import (AgentMessage, AgentRunRequest, DomainContext, ModelRequest, ModelStream,
13
+ ModelStreamChunk, ToolCallDelta, ModelTokenUsage, RuntimeLimits, PlanningResult, WorkPlan, WorkStep)
14
+ from purra.agent_tree_policy import AgentTreePolicy
15
+ from purra.model_protocol import generic_capability_snapshot
16
+ from purra.tools import InMemoryToolCatalog
17
+ from purra_sqlite import SqliteAgentAdapters
18
+ from purra_interaction import SqliteClarification
19
+
20
+ QUESTION = {"questions": [{"id": "detail", "prompt": "Choose a detail", "choices": ["yes", "no"], "allowFreeform": False}]}
21
+
22
+ def plan(ask=True, suffix=""):
23
+ steps = [WorkStep(id="ask" + suffix, title="Ask", type="read", executor="tool", capability_names=("request_user_input",))] if ask else []
24
+ steps.append(WorkStep(id="finish" + suffix, title="Finish", type="review", executor="model", depends_on=("ask" + suffix,) if ask else ()))
25
+ return PlanningResult(kind="planned", work_plan=WorkPlan(title="Clarify and finish", steps=tuple(steps)))
26
+
27
+ class Planner:
28
+ def __init__(self, ask=True): self.calls = 0; self.revisions = []; self.ask = ask
29
+ async def create_plan(self, *args, **kwargs): self.calls += 1; return plan(self.ask)
30
+ async def revise_plan(self, request, capabilities, turn, *args, **kwargs):
31
+ self.revisions.append(turn.revision); return plan(False)
32
+
33
+ class Gateway:
34
+ def __init__(self, script): self.calls = []; self.script = script
35
+ async def complete(self, *args, **kwargs): raise AssertionError("stream expected")
36
+ async def stream(self, messages, invocation, signal=None):
37
+ self.calls.append(messages)
38
+ result = self.script(messages, len(self.calls))
39
+ async def chunks():
40
+ if isinstance(result, tuple):
41
+ name, args = result
42
+ yield ModelStreamChunk(tool_call_deltas=(ToolCallDelta(index=0, id=f"call-{sum(len(m.tool_calls) for m in messages) + 1}", name=name, arguments_fragment=json.dumps(args)),), finish_reason="tool_calls", usage=ModelTokenUsage(input_tokens=2, generation_tokens=2))
43
+ else: yield ModelStreamChunk(content_delta=result, finish_reason="stop", usage=ModelTokenUsage(input_tokens=2, generation_tokens=2))
44
+ return ModelStream(
45
+ chunks=chunks(),
46
+ model="fixture",
47
+ applied_generation_limit=invocation.output_budget.max_generation_tokens,
48
+ )
49
+
50
+ def answered(messages): return any(isinstance(m.content, str) and "Answers to requested" in m.content for m in messages)
51
+
52
+ def compose(path, script, planner=None, tree=False, replan=False):
53
+ storage = SqliteAgentAdapters(path, scope="modes")
54
+ interaction = SqliteClarification(storage)
55
+ if replan:
56
+ original = interaction.registration.handler
57
+ async def question(*args, **kwargs):
58
+ return replace(await original(*args, **kwargs), planning_disposition="replan")
59
+ interaction.registration = replace(interaction.registration, handler=question)
60
+ gateway = Gateway(script)
61
+ profile = ExecutionProfile(planner=planner)
62
+ bindings = (
63
+ {"planner": AgentComponentBinding("interaction.planner", "1")}
64
+ if planner is not None
65
+ else {}
66
+ )
67
+ core = AgentCore(model_gateway=gateway, run_repository=storage.runs, output_repository=storage.outputs,
68
+ output_publisher=storage.publisher, execution_lease_store=storage.leases,
69
+ run_tree_repository=storage.run_tree if tree else None,
70
+ preset=AgentPreset(
71
+ id="interaction-modes",
72
+ revision="1",
73
+ tool_catalog=InMemoryToolCatalog((interaction.registration,)),
74
+ runtime_limits=RuntimeLimits(max_run_generation_tokens=1000),
75
+ execution_profile=profile,
76
+ component_bindings=bindings,
77
+ agent_tree_policy=(
78
+ AgentTreePolicy(allow_recursive_agents=True) if tree else None
79
+ ),
80
+ ))
81
+ request = AgentRunRequest(messages=(AgentMessage("user", "Root task"),), model=ModelRequest("fixture", "fixture", replace(generic_capability_snapshot(), max_generation_tokens=32)),
82
+ domain_context=DomainContext("fixture"), context_window=65536, tools_enabled=True)
83
+ return storage, interaction, gateway, core, request
84
+
85
+ @pytest.mark.asyncio
86
+ @pytest.mark.parametrize("mode", ["auto", "planned", "promoted", "remaining"])
87
+ async def test_modes_restart_keep_plan_and_auto_activation(tmp_path, mode):
88
+ def initial(messages, count):
89
+ if mode == "promoted" and count == 1: return "request_plan", {}
90
+ return "request_user_input", QUESTION
91
+ planner = Planner(mode != "remaining") if mode != "auto" else None
92
+ storage, interaction, gateway, core, request = compose(tmp_path / "modes.db", initial, planner)
93
+ request = replace(request, planning_mode="planned" if mode == "planned" else "auto")
94
+ handle = await interaction.submit(core, request)
95
+ with pytest.raises(UserInputRequired) as paused: await handle.wait()
96
+ checkpoint = (await storage.runs.get(handle.run_id)).execution_checkpoint
97
+ assert checkpoint.execution_profile == ("planned" if mode in {"planned", "promoted"} else "auto")
98
+ if mode in {"planned", "promoted"}:
99
+ assert (await storage.runs.get(handle.run_id)).steps[0].status.value == "done"
100
+ await core.close(); storage.close()
101
+ def resumed(messages, count):
102
+ assert answered(messages)
103
+ if mode == "remaining" and count == 1: return "request_remaining_plan", {}
104
+ return "Finished"
105
+ planner = Planner(False) if planner else None
106
+ storage, interaction, gateway, core, _ = compose(tmp_path / "modes.db", resumed, planner)
107
+ try:
108
+ await interaction.answer(paused.value.request_id, revision=1, key="answer", answers={"detail": "yes"})
109
+ resumed_handle = await interaction.resume(core, paused.value.request_id)
110
+ result = await resumed_handle.wait()
111
+ assert result.status.value == "done", result
112
+ assert resumed_handle.run_id == handle.run_id
113
+ if planner: assert planner.calls == (1 if mode == "remaining" else 0)
114
+ finally: await core.close(); storage.close()
115
+
116
+
117
+ def tree_script(messages, count):
118
+ instruction = next((m.content for m in messages if m.role.value == "system" and m.attributes.get("agentId")), "root")
119
+ delegated = any(m.role.value == "tool" and '"pendingRunIds"' in m.content for m in messages)
120
+ if instruction in {"root", "middle"}:
121
+ if not delegated:
122
+ names = ["middle", "sibling"] if instruction == "root" else ["leaf"]
123
+ return "delegateToAgents", {"children": [{"name": name, "title": name, "instruction": name, "objective": name} for name in names]}
124
+ for m in messages:
125
+ if m.role.value == "tool" and '"pendingRunIds"' in m.content: assert not json.loads(m.content)["pendingRunIds"]
126
+ return "Tree finished"
127
+ return "Child finished" if answered(messages) else ("request_user_input", QUESTION)
128
+
129
+ @pytest.mark.asyncio
130
+ @pytest.mark.parametrize("cancel", [False, True])
131
+ async def test_nested_tree_questions_restart_and_cancel(tmp_path, cancel):
132
+ path = tmp_path / "tree.db"
133
+ storage, interaction, gateway, core, request = compose(path, tree_script, tree=True)
134
+ handle = await interaction.submit(core, request)
135
+ with pytest.raises(UserInputRequired): await asyncio.wait_for(handle.wait(), 8)
136
+ questions = await interaction.list_waiting()
137
+ assert len(questions) == 2
138
+ descendants = await storage.run_tree.list_descendants(handle.run_id)
139
+ assert len(descendants) == 3 and all(run.status.value == "waiting" and run.lease_owner_id is None for run in descendants)
140
+ await core.close(); storage.close()
141
+ storage, interaction, gateway, core, _ = compose(path, tree_script, tree=True)
142
+ try:
143
+ if cancel:
144
+ assert await interaction.cancel(questions[0]["id"])
145
+ assert (await storage.runs.get(handle.run_id)).status.value == "canceled"
146
+ assert all(run.status.value == "canceled" for run in await storage.run_tree.list_descendants(handle.run_id))
147
+ assert not await interaction.list_waiting()
148
+ else:
149
+ for q in questions: await interaction.answer(q["id"], revision=1, key="answer", answers={"detail": "yes"})
150
+ resumed = await interaction.resume(core, questions[0]["id"])
151
+ result = await asyncio.wait_for(resumed.wait(), 8)
152
+ assert result.status.value == "done", result
153
+ assert resumed.run_id == handle.run_id
154
+ assert all(run.status.value == "done" for run in await storage.run_tree.list_descendants(handle.run_id))
155
+ assert not await interaction.list_pending()
156
+ finally: await core.close(); storage.close()
157
+
158
+
159
+ @pytest.mark.asyncio
160
+ async def test_replanning_revision_survives_two_input_waits(tmp_path):
161
+ class RevisingPlanner(Planner):
162
+ async def revise_plan(self, request, capabilities, turn, *args, **kwargs):
163
+ self.revisions.append(turn.revision)
164
+ return plan(turn.revision == 1, str(turn.revision))
165
+ def script(messages, count):
166
+ answers = sum("Answers to requested" in m.content for m in messages)
167
+ return ("request_user_input", QUESTION) if answers < 2 else "Finished"
168
+ path = tmp_path / "revisions.db"
169
+ planner = RevisingPlanner()
170
+ storage, interaction, gateway, core, request = compose(path, script, planner, replan=True)
171
+ request = replace(request, planning_mode="planned")
172
+ handle = await interaction.submit(core, request)
173
+ for revision in (0, 1):
174
+ with pytest.raises(UserInputRequired) as pause: await handle.wait()
175
+ checkpoint = (await storage.runs.get(handle.run_id)).execution_checkpoint
176
+ assert checkpoint.dynamic_replan_pending and checkpoint.planning_state["revision"] == revision
177
+ assert planner.revisions == ([] if revision == 0 else [1])
178
+ await core.close(); storage.close()
179
+ planner = RevisingPlanner()
180
+ storage, interaction, gateway, core, _ = compose(path, script, planner, replan=True)
181
+ await interaction.answer(pause.value.request_id, revision=1, key="a", answers={"detail": "yes"})
182
+ handle = await interaction.resume(core, pause.value.request_id)
183
+ try:
184
+ result = await handle.wait()
185
+ assert result.status.value == "done", result
186
+ assert planner.calls == 0 and planner.revisions == [2]
187
+ finally: await core.close(); storage.close()
188
+
189
+
190
+ @pytest.mark.asyncio
191
+ async def test_planned_root_and_auto_promoted_children_resume_together(tmp_path):
192
+ class TreePlanner(Planner):
193
+ async def create_plan(self, request, *args, **kwargs):
194
+ self.calls += 1
195
+ instruction = next((m.content for m in request.messages if m.attributes.get("agentId")), "root")
196
+ if instruction not in {"root", "middle"}: return plan()
197
+ return PlanningResult(kind="planned", work_plan=WorkPlan(title="Delegate", steps=(
198
+ WorkStep(id="delegate", title="Delegate", type="write", executor="tool", capability_names=("delegateToAgents",)),
199
+ WorkStep(id="finish", title="Finish", type="review", executor="model", depends_on=("delegate",)),
200
+ )))
201
+ async def revise_plan(self, request, capabilities, turn, *args, **kwargs):
202
+ for message in turn.messages:
203
+ if message.role.value == "tool":
204
+ value = json.loads(message.content)
205
+ if value.get("tool") == "delegateToAgents":
206
+ assert not json.loads(value["excerpt"])["pendingRunIds"]
207
+ self.revisions.append(turn.revision)
208
+ return plan(False, "-revised")
209
+ def make_script():
210
+ seen = set()
211
+ def script(messages, count):
212
+ instruction = next((m.content for m in messages if m.role.value == "system" and m.attributes.get("agentId")), "root")
213
+ if instruction != "root" and instruction not in seen and not answered(messages) and not any(m.role.value == "tool" for m in messages):
214
+ seen.add(instruction); return "request_plan", {}
215
+ return tree_script(messages, count)
216
+ return script
217
+ path = tmp_path / "planned-tree.db"
218
+ planner = TreePlanner()
219
+ storage, interaction, gateway, core, request = compose(path, make_script(), planner, tree=True)
220
+ handle = await interaction.submit(core, replace(request, planning_mode="planned"))
221
+ with pytest.raises(UserInputRequired): await handle.wait()
222
+ pending = await interaction.list_waiting()
223
+ assert len(pending) == 2
224
+ assert planner.calls == 4
225
+ await core.close(); storage.close()
226
+ planner = TreePlanner()
227
+ storage, interaction, gateway, core, _ = compose(path, make_script(), planner, tree=True)
228
+ try:
229
+ for row in pending: await interaction.answer(row["id"], revision=1, key="a", answers={"detail": "yes"})
230
+ resumed = await interaction.resume(core, pending[0]["id"])
231
+ result = await resumed.wait()
232
+ assert result.status.value == "done", result
233
+ assert planner.calls == 0 and planner.revisions == [1, 1]
234
+ assert all(run.status.value == "done" for run in await storage.run_tree.list_descendants(handle.run_id))
235
+ finally: await core.close(); storage.close()
@@ -0,0 +1,127 @@
1
+ import asyncio
2
+ from dataclasses import replace
3
+ import pytest
4
+ from purra.api import AgentCore, AgentPreset, UserInputRequired
5
+ from purra.contracts import AgentMessage, AgentRunRequest, DomainContext, ModelRequest, ModelStream, ModelStreamChunk, ToolCallDelta, ModelTokenUsage, RuntimeLimits
6
+ from purra.model_protocol import generic_capability_snapshot
7
+ from purra.tools import InMemoryToolCatalog
8
+ from purra_sqlite import SqliteAgentAdapters
9
+ from purra_interaction import SqliteClarification
10
+
11
+
12
+ class Gateway:
13
+ def __init__(self): self.calls = []
14
+ async def complete(self, *args, **kwargs): raise AssertionError("stream expected")
15
+ async def stream(self, messages, invocation, signal=None):
16
+ self.calls.append(messages)
17
+ answered = any('Answers to requested' in m.content for m in messages)
18
+ async def chunks():
19
+ if answered:
20
+ yield ModelStreamChunk(content_delta="Finished with the answer", finish_reason="stop", usage=ModelTokenUsage(input_tokens=5, generation_tokens=7))
21
+ else:
22
+ yield ModelStreamChunk(tool_call_deltas=(ToolCallDelta(index=0, id="ask-1", name="request_user_input", arguments_fragment='{"questions":[{"id":"length","prompt":"篇幅?","choices":["短","长"],"allowFreeform":false}]}'),), finish_reason="tool_calls", usage=ModelTokenUsage(input_tokens=10, generation_tokens=20))
23
+ return ModelStream(
24
+ chunks=chunks(),
25
+ model="fixture",
26
+ applied_generation_limit=invocation.output_budget.max_generation_tokens,
27
+ )
28
+
29
+
30
+ def compose(path, *, max_attempts=64):
31
+ storage = SqliteAgentAdapters(path, scope="owner/project")
32
+ interaction = SqliteClarification(storage)
33
+ gateway = Gateway()
34
+ core = AgentCore(model_gateway=gateway, run_repository=storage.runs,
35
+ output_repository=storage.outputs, output_publisher=storage.publisher, execution_lease_store=storage.leases,
36
+ preset=AgentPreset(id="sqlite", revision="1", tool_catalog=InMemoryToolCatalog((interaction.registration,)),
37
+ runtime_limits=RuntimeLimits(max_run_generation_tokens=100, max_model_invocation_attempts=max_attempts)))
38
+ request = AgentRunRequest(messages=(AgentMessage("user", "Write"),),
39
+ model=ModelRequest("fixture", "fixture", replace(generic_capability_snapshot(), max_generation_tokens=32)),
40
+ domain_context=DomainContext("fixture"), context_window=65536, tools_enabled=True, planning_mode="reactive")
41
+ return storage, interaction, gateway, core, request
42
+
43
+
44
+ @pytest.mark.asyncio
45
+ async def test_question_restart_answer_resume_preserves_budget_and_output(tmp_path):
46
+ path = tmp_path / "agent.db"
47
+ storage, interaction, gateway, core, request = compose(path)
48
+ handle = await interaction.submit(core, request)
49
+ with pytest.raises(UserInputRequired) as waiting:
50
+ await handle.wait()
51
+ identifier, run_id = waiting.value.request_id, handle.run_id
52
+ assert (await storage.runs.get(run_id)).status.value == "running"
53
+ assert len(gateway.calls) == 1
54
+ before = await storage.outputs.list_events(run_id, after_sequence=0)
55
+ await core.close(); storage.close()
56
+ storage, interaction, gateway, core, request = compose(path)
57
+ try:
58
+ pending = await interaction.get(identifier)
59
+ assert pending["state"] == "waiting" and "request" not in pending
60
+ with pytest.raises(ValueError, match="invalid answer"):
61
+ await interaction.answer(identifier, revision=1, key="bad", answers={"length": "invalid"})
62
+ ready = await interaction.answer(identifier, revision=1, key="answer", answers={"length": "短"})
63
+ assert ready == await interaction.answer(identifier, revision=1, key="answer", answers={"length": "短"})
64
+ resumed = await interaction.resume(core, identifier)
65
+ result = await resumed.wait()
66
+ assert resumed.run_id == run_id and result.final_response == "Finished with the answer", result
67
+ assert len(gateway.calls) == 2
68
+ assert all(any("Answers to requested" in m.content for m in call) for call in gateway.calls)
69
+ async with storage.transaction() as adapters:
70
+ run = adapters.runs._state.runs[run_id]
71
+ assert len(run.model_attempt_ids) == 3
72
+ assert sum(u.generation_tokens for u in run.model_usage_by_invocation.values() if u) == 34
73
+ events = await storage.outputs.list_events(run_id, after_sequence=0)
74
+ assert events[:len(before)] == before
75
+ assert sum(e.payload.get("type") == "input.required" for e in events) == 1
76
+ assert all("checkpoint" not in str(e.payload).lower() or e.kind.value == "runtime.event" for e in events if e.visibility.value == "public")
77
+ finally:
78
+ await core.close(); storage.close()
79
+
80
+
81
+ @pytest.mark.asyncio
82
+ async def test_resume_cannot_reset_budget_and_cancel_is_durable(tmp_path):
83
+ for cancel in (False, True):
84
+ storage, interaction, gateway, core, request = compose(tmp_path / f"budget-{cancel}.db", max_attempts=1)
85
+ try:
86
+ handle = await interaction.submit(core, request)
87
+ with pytest.raises(UserInputRequired) as waiting: await handle.wait()
88
+ identifier = waiting.value.request_id
89
+ if cancel:
90
+ assert await interaction.cancel(identifier)
91
+ assert not await interaction.cancel(identifier)
92
+ assert (await interaction.get(identifier))["state"] == "canceled"
93
+ assert not await interaction.list_waiting()
94
+ with pytest.raises(ValueError): await interaction.answer(identifier, revision=1, key="a", answers={"length": "短"})
95
+ else:
96
+ await interaction.answer(identifier, revision=1, key="a", answers={"length": "短"})
97
+ resumed = await interaction.resume(core, identifier)
98
+ result = await resumed.wait()
99
+ assert result.status.value == "failed"
100
+ assert len(gateway.calls) == 1
101
+ finally: await core.close(); storage.close()
102
+
103
+
104
+ @pytest.mark.asyncio
105
+ async def test_concurrent_resume_has_one_execution_owner(tmp_path):
106
+ storage, interaction, gateway, core, request = compose(tmp_path / "lease.db")
107
+ entered, release = asyncio.Event(), asyncio.Event()
108
+ try:
109
+ handle = await interaction.submit(core, request)
110
+ with pytest.raises(UserInputRequired) as waiting: await handle.wait()
111
+ identifier = waiting.value.request_id
112
+ await interaction.answer(identifier, revision=1, key="a", answers={"length": "短"})
113
+ original = gateway.stream
114
+ async def blocked(*args, **kwargs):
115
+ entered.set(); await release.wait()
116
+ return await original(*args, **kwargs)
117
+ gateway.stream = blocked
118
+ first = asyncio.create_task(interaction.resume(core, identifier))
119
+ await asyncio.wait_for(entered.wait(), 2)
120
+ with pytest.raises(Exception, match="lease"):
121
+ await interaction.resume(core, identifier)
122
+ release.set()
123
+ resumed = await first
124
+ assert (await resumed.wait()).status.value == "done"
125
+ finally:
126
+ release.set(); await core.close(); storage.close()
127
+