flowstatemcp 2.5.0__py3-none-any.whl

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 (143) hide show
  1. flowstate/__init__.py +34 -0
  2. flowstate/__main__.py +7 -0
  3. flowstate/activity.py +224 -0
  4. flowstate/agent_guide.py +251 -0
  5. flowstate/app_keys.py +141 -0
  6. flowstate/approvals.py +974 -0
  7. flowstate/approve_page.py +565 -0
  8. flowstate/ask.py +107 -0
  9. flowstate/autosession.py +480 -0
  10. flowstate/backup.py +201 -0
  11. flowstate/brief.py +420 -0
  12. flowstate/card_offer.py +208 -0
  13. flowstate/card_taps.py +165 -0
  14. flowstate/card_trust.py +127 -0
  15. flowstate/claims.py +461 -0
  16. flowstate/cleanup.py +619 -0
  17. flowstate/cli.py +728 -0
  18. flowstate/cli_data.py +434 -0
  19. flowstate/cli_more.py +302 -0
  20. flowstate/cli_review.py +459 -0
  21. flowstate/cloudflared_check.py +49 -0
  22. flowstate/conflict_card_ui.py +286 -0
  23. flowstate/conflict_cards.py +1193 -0
  24. flowstate/conflict_reopen.py +320 -0
  25. flowstate/conflicts.py +420 -0
  26. flowstate/connections.py +33 -0
  27. flowstate/database.py +2191 -0
  28. flowstate/dbconn.py +308 -0
  29. flowstate/deletes.py +860 -0
  30. flowstate/embeddings.py +354 -0
  31. flowstate/erase.py +1047 -0
  32. flowstate/extras.py +71 -0
  33. flowstate/git_capture.py +157 -0
  34. flowstate/guard.py +224 -0
  35. flowstate/handoffs.py +168 -0
  36. flowstate/history.py +755 -0
  37. flowstate/history_page.py +276 -0
  38. flowstate/http_app.py +204 -0
  39. flowstate/identity.py +387 -0
  40. flowstate/install_name.py +140 -0
  41. flowstate/ledger.py +272 -0
  42. flowstate/legacy_args.py +65 -0
  43. flowstate/links.py +609 -0
  44. flowstate/markdown_io.py +242 -0
  45. flowstate/meaning.py +398 -0
  46. flowstate/memory_import.py +92 -0
  47. flowstate/migrations/001_auto_sessions.sql +16 -0
  48. flowstate/migrations/002_review_queue.sql +33 -0
  49. flowstate/migrations/003_links.sql +47 -0
  50. flowstate/migrations/004_review_mode.sql +24 -0
  51. flowstate/migrations/005_history.sql +21 -0
  52. flowstate/migrations/006_activity.sql +26 -0
  53. flowstate/migrations/007_meaning_index.sql +16 -0
  54. flowstate/migrations/008_git_capture.sql +12 -0
  55. flowstate/migrations/009_hard_rules.sql +13 -0
  56. flowstate/migrations/010_handoffs.sql +14 -0
  57. flowstate/migrations/011_record_meta.sql +13 -0
  58. flowstate/migrations/012_accountability.sql +71 -0
  59. flowstate/migrations/013_todo_claims.sql +36 -0
  60. flowstate/migrations/014_decision_conflicts.sql +41 -0
  61. flowstate/migrations/015_session_runs.sql +17 -0
  62. flowstate/migrations/016_write_receipts.sql +35 -0
  63. flowstate/migrations/017_run_views.sql +26 -0
  64. flowstate/migrations/018_run_views_upto.sql +4 -0
  65. flowstate/migrations/019_approvals.sql +47 -0
  66. flowstate/migrations/020_source_stamps.sql +10 -0
  67. flowstate/migrations/021_review_links.sql +11 -0
  68. flowstate/migrations/022_review_start_tickets.sql +10 -0
  69. flowstate/migrations/023_conflict_cards.sql +68 -0
  70. flowstate/migrations/024_rule_confirmations.sql +7 -0
  71. flowstate/migrations/025_confirmed_hash.sql +7 -0
  72. flowstate/migrations/__init__.py +149 -0
  73. flowstate/models.py +307 -0
  74. flowstate/names.py +157 -0
  75. flowstate/offsite.py +386 -0
  76. flowstate/offsite_crypto.py +272 -0
  77. flowstate/paths.py +265 -0
  78. flowstate/popup.py +238 -0
  79. flowstate/priority.py +66 -0
  80. flowstate/privatefs.py +476 -0
  81. flowstate/project_history.py +710 -0
  82. flowstate/provenance.py +696 -0
  83. flowstate/receipts.py +377 -0
  84. flowstate/relay/__init__.py +72 -0
  85. flowstate/relay/acme.py +271 -0
  86. flowstate/relay/api.py +164 -0
  87. flowstate/relay/cli.py +344 -0
  88. flowstate/relay/crypto.py +137 -0
  89. flowstate/relay/ct.py +118 -0
  90. flowstate/relay/runner.py +177 -0
  91. flowstate/relay/store.py +191 -0
  92. flowstate/relay/tunnel.py +413 -0
  93. flowstate/release_signers +14 -0
  94. flowstate/remote_auth.py +1219 -0
  95. flowstate/review.py +320 -0
  96. flowstate/review_apply.py +140 -0
  97. flowstate/review_card_ui.py +241 -0
  98. flowstate/review_cards.py +564 -0
  99. flowstate/review_mode.py +274 -0
  100. flowstate/review_page.py +1361 -0
  101. flowstate/review_phone.py +465 -0
  102. flowstate/review_tunnel.py +338 -0
  103. flowstate/routing.py +392 -0
  104. flowstate/rules.py +418 -0
  105. flowstate/safety.py +98 -0
  106. flowstate/saves.py +83 -0
  107. flowstate/scheduler.py +160 -0
  108. flowstate/schema.sql +713 -0
  109. flowstate/search.py +355 -0
  110. flowstate/secret_store.py +271 -0
  111. flowstate/secrets_scan.py +135 -0
  112. flowstate/selfupdate.py +1020 -0
  113. flowstate/server.py +1299 -0
  114. flowstate/session_contents.py +382 -0
  115. flowstate/session_records.py +629 -0
  116. flowstate/site_style.py +46 -0
  117. flowstate/stored.py +158 -0
  118. flowstate/story.py +442 -0
  119. flowstate/surface.py +173 -0
  120. flowstate/tasks.py +231 -0
  121. flowstate/term.py +40 -0
  122. flowstate/tool_labels.py +104 -0
  123. flowstate/tooldefs.py +383 -0
  124. flowstate/tools/__init__.py +118 -0
  125. flowstate/tools/core.py +545 -0
  126. flowstate/tools/files.py +416 -0
  127. flowstate/tools/git_ops.py +1081 -0
  128. flowstate/tools/intelligence.py +376 -0
  129. flowstate/tools/learning.py +282 -0
  130. flowstate/tools/problems.py +159 -0
  131. flowstate/tools/sessions.py +266 -0
  132. flowstate/tools/story.py +48 -0
  133. flowstate/tools/todos.py +79 -0
  134. flowstate/tools/utils.py +71 -0
  135. flowstate/tools/variables.py +345 -0
  136. flowstate/updates.py +482 -0
  137. flowstate/urls.py +7 -0
  138. flowstate/waiting.py +828 -0
  139. flowstate/who.py +302 -0
  140. flowstatemcp-2.5.0.dist-info/METADATA +88 -0
  141. flowstatemcp-2.5.0.dist-info/RECORD +143 -0
  142. flowstatemcp-2.5.0.dist-info/WHEEL +4 -0
  143. flowstatemcp-2.5.0.dist-info/entry_points.txt +3 -0
