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
@@ -0,0 +1,208 @@
1
+ """The one-tap offer "Allow tap cards in <app>?" for an app on a network sign-in (task 65b).
2
+
3
+ An app that signed in over the network (an OAuth app, a key or a token, card_trust.py) and
4
+ says it draws MCP Apps cards gets them only once its sign-in's own name is on the user's card
5
+ sign-in list (approvals.card_allowed_credential, task 55). The first time such an app would
6
+ be shown a card and isn't on the list, it gets the text card as before, and FlowState queues
7
+ one review item of kind `card_offer` in that project: "Allow tap cards in <app>?", with the
8
+ app and the sign-in it used (card_trust shown()).
9
+
10
+ - Once per sign-in: its name goes on the "already offered" list (approval_settings
11
+ `card_offered_add`) when the offer is queued, so there is never a second one while it
12
+ waits, after the user's No, or after the user takes the cards away again (approvals.
13
+ change_signins puts a removed sign-in there too). The user offers again from the review
14
+ page's Settings or with `flowstate approvals cards offer-again NAME`; `flowstate
15
+ approvals cards offers off` stops new offers altogether.
16
+ - The user's alone, and only on the review page (this computer's, or the tunnel review
17
+ page) or the phone review page: refusal() turns away every other way, every AI tool
18
+ (chat approvals on or off), the chat walk, a popup, a card tap and the terminal. A card
19
+ has no buttons for it (approvals.user_only).
20
+ - Allow puts the sign-in's own name (stored in the item when FlowState queued it, never
21
+ the name the app sends) on the card sign-in list, the same list `flowstate approvals
22
+ cards add --sign-in` and Settings change; the decision goes to approval_log and the
23
+ change to the settings log like every other settings change. Taking it away again is the
24
+ existing remove (Settings, `approvals cards remove --sign-in NAME`).
25
+ """
26
+
27
+ import json
28
+ import re
29
+ import sqlite3
30
+ from pathlib import Path
31
+ from typing import Optional
32
+
33
+ from . import approvals
34
+
35
+ KIND = "card_offer"
36
+ OFFERED = "card_offered" # approval_settings card_offered_add: sign-ins already offered
37
+ OFFERS = "card_offers" # approval_settings: "off" = no new offers
38
+ # the only deciders of an offer: the review page's, the tunnel page's and the phone pages' own
39
+ # labels (review_page.CLIENT, review_tunnel.CLIENT, approve_page / review_phone "phone")
40
+ DECIDERS = ("review-page", "tunnel page", "phone")
41
+ SETTING_WORDS = "allowed on the offer in the review queue"
42
+
43
+ REFUSED = ("Only the user answers \"Allow tap cards in this app?\", and only on their review "
44
+ "page (on the computer where FlowState runs: the FlowState review shortcut or "
45
+ "`flowstate review-page`) or their phone review page. Nothing was decided on review "
46
+ "item #{id}; don't try again. Tell the user once, if they want cards in this app.")
47
+ QUEUED = ("This app can draw FlowState's in-chat review cards, but the user hasn't allowed "
48
+ "them for it, so the text is the card here. FlowState has asked the user once, on "
49
+ "their review page and phone review page: \"Allow tap cards in {app}?\" (review item "
50
+ "#{id}). Only they answer it; tell them once if they want to tap Approve / Reject in "
51
+ "this chat, and don't decide it for them.")
52
+
53
+
54
+ def _clean(name) -> str:
55
+ return approvals.clean_client_name(name)
56
+
57
+
58
+ def _base(name: str, source: Optional[str]) -> str:
59
+ """An OAuth app that registered again is "Claude (2)": the same place as "Claude" (as on
60
+ the sign-in list, approvals._signin_listed)."""
61
+ m = re.fullmatch(r"(.+) \((\d{1,3})\)", name)
62
+ return m.group(1) if source == "oauth_client" and m else name
63
+
64
+
65
+ def offers_on(db_path: Optional[Path]) -> bool:
66
+ if db_path is None:
67
+ return False
68
+ conn = approvals._conn(db_path)
69
+ try:
70
+ return not approvals.available(conn) or approvals._get(conn, OFFERS) != "off"
71
+ except sqlite3.Error:
72
+ return False
73
+ finally:
74
+ conn.close()
75
+
76
+
77
+ def offered(db_path: Optional[Path]) -> set:
78
+ """The sign-in names already offered (lower case): no new offer for these."""
79
+ return approvals._listed(db_path, (), OFFERED)
80
+
81
+
82
+ def was_offered(db_path: Optional[Path], credential: Optional[str],
83
+ source: Optional[str] = None) -> bool:
84
+ name = _clean(credential)
85
+ done = offered(db_path)
86
+ return name in done or _base(name, source) in done
87
+
88
+
89
+ def mark_offered(db_path: Path, name: str, offered_: bool, who: str = "command-line") -> set:
90
+ """Put a sign-in on the "already offered" list, or take it off (offer again)."""
91
+ return approvals._change_list(db_path, (), OFFERED, name, offered_, who)
92
+
93
+
94
+ def set_offers(db_path: Path, on: bool, who: str = "command-line") -> None:
95
+ approvals.set_value(db_path, OFFERS, None if on else "off", who)
96
+
97
+
98
+ def _project_id(conn, project) -> Optional[int]:
99
+ if project is None:
100
+ return None
101
+ if isinstance(project, int):
102
+ row = conn.execute("SELECT id FROM projects WHERE id = ?", (project,)).fetchone()
103
+ else:
104
+ row = conn.execute("SELECT id FROM projects WHERE name = ? COLLATE NOCASE",
105
+ (str(project),)).fetchone()
106
+ return row[0] if row else None
107
+
108
+
109
+ def pending_for(conn, name: str) -> Optional[int]:
110
+ row = conn.execute("SELECT id, payload FROM review_items WHERE kind = ? AND status = 'pending' "
111
+ "ORDER BY id", (KIND,)).fetchall()
112
+ for r in row:
113
+ try:
114
+ if _clean(json.loads(r[1] or "{}").get("credential")) == name:
115
+ return r[0]
116
+ except ValueError:
117
+ continue
118
+ return None
119
+
120
+
121
+ def offer(db_path: Optional[Path], project) -> Optional[dict]:
122
+ """Called wherever a card would be shown (the cards' pointers and brief lines). For an app
123
+ on a network sign-in that says it draws cards but isn't on the card sign-in list: queue the
124
+ offer once, and say so ({"item_id", "app", "queued"}). None for every other caller, when
125
+ offers are off, or when this sign-in was offered before and nothing waits."""
126
+ from . import card_trust, conflict_cards, review
127
+ if db_path is None or not conflict_cards.ui_declared() or conflict_cards.client_has_ui():
128
+ return None
129
+ who = card_trust.caller()
130
+ if who is None or who.credential is None: # stdio, the shared token: never an offer
131
+ return None
132
+ name = _clean(who.credential)
133
+ if not name or not offers_on(db_path):
134
+ return None
135
+ shown = " ".join(who.shown().split())[:160]
136
+ conn = approvals._conn(db_path)
137
+ try:
138
+ if not approvals.available(conn) or not review.available(conn):
139
+ return None
140
+ conn.execute("BEGIN IMMEDIATE") # one offer, whichever connection gets here first
141
+ waiting = pending_for(conn, name)
142
+ if waiting is not None:
143
+ conn.commit()
144
+ return {"item_id": waiting, "app": shown, "queued": False}
145
+ done = json.loads(approvals._get(conn, f"{OFFERED}_add") or "[]")
146
+ if name in done or _base(name, who.source) in done:
147
+ conn.commit()
148
+ return None
149
+ pid = _project_id(conn, project)
150
+ if pid is None:
151
+ conn.commit()
152
+ return None
153
+ app = " ".join(str(who.app or "an app").split())[:80]
154
+ item = review.add_item(
155
+ db_path, pid, KIND, f"Allow tap cards in {shown}?",
156
+ f"{app} can show FlowState's review cards in its chat, with Approve / Reject / Keep "
157
+ f"buttons. Allow: a tap on them counts as your own decision, for this sign-in only "
158
+ f"(\"{who.credential}\"). No: it keeps getting the text and your review link, and "
159
+ f"isn't asked again. You can change this any time in Settings (\"Apps that may show "
160
+ f"review cards\").",
161
+ {"credential": who.credential, "source": who.source, "app": app, "shown": shown,
162
+ "user_only": True}, who.sent, conn=conn)
163
+ approvals._put(conn, f"{OFFERED}_add", json.dumps(sorted(set(done) | {name})), "offer")
164
+ conn.commit()
165
+ return {"item_id": item, "app": shown, "queued": True}
166
+ except sqlite3.Error:
167
+ conn.rollback()
168
+ return None
169
+ finally:
170
+ conn.close()
171
+
172
+
173
+ def note(off: dict) -> str:
174
+ return QUEUED.format(app=off["app"], id=off["item_id"])
175
+
176
+
177
+ def refusal(item: dict, client: str, agent: bool) -> Optional[dict]:
178
+ """None when this decider may answer a waiting offer: the user on the review page, the
179
+ tunnel review page or the phone page. Everything else is refused, AI tools included."""
180
+ if item.get("kind") != KIND or item.get("status") != "pending":
181
+ return None
182
+ if not agent and str(client or "").lower().startswith(DECIDERS):
183
+ return None
184
+ return {"error": "user_only", "message": REFUSED.format(id=item["id"]), "item_id": item["id"],
185
+ "kind": KIND, "status": "waiting for the user"}
186
+
187
+
188
+ def apply(db_path: Path, item: dict, client: str) -> tuple:
189
+ """Allow: the sign-in FlowState stored with the offer goes on the card sign-in list."""
190
+ p = json.loads(item.get("payload") or "{}")
191
+ name = _clean(p.get("credential"))
192
+ if not name:
193
+ from .review import ReviewError
194
+ raise ReviewError("bad_offer", "This offer names no sign-in; nothing changed.")
195
+ before = approvals.signins(db_path, "card")
196
+ approvals.change_signins(db_path, "card", name, True, client)
197
+ approvals.log_setting(db_path, "card_signins", ", ".join(sorted(before)), f"added {name}",
198
+ client, SETTING_WORDS)
199
+ return "approval_settings", None
200
+
201
+
202
+ def describe(item: dict) -> str:
203
+ try:
204
+ p = json.loads(item.get("payload") or "{}")
205
+ except ValueError:
206
+ p = {}
207
+ return (f"let {p.get('shown') or p.get('app') or 'an app'} show tap cards in its chat "
208
+ f"(its taps on Approve / Reject then count as yours)")
flowstate/card_taps.py ADDED
@@ -0,0 +1,165 @@
1
+ """One-use tap codes for the in-chat cards (2.4.4).
2
+
3
+ An app that says it shows MCP Apps cards gets the app-only resolve tools, and the model must
4
+ never be able to use them for the user. So a card's buttons only work with a code that only
5
+ the card's page receives:
6
+
7
+ - show_review_card / show_conflict_card (and a record tap's answer, which redraws the card)
8
+ make one code per card that has buttons. The codes go in the tool result's `_meta`
9
+ (META_KEY), which MCP Apps hosts pass to the card's page and keep out of the model's
10
+ context; never in the text, never in structuredContent;
11
+ - the card sends its code back with the tap (`tap`); resolve_review_card /
12
+ resolve_conflict_card refuse a tap without a valid one (not_a_card_tap);
13
+ - a code is bound to the item, the kind of card and the caller that was shown it (on
14
+ stdio its client name; over the network its key's / token's / OAuth app's own name,
15
+ card_trust.py), and expires after TTL seconds. Only a hash is kept, in this process's
16
+ memory;
17
+ - a tap only reserves its code (redeem); the code is used up when the tap is saved, and
18
+ given back when the tap fails or is refused afterwards (settle), so a failed or timed-out
19
+ tap doesn't leave a card whose buttons refuse everything. A reserved code can't be used
20
+ by a second tap at the same time (use-once stays safe under races);
21
+ - showing a card again replaces only that card's own older codes (PER_CARD at most, the
22
+ oldest go), never other cards' live ones; MAX_CODES only bounds memory.
23
+
24
+ Honest limit: a program that pretends to be a card host (it connects on stdio with a name on
25
+ the card list, or with a key / token the user put on it, and reads `_meta` itself) gets the
26
+ codes too; the card list (approvals.card_clients) is what keeps other apps out, as the popup
27
+ list does for popups.
28
+ """
29
+
30
+ import contextvars
31
+ import hashlib
32
+ import hmac
33
+ import secrets
34
+ import threading
35
+ import time
36
+ from typing import Optional
37
+
38
+ META_KEY = "flowstate/taps"
39
+ TTL = 15 * 60 # seconds: a card left open longer asks to be shown again
40
+ PER_CARD = 3 # live codes per card (item, kind, caller); showing it again drops the oldest
41
+ MAX_CODES = 5000 # kept at once in all (memory bound); the oldest idle ones go first
42
+ BUSY = "busy"
43
+ _codes: dict = {} # sha256(code) -> [item_id, card, client, expires, reserved]
44
+ _lock = threading.Lock()
45
+ _clock = time.monotonic
46
+ _held: contextvars.ContextVar = contextvars.ContextVar("flowstate_tap_held", default=None)
47
+
48
+
49
+ def _hash(code: str) -> str:
50
+ return hashlib.sha256(code.encode()).hexdigest()
51
+
52
+
53
+ def _client(name: Optional[str]) -> str:
54
+ return " ".join(str(name or "").split()).lower()
55
+
56
+
57
+ def _drop_oldest(keys: list) -> None:
58
+ for k in keys:
59
+ if not _codes[k][4]: # a code a tap is using right now stays
60
+ del _codes[k]
61
+ return
62
+
63
+
64
+ def mint(item_id: int, card: str, client: Optional[str]) -> str:
65
+ """A fresh code for one card ("review" or "conflict") shown to `client` (card_trust.key)."""
66
+ code = secrets.token_urlsafe(24)
67
+ now = _clock()
68
+ who = (int(item_id), card, _client(client))
69
+ with _lock:
70
+ for k in [k for k, v in _codes.items() if v[3] <= now and not v[4]]:
71
+ del _codes[k]
72
+ same = [k for k, v in _codes.items() if tuple(v[:3]) == who and not v[4]]
73
+ while len(same) >= PER_CARD:
74
+ del _codes[same.pop(0)]
75
+ while len(_codes) >= MAX_CODES and any(not v[4] for v in _codes.values()):
76
+ _drop_oldest(list(_codes))
77
+ _codes[_hash(code)] = [*who, now + TTL, False]
78
+ return code
79
+
80
+
81
+ def redeem(code, item_id, card: str, client: Optional[str]):
82
+ """Reserve `code` for this tap: True for a live code made for this item, card and caller
83
+ (settle then uses it up or gives it back), BUSY while another tap holds it, else False."""
84
+ if not isinstance(code, str) or not code or len(code) > 200:
85
+ return False
86
+ try:
87
+ item_id = int(item_id)
88
+ except (TypeError, ValueError):
89
+ return False
90
+ h = _hash(code)
91
+ want = (item_id, card, _client(client))
92
+ with _lock:
93
+ got = _codes.get(h)
94
+ if got is None:
95
+ return False
96
+ if got[3] <= _clock() and not got[4]:
97
+ del _codes[h]
98
+ return False
99
+ if not hmac.compare_digest(repr(tuple(got[:3])), repr(want)):
100
+ return False
101
+ if got[4]:
102
+ return BUSY
103
+ got[4] = True
104
+ _held.set(h)
105
+ return True
106
+
107
+
108
+ def settle(result, ok: Optional[bool] = None, db_path=None):
109
+ """After a tap: the code it reserved (if any) is used up when the tap was saved (`ok`, by
110
+ default: the answer is not an error), else given back for the next tap. Returns `result`.
111
+ Inside a save of `db_path` (saves.py: the call is one commit) that waits for the save's
112
+ end: a save that is rolled back gives the code back (task 56 Low: the tap failed, the
113
+ card must still work)."""
114
+ h = _held.get()
115
+ if h is None:
116
+ return result
117
+ _held.set(None)
118
+ if ok is None:
119
+ ok = not (isinstance(result, dict) and "error" in result)
120
+ if db_path is not None and ok:
121
+ from . import dbconn
122
+ dbconn.after(db_path, lambda committed: _finish(h, committed))
123
+ else:
124
+ _finish(h, ok)
125
+ return result
126
+
127
+
128
+ def _finish(h: str, used: bool) -> None:
129
+ with _lock:
130
+ got = _codes.get(h)
131
+ if got is not None:
132
+ if used:
133
+ del _codes[h]
134
+ else:
135
+ got[4] = False
136
+
137
+
138
+ def resolve(fn, db_path, *a):
139
+ """Run a card's tap `fn(db_path, *a)` and settle its code, also when it raises, and only
140
+ once its save has committed."""
141
+ _held.set(None)
142
+ try:
143
+ result = fn(db_path, *a)
144
+ except BaseException:
145
+ settle(None, ok=False)
146
+ raise
147
+ return settle(result, db_path=db_path)
148
+
149
+
150
+ def for_cards(item_ids, card: str, client: Optional[str]) -> dict:
151
+ """{str(item_id): code} for the cards that have buttons."""
152
+ return {str(int(i)): mint(i, card, client) for i in item_ids}
153
+
154
+
155
+ REFUSED = ("This card has expired, or this tap didn't come from a card FlowState showed in "
156
+ "this app. Nothing was decided. Ask the AI to show the card again, or decide on the "
157
+ "review page or your phone.")
158
+ IN_PROGRESS = ("This card's last tap is still being saved. Nothing new was decided; wait a "
159
+ "moment and look again.")
160
+
161
+
162
+ def clear() -> None:
163
+ """Tests: forget every code."""
164
+ with _lock:
165
+ _codes.clear()
@@ -0,0 +1,127 @@
1
+ """Who may use the in-chat cards, and how a card tap is recorded (task 55, re-audit N-F1).
2
+
3
+ The card list (approvals.card_clients) says which apps' card taps count as the user's. What is
4
+ checked against it depends on how the app connected:
5
+
6
+ - stdio (the app that started this FlowState process, e.g. Claude Desktop): the MCP client
7
+ name the app sends. That name is the app's own say-so; an app the user runs on this
8
+ computer could lie about it. Accepted limit, as for popups (see conflict_cards.py).
9
+ - over the network (a LAN key, a remote token on the LAN, tunnel or relay, an OAuth app):
10
+ the key's / token's / OAuth app's own name (identity.Identity.credential), never the name
11
+ the app sends, which it can set to anything ("claude-ai"). Only a name the user added
12
+ themselves counts (`flowstate approvals cards add NAME` or the review page's Settings),
13
+ not the built-in default: an OAuth app picks its own name when it registers.
14
+ - the shared LAN token, or an HTTP call without a sign-in: no cards. The shared token is one
15
+ secret for every app, so it can't say which app taps.
16
+
17
+ The tap codes (card_taps.py) are bound to the same caller (key()), and a tap is recorded with
18
+ label(): "card (<app>)", plus "signed in as <credential>" over the network, everywhere a card
19
+ decision is written (decided_by, approval_log, a session summary's per-record decisions).
20
+ """
21
+
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+ from typing import Optional
25
+
26
+ NETWORK_SOURCES = ("app_key", "oauth_client", "remote_token")
27
+ LABEL_MAX = 80
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class CardCaller:
32
+ sent: str # the MCP client name the app sent (stdio: what is checked)
33
+ app: str # the app's name as FlowState records it (identity.py)
34
+ credential: Optional[str] # the key's / token's / OAuth app's own name; None on stdio
35
+ source: str # "stdio", or the identity source of the sign-in
36
+
37
+ def key(self) -> str:
38
+ """Who a tap code is bound to (card_taps.py lower-cases it)."""
39
+ if self.credential is None:
40
+ return self.sent
41
+ return f"{self.source}|{self.credential}"
42
+
43
+ def shown(self) -> str:
44
+ """The app, and the sign-in it used: "claude-ai (signed in as Laptop key)"."""
45
+ if self.credential is None:
46
+ return self.app
47
+ return f"{self.app} (signed in as {self.credential})"
48
+
49
+ def label(self, path: str = "card") -> str:
50
+ """How a tap (or a popup / walk answer: path "popup" / "chat") is recorded as the
51
+ decider: "card (claude-ai)" / "card (claude-ai, signed in as Laptop key)", the
52
+ sign-in's name kept whole."""
53
+ if self.credential is None:
54
+ return f"{path} ({self.app})"[:LABEL_MAX]
55
+ tail = f", signed in as {self.credential})"
56
+ room = max(8, LABEL_MAX - len(path) - 2 - len(tail))
57
+ return f"{path} ({self.app[:room]}{tail}"[:LABEL_MAX]
58
+
59
+
60
+ def caller() -> Optional[CardCaller]:
61
+ """This connection as the cards see it; None outside a request, and for the shared LAN
62
+ token or an HTTP call without a sign-in (no cards for those)."""
63
+ from . import identity
64
+ from .server import _client_name, _identity, server
65
+ try:
66
+ req = server.request_context.request
67
+ except LookupError:
68
+ return None
69
+ sent = _client_name()
70
+ if req is None: # stdio
71
+ return CardCaller(sent, identity._app_name(sent) or "unknown", None, "stdio")
72
+ ident = _identity(sent, {})
73
+ if ident.identity_source not in NETWORK_SOURCES or not ident.credential:
74
+ return None
75
+ return CardCaller(sent, ident.app, ident.credential, ident.identity_source)
76
+
77
+
78
+ def allowed(db_path: Optional[Path], who: Optional[CardCaller]) -> bool:
79
+ """May this caller get the cards (and their app-only tap tools)? See the module text."""
80
+ from . import approvals
81
+ if who is None:
82
+ return False
83
+ if who.credential is None:
84
+ return approvals.card_allowed(db_path, who.sent)
85
+ return approvals.card_allowed_credential(db_path, who.credential, who.source)
86
+
87
+
88
+ def key(fallback: Optional[str]) -> str:
89
+ who = caller()
90
+ return who.key() if who is not None else str(fallback or "")
91
+
92
+
93
+ def shown(fallback: Optional[str]) -> str:
94
+ who = caller()
95
+ return who.shown() if who is not None else str(fallback or "an app")
96
+
97
+
98
+ def label(fallback: Optional[str]) -> str:
99
+ """The decider label of a card tap; outside a request (FlowState's own calls, tests)
100
+ "card (<fallback>)"."""
101
+ who = caller()
102
+ if who is not None:
103
+ return who.label()
104
+ return f"card ({fallback or 'unknown'})"[:LABEL_MAX]
105
+
106
+
107
+ def defused(result, card: bool = True):
108
+ """A card tool's answer as the model may see it (re-audit N-F8). Both model-visible parts,
109
+ the text and the card's structuredContent (`_ui["structured"]`), are defused and marked
110
+ like every other answer (stored.py, audit D6); the card pages write every text with
111
+ textContent, so a defused character only shows as a slightly changed one. Only the tap
112
+ codes (`_ui["taps"]`, sent in _meta, which the model doesn't get) stay as they are."""
113
+ from . import stored
114
+ ui = result.pop("_ui", None) if isinstance(result, dict) else None
115
+ result = stored.defuse_all(stored.mark("", result))
116
+ if card and isinstance(result, dict):
117
+ if "error" not in result and "records_are" not in result:
118
+ result = {"records_are": stored.NOTE, **result}
119
+ if isinstance(ui, dict):
120
+ ui = dict(ui)
121
+ if isinstance(ui.get("structured"), dict):
122
+ ui["structured"] = {"records_are": stored.NOTE,
123
+ **stored.defuse_all(ui["structured"])}
124
+ elif ui.get("structured") is not None:
125
+ ui["structured"] = stored.defuse_all(ui["structured"])
126
+ result["_ui"] = ui
127
+ return result