Simzy commited on
Commit
2204fb4
·
verified ·
1 Parent(s): a283838

Add GET /api/chat/pending for Chief of Staff polling

Browse files
Files changed (1) hide show
  1. app.py +90 -8
app.py CHANGED
@@ -1,6 +1,7 @@
1
  """Command Center chat bridge API for Hugging Face Spaces."""
2
  from __future__ import annotations
3
 
 
4
  import json
5
  import logging
6
  import os
@@ -144,6 +145,19 @@ def _append_key_query(url: str, key: str) -> str:
144
  return urlunparse(parsed._replace(query=new_query))
145
 
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  @app.get("/health")
148
  def health() -> dict[str, bool]:
149
  return {"ok": True}
@@ -157,11 +171,13 @@ def root() -> dict[str, Any]:
157
  "health": "/health",
158
  "chat": "/api/chat",
159
  "reply": "/api/chat/reply",
 
160
  }
161
 
162
 
163
  @app.options("/api/chat")
164
  @app.options("/api/chat/reply")
 
165
  async def options_ok() -> JSONResponse:
166
  return JSONResponse(
167
  content={"ok": True},
@@ -179,6 +195,7 @@ async def post_chat(body: ChatRequest) -> dict[str, Any]:
179
  "id": str(uuid.uuid4()),
180
  "role": "user",
181
  "botId": body.botId,
 
182
  "text": body.text,
183
  "clientMsgId": body.clientMsgId,
184
  "createdAt": _now_iso(),
@@ -258,14 +275,7 @@ async def post_reply(
258
  body: ReplyRequest,
259
  authorization: Optional[str] = Header(default=None),
260
  ) -> dict[str, bool]:
261
- secret = (os.environ.get("CHAT_BRIDGE_SECRET") or "").strip()
262
- if not secret:
263
- raise HTTPException(status_code=503, detail="CHAT_BRIDGE_SECRET not configured")
264
- if not authorization or not authorization.startswith("Bearer "):
265
- raise HTTPException(status_code=401, detail="missing bearer token")
266
- token = authorization[7:].strip()
267
- if token != secret:
268
- raise HTTPException(status_code=401, detail="invalid bearer token")
269
 
270
  with _lock:
271
  data = _load_session(body.sessionId)
@@ -301,6 +311,78 @@ async def post_reply(
301
  return {"ok": True}
302
 
303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  @app.on_event("startup")
305
  def on_startup() -> None:
306
  global SESSIONS_DIR
 
1
  """Command Center chat bridge API for Hugging Face Spaces."""
2
  from __future__ import annotations
3
 
4
+ import hmac
5
  import json
6
  import logging
7
  import os
 
145
  return urlunparse(parsed._replace(query=new_query))
146
 
147
 
148
+
149
+
150
+ def _require_bridge_secret(authorization: Optional[str]) -> None:
151
+ secret = (os.environ.get("CHAT_BRIDGE_SECRET") or "").strip()
152
+ if not secret:
153
+ raise HTTPException(status_code=503, detail="CHAT_BRIDGE_SECRET not configured")
154
+ if not authorization or not authorization.startswith("Bearer "):
155
+ raise HTTPException(status_code=401, detail="missing bearer token")
156
+ token = authorization[7:].strip()
157
+ if not hmac.compare_digest(token, secret):
158
+ raise HTTPException(status_code=401, detail="invalid bearer token")
159
+
160
+
161
  @app.get("/health")
162
  def health() -> dict[str, bool]:
163
  return {"ok": True}
 
171
  "health": "/health",
172
  "chat": "/api/chat",
173
  "reply": "/api/chat/reply",
174
+ "pending": "/api/chat/pending",
175
  }
176
 
177
 
178
  @app.options("/api/chat")
179
  @app.options("/api/chat/reply")
180
+ @app.options("/api/chat/pending")
181
  async def options_ok() -> JSONResponse:
182
  return JSONResponse(
183
  content={"ok": True},
 
195
  "id": str(uuid.uuid4()),
196
  "role": "user",
197
  "botId": body.botId,
198
+ "botName": body.botName,
199
  "text": body.text,
200
  "clientMsgId": body.clientMsgId,
201
  "createdAt": _now_iso(),
 
275
  body: ReplyRequest,
276
  authorization: Optional[str] = Header(default=None),
277
  ) -> dict[str, bool]:
278
+ _require_bridge_secret(authorization)
 
 
 
 
 
 
 
279
 
280
  with _lock:
281
  data = _load_session(body.sessionId)
 
311
  return {"ok": True}
312
 
313
 
314
+
315
+ @app.get("/api/chat/pending")
316
+ async def get_pending(
317
+ authorization: Optional[str] = Header(default=None),
318
+ ) -> dict[str, Any]:
319
+ """Return unanswered user messages (no matching assistant final for clientMsgId)."""
320
+ _require_bridge_secret(authorization)
321
+
322
+ pending: list[dict[str, Any]] = []
323
+ with _lock:
324
+ try:
325
+ session_files = sorted(SESSIONS_DIR.glob("*.json"))
326
+ except OSError as exc:
327
+ log.warning("Failed to list sessions: %s", exc)
328
+ session_files = []
329
+
330
+ for path in session_files:
331
+ if path.name.endswith(".tmp"):
332
+ continue
333
+ try:
334
+ with path.open("r", encoding="utf-8") as f:
335
+ data = json.load(f)
336
+ except (json.JSONDecodeError, OSError) as exc:
337
+ log.warning("Failed to read session file %s: %s", path, exc)
338
+ continue
339
+ if not isinstance(data, dict):
340
+ continue
341
+ session_id = data.get("sessionId") or path.stem
342
+ messages = data.get("messages") or []
343
+ if not isinstance(messages, list):
344
+ continue
345
+
346
+ final_assistant_ids: set[str] = set()
347
+ for m in messages:
348
+ if not isinstance(m, dict):
349
+ continue
350
+ if (
351
+ m.get("role") == "assistant"
352
+ and m.get("status") == "final"
353
+ and isinstance(m.get("clientMsgId"), str)
354
+ ):
355
+ final_assistant_ids.add(m["clientMsgId"])
356
+
357
+ for m in messages:
358
+ if not isinstance(m, dict):
359
+ continue
360
+ if m.get("role") != "user":
361
+ continue
362
+ client_msg_id = m.get("clientMsgId")
363
+ if not isinstance(client_msg_id, str) or not client_msg_id:
364
+ continue
365
+ if client_msg_id in final_assistant_ids:
366
+ continue
367
+ pending.append(
368
+ {
369
+ "sessionId": session_id,
370
+ "clientMsgId": client_msg_id,
371
+ "botId": m.get("botId"),
372
+ "botName": m.get("botName"),
373
+ "text": m.get("text"),
374
+ "createdAt": m.get("createdAt"),
375
+ }
376
+ )
377
+
378
+ def _sort_key(item: dict[str, Any]) -> str:
379
+ created = item.get("createdAt")
380
+ return created if isinstance(created, str) else ""
381
+
382
+ pending.sort(key=_sort_key)
383
+ return {"messages": pending[:50]}
384
+
385
+
386
  @app.on_event("startup")
387
  def on_startup() -> None:
388
  global SESSIONS_DIR