Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/api/app/api/routes/admin/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ class GenerateCardKeysIn(BaseModel):
"""credit = unified 积分 top-up; plan = membership + monthly 积分."""
kind: str = Field(default="credit", max_length=16)
# Face value in 积分.
tokens: int = Field(default=0, ge=0, le=50_000_000)
credits: int = Field(default=0, ge=0, le=50_000_000)
planId: str | None = Field(default=None, max_length=16)
expiresDays: int = Field(default=365, ge=0, le=3650)
# Dedicated generate password (CARD_KEY_OPS_PASSWORD), not the login password.
Expand Down
4 changes: 2 additions & 2 deletions apps/api/app/api/routes/admin/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def admin_generate_card_keys(
try:
keys = generate_card_keys(
count=body.count,
tokens=body.tokens,
credits=body.credits,
expires_days=body.expiresDays,
kind=body.kind,
plan_id=body.planId,
Expand All @@ -131,7 +131,7 @@ def admin_generate_card_keys(
"count": len(keys),
"kind": first.get("kind") or body.kind,
"planId": first.get("planId") or body.planId,
"tokens": first.get("tokens") if keys else body.tokens,
"credits": first.get("credits") if keys else body.credits,
"expiresDays": body.expiresDays,
"keys": keys,
}
Expand Down
15 changes: 4 additions & 11 deletions apps/api/app/api/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@
)
from app.services.wallet.db import (
ensure_user_balance,
get_user_tokens,
get_wallet,
init_wallet_db,
list_ledger,
Expand Down Expand Up @@ -510,10 +509,8 @@ def email_login(body: EmailLoginIn, request: Request) -> dict[str, Any]:

@router.get("/me", response_model=AuthMeOut)
def auth_me(current_user: CurrentUser) -> dict[str, Any]:
init_wallet_db()
return {
"user": _user_payload(current_user),
"tokens": get_user_tokens(current_user.id),
}


Expand Down Expand Up @@ -578,10 +575,9 @@ def _wallet_plan_fields(snap: dict[str, Any]) -> dict[str, Any]:
def wallet_me(current_user: CurrentUser) -> dict[str, Any]:
init_wallet_db()
snap = get_wallet(current_user.id)
credits = int(snap.get("credits") or snap.get("tokens") or 0)
credits = int(snap.get("credits") or 0)
return {
"credits": credits,
"tokens": credits,
**_wallet_plan_fields(snap),
"ledger": list_ledger(current_user.id),
}
Expand All @@ -600,10 +596,9 @@ def wallet_ledger(
"""
init_wallet_db()
snap = get_wallet(current_user.id)
credits = int(snap.get("credits") or snap.get("tokens") or 0)
credits = int(snap.get("credits") or 0)
return {
"credits": credits,
"tokens": credits,
**_wallet_plan_fields(snap),
**list_ledger_page(current_user.id, page=page, page_size=pageSize, kind=kind),
}
Expand Down Expand Up @@ -640,14 +635,12 @@ def wallet_redeem(
) from err
clear_redeem_rate_limit(user_id=current_user.id, ip=ip)
snap = get_wallet(current_user.id)
credits = int(snap.get("credits") or snap.get("tokens") or 0)
added = int(result.get("creditsAdded") or result.get("tokensAdded") or 0)
credits = int(snap.get("credits") or 0)
added = int(result.get("creditsAdded") or 0)
return {
"kind": result.get("kind") or "credit",
"creditsAdded": added,
"tokensAdded": added,
"credits": credits,
"tokens": credits,
**_wallet_plan_fields(snap),
"ledger": list_ledger(current_user.id),
}
Expand Down
14 changes: 4 additions & 10 deletions apps/api/app/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -2438,17 +2438,15 @@ def _bind(val: Any) -> str:
where.append(f"status = {_bind(status.strip())}")
if q and q.strip():
like = f"%{q.strip()}%"
b1, b2, b3, b4, b5 = (
_bind(like),
b1, b2, b3, b4 = (
_bind(like),
_bind(like),
_bind(like),
_bind(like),
)
where.append(
f"(id LIKE {b1} OR user_id LIKE {b2} OR prompt LIKE {b3} OR "
f"coalesce(json_extract(meta_json, '$.trace_id'), '') LIKE {b4} OR "
f"coalesce(json_extract(meta_json, '$.decision_log.trace_id'), '') LIKE {b5})"
f"coalesce(json_extract(meta_json, '$.decision_log.trace_id'), '') LIKE {b4})"
)
route_filter = (route or "").strip().lower()
if route_filter:
Expand Down Expand Up @@ -2477,24 +2475,20 @@ def _bind(val: Any) -> str:
f"""
SELECT
id, user_id, scene, status, prompt, error_message, created_at, updated_at,
json_extract(meta_json, '$.trace_id') AS trace_id,
json_extract(meta_json, '$.control') AS control,
json_extract(meta_json, '$.flow_id') AS flow_id,
json_extract(meta_json, '$.flow_version') AS flow_version,
json_extract(meta_json, '$.decision_log.trace_id') AS dl_trace,
json_extract(meta_json, '$.decision_log.route') AS dl_route,
json_extract(meta_json, '$.decision_log.intent') AS dl_intent,
json_extract(meta_json, '$.execution_log.trace_id') AS el_trace,
json_extract(meta_json, '$.execution_log.intent') AS el_intent,
json_extract(meta_json, '$.execution_log.flow_id') AS el_flow,
json_extract(meta_json, '$.execution_log.ops_count') AS ops_count,
json_extract(meta_json, '$.execution_log.total_tokens') AS total_tokens,
json_extract(meta_json, '$.execution_log.total_duration_ms') AS total_duration_ms,
json_extract(meta_json, '$.execution_log.painted') AS painted,
json_extract(meta_json, '$.execution_log.task_tier') AS task_tier,
json_extract(meta_json, '$.execution_log.vision_used') AS vision_used,
json_extract(meta_json, '$.execution_log.model') AS model,
json_extract(meta_json, '$.execution_log.skills_loaded') AS el_skills,
json_extract(meta_json, '$.decision_log.skills_loaded') AS dl_skills
json_extract(meta_json, '$.execution_log.skills_loaded') AS el_skills
FROM design_task
WHERE {sql_where}
ORDER BY created_at DESC
Expand Down
1 change: 0 additions & 1 deletion apps/api/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ class AuthSessionOut(SQLModel):

class AuthMeOut(SQLModel):
user: UserPublic
tokens: int | float | None = None


class OkOut(SQLModel):
Expand Down
7 changes: 3 additions & 4 deletions apps/api/app/services/admin/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from app.services.db import init_schema
from app.services.wallet.db import (
credit_tokens,
get_user_tokens,
get_wallet,
list_ledger_page,
normalize_plan,
Expand Down Expand Up @@ -97,7 +96,7 @@ def adjust_tokens(user_id: str, amount: int, detail: str = "") -> dict[str, Any]
else:
balance = spend_tokens(uid, abs(amt), detail=note, force=True)

return {"userId": uid, "tokens": balance, "amount": amt}
return {"userId": uid, "credits": balance, "amount": amt}


def user_ledger(
Expand All @@ -110,7 +109,7 @@ def user_ledger(
snap = get_wallet(user_id)
expires = snap.get("planExpiresAt")
return {
"tokens": int(snap.get("tokens") or get_user_tokens(user_id) or 0),
"credits": int(snap.get("credits") or 0),
"planId": snap.get("planId") or "free",
"planStored": snap.get("planStored") or "free",
"planExpiresAt": int(float(expires) * 1000) if expires is not None else None,
Expand Down Expand Up @@ -149,7 +148,7 @@ def _user_to_out(user: User, bal: UserBalance | None) -> dict[str, Any]:
"provider": user.provider or "email",
"role": user.role or "user",
"status": user.status or "active",
"tokens": int(bal.tokens or 0) if bal else 0,
"credits": int(bal.tokens or 0) if bal else 0,
"planId": plan_id,
"planStored": stored,
"planExpiresAt": int(expires_at * 1000) if expires_at is not None else None,
Expand Down
8 changes: 4 additions & 4 deletions apps/api/app/services/agent_memory/episodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ def _summarize_actions(ops: list[Any] | None) -> list[dict[str, Any]]:
for item in ops or []:
if not isinstance(item, dict):
continue
name = str(item.get("op") or item.get("type") or item.get("name") or "").strip()
name = str(item.get("name") or "").strip()
if not name:
continue
slim: dict[str, Any] = {"op": name[:64]}
slim: dict[str, Any] = {"name": name[:64]}
for key in ("id", "frameId", "targetId", "name"):
val = item.get(key)
if val is not None and str(val).strip():
Expand Down Expand Up @@ -280,9 +280,9 @@ def _row_to_hit(r: Any, *, retrieve: str, score: float | None = None) -> dict[st
except Exception:
actions = []
op_names = [
str(a.get("op") or "")
str(a.get("name") or "")
for a in actions
if isinstance(a, dict) and a.get("op")
if isinstance(a, dict) and a.get("name")
]
hit: dict[str, Any] = {
"id": str(_col(r, "id") or ""),
Expand Down
12 changes: 5 additions & 7 deletions apps/api/app/services/agent_memory/kg.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def extract_factual_triples_from_episode(
op_names: list[str] = []
for a in actions or []:
if isinstance(a, dict):
name = str(a.get("op") or a.get("name") or "").strip()
name = str(a.get("name") or "").strip()
if name:
op_names.append(name)
elif isinstance(a, str) and a.strip():
Expand Down Expand Up @@ -553,17 +553,15 @@ def _parse_triples_json(
raw = None
items: list[Any] = []
if isinstance(raw, dict):
items = raw.get("triples") or raw.get("items") or raw.get("edges") or []
elif isinstance(raw, list):
items = raw
items = raw.get("triples") or []
sc = (scene or "").strip().lower() or ""
out: list[tuple[str, str, str]] = []
for it in items:
if not isinstance(it, dict):
continue
s = str(it.get("s") or it.get("subject") or "").strip()
p = str(it.get("p") or it.get("predicate") or "").strip()
o = str(it.get("o") or it.get("object") or "").strip()
s = str(it.get("s") or "").strip()
p = str(it.get("p") or "").strip()
o = str(it.get("o") or "").strip()
if not p or not o:
continue
if p not in allowed:
Expand Down
6 changes: 3 additions & 3 deletions apps/api/app/services/agent_memory/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def slim_review_for_memory(review: dict[str, Any] | None) -> dict[str, Any]:
out["overall"] = int(src.get("overall"))
except (TypeError, ValueError):
pass
action = str(src.get("action") or src.get("review_action") or "").strip()
action = str(src.get("action") or "").strip()
if action:
out["action"] = action
summary = str(src.get("summary") or "").strip()
Expand Down Expand Up @@ -357,7 +357,7 @@ def trim_short_turn(turn: dict[str, Any]) -> dict[str, Any] | None:
role = str(turn.get("role") or "").strip().lower()
if role not in ("user", "assistant"):
return None
text = str(turn.get("text") or turn.get("content") or "").strip()
text = str(turn.get("text") or "").strip()
if not text:
return None
if re_looks_like_markup(text):
Expand All @@ -373,4 +373,4 @@ def trim_short_turn(turn: dict[str, Any]) -> dict[str, Any] | None:
def re_looks_like_markup(text: str) -> bool:
import re

return bool(re.search(r"<svg\b|</svg>|\{\s*\"tool_ops\"|\"ops\"\s*:", text, flags=re.I))
return bool(re.search(r"<svg\b|</svg>|\{\s*\"tool_ops\"", text, flags=re.I))
6 changes: 3 additions & 3 deletions apps/api/app/services/agent_memory/short_term.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def assistant_facing_text(text: str, *, max_chars: int = 800) -> str:

def normalize_turn_for_dialogue(turn: dict[str, Any], *, per_turn_chars: int) -> dict[str, Any] | None:
role = str(turn.get("role") or "").strip().lower()
raw = str(turn.get("text") or turn.get("content") or "").strip()
raw = str(turn.get("text") or "").strip()
if not raw or role not in ("user", "assistant"):
return None
text = assistant_facing_text(raw, max_chars=per_turn_chars) if role == "assistant" else raw[:per_turn_chars]
Expand Down Expand Up @@ -278,7 +278,7 @@ def trim_turns_by_chars(
lc_msgs: list[BaseMessage] = []
for t in turns:
role = str(t.get("role") or "")
text = str(t.get("text") or t.get("content") or "")
text = str(t.get("text") or "")
if role == "user":
lc_msgs.append(HumanMessage(content=text))
elif role == "assistant":
Expand Down Expand Up @@ -378,7 +378,7 @@ def update_dialogue_after_run(
names: list[str] = []
for op in tool_ops_applied[:6]:
if isinstance(op, dict):
n = str(op.get("name") or op.get("op") or "").strip()
n = str(op.get("name") or "").strip()
if n:
names.append(n)
elif isinstance(op, str) and op.strip():
Expand Down
4 changes: 2 additions & 2 deletions apps/api/app/services/agent_memory/subgoals.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def normalize_item(raw: Any) -> dict[str, Any] | None:
}
if not isinstance(raw, dict):
return None
text = str(raw.get("text") or raw.get("goal") or raw.get("title") or "").strip()
text = str(raw.get("text") or "").strip()
if not text:
return None
status = str(raw.get("status") or "todo").strip().lower()
Expand Down Expand Up @@ -136,7 +136,7 @@ def parse_subgoals_payload(raw: Any) -> list[str]:
if isinstance(item, str) and item.strip():
out.append(item.strip()[:200])
elif isinstance(item, dict):
t = str(item.get("text") or item.get("goal") or "").strip()
t = str(item.get("text") or "").strip()
if t:
out.append(t[:200])
if len(out) >= 8:
Expand Down
4 changes: 2 additions & 2 deletions apps/api/app/services/chat_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def _pack_message_meta(m: dict[str, Any]) -> str | None:
content_marked = m.get("contentMarked")
if isinstance(content_marked, str) and content_marked:
meta["contentMarked"] = content_marked
# Normalize snake_case aliases once, then copy Ask/resume fields.
# Copy Ask / resume fields from the write payload.
aliases = {
"designTaskId": m.get("designTaskId"),
"canResume": True if m.get("canResume") is True else None,
Expand Down Expand Up @@ -92,7 +92,7 @@ def _copy_ask_fields(src: dict[str, Any], dest: dict[str, Any]) -> None:


def _message_public(m: dict[str, Any], *, sort_fallback: int = 0) -> dict[str, Any]:
meta = _unpack_message_meta(m.get("meta_json") or m.get("metaJson") or m.get("meta"))
meta = _unpack_message_meta(m.get("meta_json"))
# Flat fields on write payload also win when listing from in-memory upsert return.
if m.get("durationMs") is not None and "durationMs" not in meta:
try:
Expand Down
Loading
Loading