flowstate/popup.py ADDED
@@ -0,0 +1,238 @@
1
+ """The in-chat popup for user-only approvals (approvals.py): an MCP elicitation form with one
2
+ required checkbox, `approve` (plus an optional note; a project delete also asks for its name).
3
+
4
+ Sent with the installed MCP SDK's server-to-client request (`session.elicit_form`, protocol
5
+ 2025-06-18 / 2025-11-25). The SDK installed with this release (mcp 1.30) has no support for
6
+ the 2026-07-28 style, so that one isn't offered. The wait (at most approvals.POPUP_SECONDS)
7
+ runs after the tool's own work has committed, outside the call's time limit and holding no
8
+ database lock; only accept with approve=true approves. Anything else leaves the item queued.
9
+
10
+ No box at all (no_box) for requests that came through the relay or the public listener, or to
11
+ the LAN listener from another computer. On stdio the popup list is checked against the name the
12
+ app sends (its own say-so, from an app the user started on this computer); a LAN app on this
13
+ computer is checked by its key's or token's own name on the list's sign-in part, never by the
14
+ name it sends, which it could set to "claude-code" (task 57, H-1; as card_trust.py for cards). And an answer that comes back faster than a person could
15
+ read the box (HUMAN_SECONDS) means the box was never shown: it counts as no answer, is not
16
+ logged as the user's decision, and FlowState falls back to the plain line / list.
17
+ """
18
+
19
+ import asyncio
20
+ import logging
21
+ import time
22
+ from typing import Optional
23
+
24
+ from . import approvals
25
+
26
+ log = logging.getLogger("flowstate.popup")
27
+
28
+ APPROVE_FIELD = {"type": "boolean", "title": "Approve",
29
+ "description": "Tick to approve. Leave it unticked, decline or close to say no."}
30
+ NOTE_FIELD = {"type": "string", "title": "Note (optional)", "maxLength": 300}
31
+ HUMAN_SECONDS = 1.0 # an answer sooner than this came from software: the box wasn't shown
32
+ _clock = time.monotonic
33
+
34
+
35
+ def schema(project_name: Optional[str] = None) -> dict:
36
+ props = {"approve": dict(APPROVE_FIELD), "note": dict(NOTE_FIELD)}
37
+ required = ["approve"]
38
+ if project_name:
39
+ props["confirm_name"] = {"type": "string", "title": "Type the project's exact name",
40
+ "description": f"Deleting a whole project: type {project_name}"}
41
+ required.append("confirm_name")
42
+ return {"type": "object", "properties": props, "required": required}
43
+
44
+
45
+ def declared(session) -> bool:
46
+ """Did this connection declare form elicitation? (An empty `elicitation: {}` means form.)"""
47
+ try:
48
+ caps = session.client_params.capabilities.elicitation
49
+ except AttributeError:
50
+ return False
51
+ if caps is None:
52
+ return False
53
+ return getattr(caps, "form", None) is not None or getattr(caps, "url", None) is None
54
+
55
+
56
+ def _scope() -> Optional[dict]:
57
+ """The ASGI scope of the HTTP request FlowState is answering; None for stdio."""
58
+ from . import server as S
59
+ try:
60
+ req = S.server.request_context.request
61
+ except LookupError:
62
+ return None
63
+ return None if req is None else (getattr(req, "scope", None) or {})
64
+
65
+
66
+ def listener() -> str:
67
+ """How this request reached FlowState: stdio, or the HTTP listener remote_auth.Gate
68
+ marked it with (lan / public / relay; "unknown" if unmarked)."""
69
+ from .remote_auth import LISTENER_KEY
70
+ scope = _scope()
71
+ return "stdio" if scope is None else scope.get(LISTENER_KEY) or "unknown"
72
+
73
+
74
+ def on_this_computer() -> bool:
75
+ """Is the app on the computer where FlowState runs? stdio, or the LAN listener with a
76
+ loopback socket peer (remote_auth.Gate's LOCAL_KEY). Relay, public, other peers and
77
+ unmarked requests are not. Decides whether the 127.0.0.1 review link is offered."""
78
+ from .remote_auth import LOCAL_KEY
79
+ if listener() == "stdio":
80
+ return True
81
+ return listener() == "lan" and (_scope() or {}).get(LOCAL_KEY) is True
82
+
83
+
84
+ def no_box(session, client: str, db_path) -> Optional[str]:
85
+ """Why this connection gets no Approve / Reject box; None if it may get one."""
86
+ via = listener()
87
+ if via == "relay":
88
+ return ("This request came through the relay, where the app's name is only its own "
89
+ "say-so, so FlowState shows no Approve / Reject boxes here.")
90
+ if via not in ("stdio", "lan"):
91
+ return ("This request came from outside this computer, so FlowState shows no "
92
+ "Approve / Reject boxes here.")
93
+ if via == "lan" and not on_this_computer():
94
+ return ("This request came from another computer, so FlowState shows no "
95
+ "Approve / Reject boxes here.")
96
+ if session is None:
97
+ return "This app can't show FlowState's Approve / Reject boxes."
98
+ if via == "stdio":
99
+ ok = approvals.popup_allowed(db_path, client, declared(session))
100
+ else: # the LAN listener, from this computer: the sign-in's own name, never the sent one
101
+ from . import card_trust
102
+ who = card_trust.caller()
103
+ ok = who is not None and who.credential is not None and \
104
+ approvals.popup_allowed_credential(db_path, who.credential, declared(session), who.source)
105
+ if not ok:
106
+ return "This app can't show FlowState's Approve / Reject boxes."
107
+ return None
108
+
109
+
110
+ def decider_label(path: str, client: str) -> str:
111
+ """The decider label of a popup / walk answer: "popup (claude-code)", or with the sign-in
112
+ over the LAN, "chat (claude-code, signed in as Laptop key)"."""
113
+ from . import card_trust
114
+ who = card_trust.caller()
115
+ if who is not None:
116
+ return who.label(path)
117
+ return f"{path} ({client or 'unknown'})"[:card_trust.LABEL_MAX]
118
+
119
+
120
+ async def elicit(session, message: str, form: dict, related_request_id=None,
121
+ timeout: Optional[float] = None) -> tuple[str, dict]:
122
+ """One box: (action, content). action accept / decline / cancel, timed_out, failed, or
123
+ not_shown (answered in under HUMAN_SECONDS: no person saw it)."""
124
+ t0 = _clock()
125
+ try:
126
+ res = await asyncio.wait_for(session.elicit_form(message, form, related_request_id),
127
+ approvals.POPUP_SECONDS if timeout is None else timeout)
128
+ except asyncio.TimeoutError:
129
+ return "timed_out", {}
130
+ except Exception as e: # noqa: BLE001 - a broken box is a "no", never an approval
131
+ log.warning("box failed: %s", e)
132
+ return "failed", {}
133
+ if _clock() - t0 < HUMAN_SECONDS:
134
+ log.warning("box answered in under %ss (%s): treated as not shown", HUMAN_SECONDS, res.action)
135
+ return "not_shown", {}
136
+ return res.action, res.content if isinstance(res.content, dict) else {}
137
+
138
+
139
+ async def ask(session, message: str, form: dict, related_request_id=None,
140
+ timeout: Optional[float] = None) -> tuple[str, dict]:
141
+ """(outcome, content): outcome approved / declined / cancelled / timed_out / failed /
142
+ not_shown."""
143
+ action, content = await elicit(session, message, form, related_request_id, timeout)
144
+ if action in ("timed_out", "failed", "not_shown"):
145
+ return action, {}
146
+ if action == "decline":
147
+ return "declined", {}
148
+ if action != "accept":
149
+ return "cancelled", {}
150
+ if content.get("approve") is not True: # required, and exactly true
151
+ return "declined", content
152
+ for key in form.get("required") or ():
153
+ if content.get(key) in (None, ""):
154
+ return "declined", content
155
+ return "approved", content
156
+
157
+
158
+ _SAID = {"declined": "the user said no", "cancelled": "the user closed it",
159
+ "timed_out": "no answer within 2 minutes", "failed": "the app couldn't show it",
160
+ "wrong_name": "the project name didn't match"}
161
+
162
+
163
+ async def resolve(result: dict, session, client: str, db_path, request_id, decide,
164
+ log_outcome) -> dict:
165
+ """Turn a tool answer that carries `_ask_user` into the final answer: show the popup when
166
+ this app may get one, else pass on the one-line fallback (phone link or terminal).
167
+ `decide(item_id, content)` (async) carries out an approval; `log_outcome(item_id, outcome)`
168
+ (async) records a "no"."""
169
+ ask_user = result.pop("_ask_user")
170
+ item_id = ask_user["item_id"]
171
+ if no_box(session, client, db_path):
172
+ result["next"] = ask_user["line"]
173
+ return result
174
+ outcome, content = await ask(session, ask_user["message"], schema(ask_user.get("project_name")),
175
+ request_id)
176
+ if outcome == "not_shown": # no person saw it: not the user's answer, nothing logged
177
+ result["next"] = ("No popup was shown (this app answered it at once, faster than a "
178
+ "person could); nothing changed. " + ask_user["line"])
179
+ return result
180
+ if outcome == "approved" and ask_user.get("project_name") \
181
+ and content.get("confirm_name") != ask_user["project_name"]:
182
+ outcome = "wrong_name"
183
+ if outcome != "approved":
184
+ await log_outcome(item_id, outcome)
185
+ result["next"] = (f"Not approved in the popup ({_SAID[outcome]}); nothing changed and item "
186
+ f"#{item_id} stays queued.")
187
+ return result
188
+ done = await decide(item_id, content)
189
+ if isinstance(done, dict) and "error" in done:
190
+ result["next"] = f"Approved in the popup, but it failed: {done.get('message') or done['error']}"
191
+ return result
192
+ out = {k: v for k, v in result.items() if k in ("receipt",)}
193
+ out.update(done if isinstance(done, dict) else {"result": done})
194
+ out["approved_in"] = "popup"
195
+ return out
196
+
197
+
198
+ async def ask_user(result: dict, session_obj, client: str) -> dict:
199
+ """server.py's hook: the popup for a user-only item, else the one-line phone / terminal step;
200
+ or the review walk the user asked for (waiting.walk)."""
201
+ from . import review
202
+ from . import server as S
203
+ if "_walk" in result:
204
+ from .waiting import walk
205
+ return await walk(result, session_obj, client)
206
+ try:
207
+ rid = S.server.request_context.request_id
208
+ except LookupError:
209
+ rid = None
210
+ from . import card_trust
211
+ label, where = decider_label("popup", client), card_trust.shown(client)
212
+
213
+ async def decide(item_id: int, content: dict):
214
+ args = {"item_id": item_id, "confirm_name": content.get("confirm_name"),
215
+ "user_request": f"The user approved this in the popup in {where}."}
216
+ return await asyncio.wait_for(asyncio.to_thread(as_user, "review_approve", args, label),
217
+ S.call_timeout())
218
+
219
+ async def log_outcome(item_id: int, outcome: str):
220
+ item = await asyncio.to_thread(S._safe_call, review.get_item, S.backend.db_path, item_id)
221
+ if item:
222
+ await asyncio.to_thread(S._safe_call, approvals.log_decision, S.backend.db_path, item,
223
+ "popup", label, outcome)
224
+
225
+ return await resolve(result, session_obj, client, S.backend.db_path, rid, decide, log_outcome)
226
+
227
+
228
+ def as_user(name: str, args: dict, label: str):
229
+ """A decision the user made themselves (popup, phone page): no agent identity, so the
230
+ user-only check lets it through; `label` says how (approvals.path_of)."""
231
+ from . import identity, review
232
+ from . import server as S
233
+ tok = identity.set_current(None)
234
+ try:
235
+ item = review.get_item(S.backend.db_path, int(args["item_id"]))
236
+ return S._review_decide(name, item["project_id"] if item else None, args, label)
237
+ finally:
238
+ identity.reset(tok)
flowstate/priority.py ADDED
@@ -0,0 +1,66 @@
1
+ """Todo priority levels (v2 Phase D, E1): critical / urgent / normal / low.
2
+
3
+ The database keeps the older names (its CHECK constraint allows low/medium/high/critical and
4
+ the v1 server reads them): urgent is stored as high, normal as medium. Every input accepts
5
+ both names; everything FlowState shows uses the new ones.
6
+ """
7
+
8
+ from typing import Optional
9
+
10
+ LEVELS = ("critical", "urgent", "normal", "low") # most urgent first
11
+ _STORE = {"critical": "critical", "urgent": "high", "normal": "medium", "low": "low",
12
+ "high": "high", "medium": "medium"}
13
+ _LABEL = {"critical": "critical", "high": "urgent", "medium": "normal", "low": "low"}
14
+ RANK = {"critical": 0, "high": 1, "medium": 2, "low": 3} # by stored value
15
+ ACCEPTED = ("critical", "urgent", "high", "normal", "medium", "low")
16
+ DEFAULT = "medium"
17
+
18
+ # SQL ordering by stored value (most urgent first); `col` is the column expression.
19
+ def order_sql(col: str = "priority") -> str:
20
+ return (f"CASE {col} WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 "
21
+ f"WHEN 'low' THEN 3 ELSE 2 END")
22
+
23
+
24
+ class PriorityError(ValueError):
25
+ pass
26
+
27
+
28
+ def store(value: Optional[str], default: Optional[str] = DEFAULT) -> Optional[str]:
29
+ """The value to save (old names). None/'' -> default. Unknown -> PriorityError."""
30
+ if value is None or str(value).strip() == "":
31
+ return default
32
+ v = str(value).strip().lower()
33
+ if v not in _STORE:
34
+ raise PriorityError(f"priority must be one of {', '.join(LEVELS)} "
35
+ f"(older names high and medium also work); got {value!r}.")
36
+ return _STORE[v]
37
+
38
+
39
+ def label(stored: Optional[str]) -> str:
40
+ """The name to show for a stored value (unknown or empty -> normal)."""
41
+ return _LABEL.get((stored or "").strip().lower(), "normal")
42
+
43
+
44
+ def show(value):
45
+ """An answer with every to-do "priority" shown by its name (high -> urgent, medium ->
46
+ normal), however deep. Only todos have a priority; problems' severity is left alone."""
47
+ if isinstance(value, dict):
48
+ return {k: (_LABEL.get(v, v) if k == "priority" and isinstance(v, str) else show(v))
49
+ for k, v in value.items()}
50
+ if isinstance(value, list):
51
+ return [show(v) for v in value]
52
+ return value
53
+
54
+
55
+ def rank(stored: Optional[str]) -> int:
56
+ return RANK.get((stored or "").strip().lower(), 2)
57
+
58
+
59
+ def at_least(level: str) -> list[str]:
60
+ """Stored values at this level or more urgent (for min_priority filters)."""
61
+ top = rank(store(level))
62
+ return [v for v, r in RANK.items() if r <= top]
63
+
64
+
65
+ def error_payload(e: Exception) -> dict:
66
+ return {"error": "bad_priority", "message": str(e)}