-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
351 lines (289 loc) · 12.9 KB
/
Copy pathapi_server.py
File metadata and controls
351 lines (289 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""
FastAPI hub for the Chrome extension (thin client).
All intelligence runs here — extension only scrapes DOM and renders UI.
"""
from __future__ import annotations
import os
import re
from typing import Any, Literal
from pathlib import Path
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from spoke_cards import get_company_dna
from spoke_extension import normalize_extension_payload
from spoke_intelligence import run_cfo_auditor, run_search_strategist, reevaluate_with_justification
from spoke_market import execute_exa_instant_scan
from spoke_stripe_tracker import capture_pending_auth, fetch_live_financial_health, resolve_authorization
app = FastAPI(title="AgentCFO APE Backend", version="1.1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
PROFILE_ID = os.getenv("APE_COMPANY_PROFILE", "standard_b2b_startup")
_EXTENSION_DIR = Path(__file__).parent / "extension"
# In-memory context cache keyed by pending auth id — enables HITL re-evaluation
# of a flagged purchase using the human's justification as new context.
_AUDIT_SESSIONS: dict[str, dict[str, Any]] = {}
class InterceptRequest(BaseModel):
raw_dom_text: str = Field(..., description="Sanitized checkout DOM text from extension")
merchant: str | None = None
amount_cents: int | None = None
currency: str = "usd"
department: str = "Engineering"
used_card_id: str = "ic_extension_card"
category: str = "software"
line_items: list[dict[str, Any]] | None = None
page_url: str = ""
class ResolveBody(BaseModel):
auth_id: str
justification: str = ""
def _parse_analysis_sections(concise_analysis: str | dict[str, Any]) -> dict[str, str]:
if isinstance(concise_analysis, dict):
return {
"market": concise_analysis.get("market", ""),
"financial": concise_analysis.get("financial", ""),
"company": concise_analysis.get("company", ""),
}
sections = {"market": "", "financial": "", "company": ""}
patterns = {
"market": r"Market Intelligence \(Exa\):\s*(.+?)(?=Financial|Company|$)",
"financial": r"Financial Health \(Stripe\):\s*(.+?)(?=Company|Market|$)",
"company": r"Company Context \(Precollected DNA\):\s*(.+?)(?=Market|Financial|$)",
}
for key, pattern in patterns.items():
match = re.search(pattern, concise_analysis, re.I | re.S)
if match:
sections[key] = match.group(1).strip()
if not any(sections.values()):
sections["market"] = concise_analysis[:500]
return sections
def _cents_to_display(cents: int) -> str:
return f"${cents / 100:,.0f}/mo" if cents else "—"
def _build_ui_capsules(
audit: dict[str, Any],
market_data: dict[str, Any],
financials: dict[str, Any],
company_dna: dict[str, Any],
cart: dict[str, Any] | None = None,
) -> dict[str, dict[str, Any]]:
signals = audit.get("signals", {})
sections = _parse_analysis_sections(audit.get("concise_analysis", ""))
premium = signals.get("market_premium_percent", market_data.get("summary", {}).get("estimated_premium_percent", 0))
util = signals.get("department_projected_utilization_percent", 0)
runway = signals.get("cash_runway_months", financials.get("cash_runway_months", 0))
cart = cart or {}
amount_cents = cart.get("amount_cents") or 0
target_monthly = amount_cents // 12 if amount_cents > 10000 else amount_cents
fair_monthly = int(target_monthly / (1 + premium / 100)) if premium else target_monthly
efficiency_delta = -int(premium) if premium else 0
dept = cart.get("department") or financials.get("department", "Team")
budget_label = (
f"{dept} Software Budget At Peak Capacity"
if util > 90
else f"{dept} Software Budget Utilization"
)
checklist: list[dict[str, str]] = []
for dup in signals.get("stack_duplicates", []):
checklist.append(
{
"text": f"Stack redundancy: {dup.get('unused_seats', 0)} unused {dup.get('existing_tool', 'tool')} licenses",
"status": "warn",
}
)
for v in signals.get("policy_violations", []):
checklist.append({"text": v.get("detail") or v.get("description", "Policy check"), "status": "warn"})
if not checklist:
checklist.append({"text": "Mission alignment verified against sustainability charter", "status": "ok"})
checklist.append({"text": "No duplicate tooling detected in Stack Registry", "status": "ok"})
checklist.append({"text": "Expense policy thresholds within nominal range", "status": "ok"})
return {
"market": {
"source": "Exa",
"headline": "Market Benchmark Baseline",
"label": "Market Intelligence (Exa API Data)",
"metric_percent": premium,
"target_display": _cents_to_display(target_monthly),
"fair_rate_display": _cents_to_display(fair_monthly),
"efficiency_delta": efficiency_delta,
"body": sections["market"]
or market_data.get("summary", {}).get("baseline_note", "Benchmark scan complete."),
},
"financial": {
"source": "Stripe",
"headline": "Stripe Corporate Ledger",
"label": "Financial Health (Stripe API Data)",
"metric_percent": util,
"budget_fill_percent": min(int(util), 100),
"budget_label": budget_label,
"runway_months": runway,
"body": sections["financial"]
or f"Cash runway ~{runway} months; department utilization {util:.0f}%.",
},
"company": {
"source": "DNA",
"headline": "Corporate DNA Sync",
"label": "Strategic Alignment (Precollected DNA Data)",
"body": sections["company"] or company_dna["mission_hub"]["statement"],
"checklist": checklist,
},
}
def _run_intercept_pipeline(cart_data: dict[str, Any]) -> dict[str, Any]:
import time
telemetry: list[dict[str, Any]] = []
def _stage(agent: str, label: str, fn):
start = time.perf_counter()
result = fn()
elapsed_ms = int((time.perf_counter() - start) * 1000)
telemetry.append({"agent": agent, "label": label, "ms": elapsed_ms, "status": "done"})
return result
company_dna = _stage(
"Company DNA", "Loading precollected corporate rules",
lambda: get_company_dna(profile_id=PROFILE_ID),
)
stripe_health = _stage(
"Stripe Hub", "Pulling live balances & runway",
lambda: fetch_live_financial_health(card_id=cart_data["used_card_id"]),
)
pending_auth_id = _stage(
"Stripe Hub", "Placing manual authorization hold",
lambda: capture_pending_auth(
card_id=cart_data["used_card_id"],
amount_cents=cart_data["amount_cents"],
merchant=cart_data["merchant"],
),
)
stripe_health["pending_auth_id"] = pending_auth_id
exa_query = _stage(
"Agent 1: Search Strategist", "Compiling Exa query",
lambda: run_search_strategist(raw_cart=cart_data, api_key=os.getenv("OPENAI_API_KEY")),
)
market_benchmarks = _stage(
"Exa API", "Pulling market benchmarks",
lambda: execute_exa_instant_scan(query=exa_query, api_key=os.getenv("EXA_API_KEY")),
)
audit_decision = _stage(
"Agent 2: CFO Auditor", "Cross-referencing Stripe ledger & DNA",
lambda: run_cfo_auditor(
cart=cart_data,
market_data=market_benchmarks,
company_rules=company_dna,
financials=stripe_health,
api_key=os.getenv("OPENAI_API_KEY"),
),
)
capsules = _build_ui_capsules(audit_decision, market_benchmarks, stripe_health, company_dna, cart_data)
# Proof-of-tool-use: surface the real query Agent 1 formulated and the data sources hit.
tool_use = {
"exa_query": exa_query,
"exa_mode": market_benchmarks.get("mode", "unknown"),
"exa_sources": [s.get("url", "") for s in market_benchmarks.get("sources", [])][:3],
"stripe_mode": stripe_health.get("mode", "unknown"),
"pending_auth_id": pending_auth_id,
}
# Cache context for HITL justification re-evaluation at /api/v1/review.
_AUDIT_SESSIONS[pending_auth_id] = {
"cart": cart_data,
"market_data": market_benchmarks,
"company_dna": company_dna,
"financials": stripe_health,
"signals": audit_decision.get("signals", {}),
}
return {
"cart": cart_data,
"exa_query": exa_query,
"pending_auth_id": pending_auth_id,
"telemetry": telemetry,
"tool_use": tool_use,
"audit": {
"is_flagged": audit_decision.get("is_flagged", False),
"missing_context_question": audit_decision.get("missing_context_question", ""),
"chain_of_thought": audit_decision.get("chain_of_thought", []),
"capsules": capsules,
"signals": audit_decision.get("signals", {}),
},
}
@app.get("/health")
def health() -> dict[str, str]:
return {"status": "ok", "service": "agentcfo-ape", "version": "1.1.0"}
# Extension assets for http://127.0.0.1:8787/demo (JS/CSS for demo page)
if _EXTENSION_DIR.exists():
app.mount("/css", StaticFiles(directory=_EXTENSION_DIR / "css"), name="ext-css")
app.mount("/js", StaticFiles(directory=_EXTENSION_DIR / "js"), name="ext-js")
@app.get("/demo")
def demo_checkout_page() -> FileResponse:
"""HTTP checkout demo — content scripts also run here (unlike file:// URLs)."""
page = _EXTENSION_DIR / "demo.html"
if not page.exists():
page = _EXTENSION_DIR / "demo_checkout.html"
return FileResponse(page, media_type="text/html")
@app.post("/api/v1/intercept")
def intercept_v1(request: InterceptRequest) -> dict[str, Any]:
"""Primary thin-client endpoint — full APE pipeline, UI-ready JSON."""
cart_data = normalize_extension_payload(request.model_dump())
return _run_intercept_pipeline(cart_data)
@app.post("/api/v1/resolve")
def resolve_v1(
body: ResolveBody,
action: Literal["approve", "decline"] = Query(..., description="approve or decline"),
) -> dict[str, Any]:
"""Finalize Stripe authorization after user decision."""
bridge_action = "override" if action == "approve" else "abort"
if action == "approve" and not body.justification.strip():
raise HTTPException(status_code=400, detail="Justification required for approve.")
result = resolve_authorization(auth_id=body.auth_id, action=bridge_action)
result["justification"] = body.justification
result["action"] = action
_AUDIT_SESSIONS.pop(body.auth_id, None)
return result
@app.post("/api/v1/review")
def review_v1(body: ResolveBody) -> dict[str, Any]:
"""
HITL: re-evaluate a flagged purchase against the human's justification.
Returns whether the CFO Auditor accepts the override and its reasoning trace,
WITHOUT yet moving money — the client calls /api/v1/resolve on acceptance.
"""
if not body.justification.strip():
raise HTTPException(status_code=400, detail="Justification required for review.")
ctx = _AUDIT_SESSIONS.get(body.auth_id)
if not ctx:
# No cached context (e.g. fallback session) — accept substantive justification heuristically.
return reevaluate_with_justification(
cart={}, market_data={}, company_rules={}, financials={},
prior_signals={}, justification=body.justification,
api_key=os.getenv("OPENAI_API_KEY"),
)
return reevaluate_with_justification(
cart=ctx["cart"],
market_data=ctx["market_data"],
company_rules=ctx["company_dna"],
financials=ctx["financials"],
prior_signals=ctx["signals"],
justification=body.justification,
api_key=os.getenv("OPENAI_API_KEY"),
)
# Legacy routes (backward compatible)
class AuditRequest(InterceptRequest):
pass
class ResolveRequest(BaseModel):
auth_id: str
action: Literal["override", "abort"]
justification: str = ""
@app.post("/api/audit")
def run_audit(request: AuditRequest) -> dict[str, Any]:
return _run_intercept_pipeline(normalize_extension_payload(request.model_dump()))
@app.post("/api/resolve")
def resolve_transaction(request: ResolveRequest) -> dict[str, Any]:
if request.action == "override" and not request.justification.strip():
raise HTTPException(status_code=400, detail="Justification required for override.")
result = resolve_authorization(auth_id=request.auth_id, action=request.action)
result["justification"] = request.justification
return result
if __name__ == "__main__":
import uvicorn
uvicorn.run("api_server:app", host="127.0.0.1", port=8787, reload=True)