shopping-cli 3.2.5__tar.gz → 3.2.7__tar.gz
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.
- {shopping_cli-3.2.5/shopping_cli.egg-info → shopping_cli-3.2.7}/PKG-INFO +1 -1
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/pyproject.toml +2 -2
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/__init__.py +1 -1
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/agents/merchant_agent.py +25 -12
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/agents/merchant_daemon.py +57 -20
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/app.py +7 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/auth.py +10 -6
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/error_handlers.py +11 -1
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/error_response.py +4 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/fallback_asgi.py +11 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/fastapi_routes.py +97 -0
- shopping_cli-3.2.7/shopping_cli/api/handlers/catalog.py +1021 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/handlers/erp.py +20 -1
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/handlers/human_review.py +9 -8
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/handlers/listings_projection.py +3 -1
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/handlers/negotiation.py +9 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/request_limits.py +10 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/route_matching.py +3 -1
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/route_registry.py +9 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/route_table.py +104 -0
- shopping_cli-3.2.7/shopping_cli/api/sqlite_contention.py +11 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/cli.py +71 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/cli_agent_commands.py +35 -27
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/cli_catalog_commands.py +100 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/commerce/adapters.py +19 -6
- shopping_cli-3.2.7/shopping_cli/contracts/kiwi-contracts.lock.json +7 -0
- shopping_cli-3.2.7/shopping_cli/contracts/kiwi-contracts.manifest.json +211 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/catalog.py +134 -4
- shopping_cli-3.2.7/shopping_cli/core/money_authority.py +433 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/negotiation_contracts.py +6 -1
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/data_sources/adapter.py +3 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/data_sources/csv_excel_source.py +68 -47
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/data_sources/erp_source.py +36 -8
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/db/migrations.py +242 -1
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/db/models.py +39 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/listings/projection.py +25 -15
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/negotiation.py +30 -7
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/tokens.py +19 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7/shopping_cli.egg-info}/PKG-INFO +1 -1
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli.egg-info/SOURCES.txt +3 -0
- shopping_cli-3.2.5/shopping_cli/api/handlers/catalog.py +0 -438
- shopping_cli-3.2.5/shopping_cli/contracts/kiwi-contracts.lock.json +0 -7
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/LICENSE +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/MANIFEST.in +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/README.md +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/setup.cfg +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/agents/__init__.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/agents/agent_cli.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/agents/buyer_cli.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/agents/merchant_state_helpers.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/agents/tools.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/__init__.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/handlers/__init__.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/handlers/agents.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/handlers/audit.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/handlers/buyer.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/handlers/common.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/handlers/conversations.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/idempotency.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/limits.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/request_dispatch.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/routes_agents.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/routes_conversations.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/routes_marketplace.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/routes_merchants.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/api/server.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/cli_adapter_commands.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/cli_buyer_commands.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/cli_common.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/cli_conversation_commands.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/cli_erp_commands.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/cli_listing_commands.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/commerce/__init__.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/commerce/data_source.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/config.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/contracts/shopping.negotiation/0.1/capabilities.schema.json +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/contracts/shopping.negotiation/0.1/decision.schema.json +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/contracts/shopping.negotiation/0.1/policy-result.schema.json +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/contracts/shopping.negotiation/0.1/snapshot.schema.json +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/__init__.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/catalog_scoring.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/catalog_text.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/catalog_views.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/channels.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/conversations.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/delivery.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/errors.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/harness.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/limits.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/negotiation.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/policies.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/risk.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/core/tokens.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/data_sources/__init__.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/db/__init__.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/db/provenance.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/db/session.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/http_client.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/listings/__init__.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/__init__.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/agents.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/audit.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/buyer_bootstrap.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/conversations.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/human_review.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_gates.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_message.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_policy_helpers.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_policy_result.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_snapshot.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_snapshot_projection.py +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli.egg-info/dependency_links.txt +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli.egg-info/entry_points.txt +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli.egg-info/requires.txt +0 -0
- {shopping_cli-3.2.5 → shopping_cli-3.2.7}/shopping_cli.egg-info/top_level.txt +0 -0
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "shopping-cli"
|
|
7
|
-
version = "3.2.
|
|
7
|
+
version = "3.2.7"
|
|
8
8
|
description = "Standalone local-commerce AI consultation marketplace runtime"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -67,4 +67,4 @@ where = ["."]
|
|
|
67
67
|
include = ["shopping_cli*"]
|
|
68
68
|
|
|
69
69
|
[tool.setuptools.package-data]
|
|
70
|
-
shopping_cli = ["contracts/*.json"]
|
|
70
|
+
shopping_cli = ["contracts/*.json", "contracts/**/*.json"]
|
|
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
import os
|
|
6
6
|
import re
|
|
7
7
|
import sqlite3
|
|
8
|
+
from decimal import Decimal, InvalidOperation, localcontext
|
|
8
9
|
from typing import Any, cast
|
|
9
10
|
|
|
10
11
|
from shopping_cli import VERSION
|
|
@@ -115,29 +116,41 @@ def _authorized_bargain_amount(product: dict[str, Any]) -> str:
|
|
|
115
116
|
return ""
|
|
116
117
|
|
|
117
118
|
|
|
118
|
-
def
|
|
119
|
-
"""
|
|
119
|
+
def _effective_floor_price_decimal(product: dict[str, Any]) -> Decimal | None:
|
|
120
|
+
"""Exact private floor calculation; preserves the existing policy priority."""
|
|
121
|
+
def amount(value: Any) -> Decimal:
|
|
122
|
+
if isinstance(value, Decimal):
|
|
123
|
+
return value if value.is_finite() and value >= 0 else Decimal(0)
|
|
124
|
+
return Decimal(str(_safe_non_negative_float(value)))
|
|
120
125
|
|
|
121
|
-
|
|
122
|
-
``0 < max_discount_percent <= 100`` → ``price * (1 - discount/100)``;
|
|
123
|
-
否则回退 ``_authorized_bargain_amount`` 自由文本正则(存量
|
|
124
|
-
``automation_boundaries`` 兼容)。全无 → None(无授权底价)。
|
|
125
|
-
"""
|
|
126
|
-
floor = _safe_non_negative_float(product.get("floor_price"))
|
|
126
|
+
floor = amount(product.get("floor_price"))
|
|
127
127
|
if floor > 0:
|
|
128
128
|
return floor
|
|
129
|
-
discount =
|
|
129
|
+
discount = amount(product.get("max_discount_percent"))
|
|
130
130
|
if 0 < discount <= 100:
|
|
131
|
-
|
|
131
|
+
price = amount(product.get("price"))
|
|
132
|
+
# Enough precision for the finite stored decimal coefficients/exponents,
|
|
133
|
+
# including a tiny discount. No currency/floor rounding policy is added.
|
|
134
|
+
with localcontext() as context:
|
|
135
|
+
context.prec = max(28, sum(len(v.as_tuple().digits) + abs(int(v.as_tuple().exponent))
|
|
136
|
+
for v in (price, discount)) + 10)
|
|
137
|
+
return price * (1 - discount / 100)
|
|
132
138
|
free_text = _authorized_bargain_amount(product)
|
|
133
139
|
if free_text:
|
|
134
140
|
try:
|
|
135
|
-
|
|
136
|
-
|
|
141
|
+
value = Decimal(free_text)
|
|
142
|
+
return value if value.is_finite() and value >= 0 else None
|
|
143
|
+
except (InvalidOperation, TypeError, ValueError):
|
|
137
144
|
return None
|
|
138
145
|
return None
|
|
139
146
|
|
|
140
147
|
|
|
148
|
+
def _effective_floor_price(product: dict[str, Any]) -> float | None:
|
|
149
|
+
"""Legacy float projection for existing callers; the authoritative gate is decimal."""
|
|
150
|
+
value = _effective_floor_price_decimal(product)
|
|
151
|
+
return float(value) if value is not None else None
|
|
152
|
+
|
|
153
|
+
|
|
141
154
|
def generate_reply(
|
|
142
155
|
tools: MerchantAgentTools,
|
|
143
156
|
conversation: dict[str, Any],
|
|
@@ -335,6 +335,41 @@ def pid_record_matches_process(pid_record: dict[str, Any], merchant_id: str) ->
|
|
|
335
335
|
return True
|
|
336
336
|
|
|
337
337
|
|
|
338
|
+
def _pid_record_disposition(pid_record: dict[str, Any], merchant_id: str) -> bool | None:
|
|
339
|
+
"""True: confirmed owner; False: dead/reused; None: cannot verify safely."""
|
|
340
|
+
pid = safe_non_negative_int(pid_record.get("pid"))
|
|
341
|
+
if not pid:
|
|
342
|
+
return False
|
|
343
|
+
if psutil is not None and pid_record_matches_process(pid_record, merchant_id):
|
|
344
|
+
return True
|
|
345
|
+
try:
|
|
346
|
+
os.kill(pid, 0)
|
|
347
|
+
except ProcessLookupError:
|
|
348
|
+
return False
|
|
349
|
+
except (PermissionError, OSError):
|
|
350
|
+
return None
|
|
351
|
+
if psutil is None:
|
|
352
|
+
return None
|
|
353
|
+
identity = process_identity(pid)
|
|
354
|
+
if identity is None:
|
|
355
|
+
try:
|
|
356
|
+
if psutil.Process(pid).status() == psutil.STATUS_ZOMBIE:
|
|
357
|
+
return False
|
|
358
|
+
except psutil.NoSuchProcess:
|
|
359
|
+
return False
|
|
360
|
+
except (psutil.AccessDenied, OSError):
|
|
361
|
+
pass
|
|
362
|
+
return None
|
|
363
|
+
# A readable process with a different birth/command is a confirmed reused PID.
|
|
364
|
+
if not pid_record.get("launch_token") or not pid_record.get("create_time"):
|
|
365
|
+
required = ["shopping_cli.cli", "agent", "run", "--merchant", str(merchant_id)]
|
|
366
|
+
cmdline = list(identity.get("cmdline") or [])
|
|
367
|
+
if not all(item in cmdline for item in required):
|
|
368
|
+
return False
|
|
369
|
+
return None
|
|
370
|
+
return False
|
|
371
|
+
|
|
372
|
+
|
|
338
373
|
def state_matches_pid_record(state: dict[str, Any], pid_record: dict[str, Any], merchant_id: str) -> bool:
|
|
339
374
|
launch_token = str(pid_record.get("launch_token") or "")
|
|
340
375
|
if not launch_token or str(state.get("launch_token") or "") != launch_token:
|
|
@@ -429,11 +464,9 @@ def start_agent(
|
|
|
429
464
|
with _PidFileLock(paths["pid_file"]):
|
|
430
465
|
pid_record = read_json(paths["pid_file"], {})
|
|
431
466
|
existing_pid = safe_non_negative_int(pid_record.get("pid"))
|
|
432
|
-
|
|
433
|
-
existing_matches
|
|
434
|
-
|
|
435
|
-
and pid_record_matches_process(pid_record, merchant_id)
|
|
436
|
-
)
|
|
467
|
+
existing_matches = _pid_record_disposition(pid_record, merchant_id)
|
|
468
|
+
if existing_pid and existing_matches is None:
|
|
469
|
+
raise SystemExit(f"Agent process identity unverified for merchant {merchant_id}: pid {existing_pid}")
|
|
437
470
|
stale_replaced = bool(existing_pid and not existing_matches)
|
|
438
471
|
if existing_pid and existing_matches:
|
|
439
472
|
raise SystemExit(f"Agent already running for merchant {merchant_id}: pid {existing_pid}")
|
|
@@ -574,14 +607,11 @@ def stop_agent(
|
|
|
574
607
|
session_id = str(pid_record.get("session_id") or "")
|
|
575
608
|
api_url = str(pid_record.get("api_url") or "")
|
|
576
609
|
launch_token = str(pid_record.get("launch_token") or "")
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
and state_matches_pid_record(state_before_stop, pid_record, merchant_id)
|
|
583
|
-
and pid_record_matches_process(pid_record, merchant_id)
|
|
584
|
-
)
|
|
610
|
+
initial_disposition = _pid_record_disposition(pid_record, merchant_id)
|
|
611
|
+
was_running = initial_disposition is True
|
|
612
|
+
|
|
613
|
+
stop_timed_out = False
|
|
614
|
+
force_kill_attempted = False
|
|
585
615
|
|
|
586
616
|
if was_running:
|
|
587
617
|
# 审查 P2-07:stop 文件含 launch_token——0600(open() 默认 mode 会
|
|
@@ -601,6 +631,8 @@ def stop_agent(
|
|
|
601
631
|
# SIGKILL 兜底:SIGTERM 被阻塞的处理中进程(如卡在 HTTP 调用,
|
|
602
632
|
# 默认 5s 内无法响应)停不掉——强杀并短等待。
|
|
603
633
|
if pid_record_matches_process(pid_record, merchant_id):
|
|
634
|
+
stop_timed_out = True
|
|
635
|
+
force_kill_attempted = True
|
|
604
636
|
try:
|
|
605
637
|
os.kill(pid, signal.SIGKILL)
|
|
606
638
|
except (PermissionError, ProcessLookupError):
|
|
@@ -608,7 +640,6 @@ def stop_agent(
|
|
|
608
640
|
time.sleep(0.2)
|
|
609
641
|
|
|
610
642
|
with _PidFileLock(paths["pid_file"]):
|
|
611
|
-
state_after_stop = read_json(paths["state_file"], {})
|
|
612
643
|
current_record = read_json(paths["pid_file"], {})
|
|
613
644
|
same_launch = bool(
|
|
614
645
|
launch_token
|
|
@@ -618,17 +649,19 @@ def stop_agent(
|
|
|
618
649
|
# A different launch token means a new daemon took over the pid/state
|
|
619
650
|
# files while this stop was in flight; it must remain untouched.
|
|
620
651
|
replaced_by_new_launch = bool(str(current_record.get("launch_token") or "")) and not same_launch
|
|
621
|
-
|
|
622
|
-
|
|
652
|
+
final_disposition = _pid_record_disposition(current_record, merchant_id) if same_launch else False
|
|
653
|
+
identity_unverified = same_launch and final_disposition is None
|
|
654
|
+
running = same_launch and final_disposition is True
|
|
655
|
+
if not running and not identity_unverified and same_launch and paths["pid_file"].exists():
|
|
623
656
|
paths["pid_file"].unlink()
|
|
624
657
|
|
|
625
|
-
if mode != "api":
|
|
658
|
+
if mode != "api" and not replaced_by_new_launch and not identity_unverified:
|
|
626
659
|
with db_session(db_path) as conn:
|
|
627
660
|
merchant_agent.heartbeat(conn, merchant_id, status="away")
|
|
628
661
|
|
|
629
662
|
previous = read_json(paths["state_file"], {})
|
|
630
663
|
counters = previous.get("counters") or {"checked": 0, "replied": 0}
|
|
631
|
-
if not running and not replaced_by_new_launch:
|
|
664
|
+
if not running and not replaced_by_new_launch and not identity_unverified:
|
|
632
665
|
write_state(
|
|
633
666
|
paths["state_file"],
|
|
634
667
|
merchant_id,
|
|
@@ -638,7 +671,8 @@ def stop_agent(
|
|
|
638
671
|
pid=pid or None,
|
|
639
672
|
extra={
|
|
640
673
|
"stopped_at": now_iso(),
|
|
641
|
-
"stop_timed_out":
|
|
674
|
+
"stop_timed_out": stop_timed_out,
|
|
675
|
+
"force_kill_attempted": force_kill_attempted,
|
|
642
676
|
"mode": mode,
|
|
643
677
|
"api_url": api_url,
|
|
644
678
|
"host": host,
|
|
@@ -647,7 +681,10 @@ def stop_agent(
|
|
|
647
681
|
},
|
|
648
682
|
)
|
|
649
683
|
return {
|
|
650
|
-
"ok": not running,
|
|
684
|
+
"ok": not running and not identity_unverified and not replaced_by_new_launch,
|
|
685
|
+
"identity_unverified": identity_unverified,
|
|
686
|
+
"stop_timed_out": stop_timed_out,
|
|
687
|
+
"force_kill_attempted": force_kill_attempted,
|
|
651
688
|
"merchant_id": merchant_id,
|
|
652
689
|
"pid": pid or None,
|
|
653
690
|
"mode": mode,
|
|
@@ -15,10 +15,12 @@ route_registry、fallback ASGI 与既有导入方不变。
|
|
|
15
15
|
from __future__ import annotations
|
|
16
16
|
|
|
17
17
|
import logging
|
|
18
|
+
import sqlite3
|
|
18
19
|
from pathlib import Path
|
|
19
20
|
from typing import Any
|
|
20
21
|
|
|
21
22
|
from shopping_cli import VERSION
|
|
23
|
+
from shopping_cli.api.sqlite_contention import CONTENTION_MESSAGE, is_sqlite_contention
|
|
22
24
|
from shopping_cli.api.fallback_asgi import MarketplaceASGIApp
|
|
23
25
|
from shopping_cli.api.fastapi_routes import (
|
|
24
26
|
AUTHORIZATION_HEADER, # noqa: F401 - compat re-export for external importers
|
|
@@ -92,6 +94,11 @@ def handle_request(
|
|
|
92
94
|
return 400, {"ok": False, "error": str(exc)}
|
|
93
95
|
except ShoppingCliError as exc:
|
|
94
96
|
return 400, {"ok": False, "error": str(exc)}
|
|
97
|
+
except sqlite3.OperationalError as exc:
|
|
98
|
+
if is_sqlite_contention(exc):
|
|
99
|
+
return 503, {"ok": False, "error": CONTENTION_MESSAGE}
|
|
100
|
+
logger.exception("unhandled SQLite operation handling %s %s", method, path)
|
|
101
|
+
return 500, {"ok": False, "error": "internal server error"}
|
|
95
102
|
except Exception:
|
|
96
103
|
logger.exception("unhandled error handling %s %s", method, path)
|
|
97
104
|
return 500, {"ok": False, "error": "internal server error"}
|
|
@@ -9,7 +9,7 @@ from typing import Any
|
|
|
9
9
|
from shopping_cli.core.channels import normalize_channel
|
|
10
10
|
from shopping_cli.core.errors import AuthError
|
|
11
11
|
from shopping_cli.core.tokens import token_matches
|
|
12
|
-
from shopping_cli.config import secret_is_usable
|
|
12
|
+
from shopping_cli.config import deployment_profile_from, secret_is_usable
|
|
13
13
|
from shopping_cli.api.limits import validate_payload
|
|
14
14
|
|
|
15
15
|
|
|
@@ -49,6 +49,10 @@ def payload_with_auth(
|
|
|
49
49
|
return merged
|
|
50
50
|
|
|
51
51
|
|
|
52
|
+
def _runtime_secret_is_usable(value: str) -> bool:
|
|
53
|
+
return secret_is_usable(value, production=deployment_profile_from() == "production")
|
|
54
|
+
|
|
55
|
+
|
|
52
56
|
def configured_admin_token() -> str:
|
|
53
57
|
return str(os.environ.get("SHOPPING_ADMIN_TOKEN") or "").strip()
|
|
54
58
|
|
|
@@ -59,7 +63,7 @@ def configured_buyer_bootstrap_token() -> str:
|
|
|
59
63
|
|
|
60
64
|
def require_admin_token(payload: dict[str, Any]) -> None:
|
|
61
65
|
expected = configured_admin_token()
|
|
62
|
-
if not
|
|
66
|
+
if not _runtime_secret_is_usable(expected):
|
|
63
67
|
raise AuthError("admin bootstrap token is not configured")
|
|
64
68
|
token = payload_admin_token(payload)
|
|
65
69
|
if not token:
|
|
@@ -70,7 +74,7 @@ def require_admin_token(payload: dict[str, Any]) -> None:
|
|
|
70
74
|
|
|
71
75
|
def require_buyer_bootstrap_token(payload: dict[str, Any], digest_fn: Any) -> str:
|
|
72
76
|
expected = configured_buyer_bootstrap_token()
|
|
73
|
-
if not
|
|
77
|
+
if not _runtime_secret_is_usable(expected):
|
|
74
78
|
raise AuthError("buyer bootstrap token is not configured")
|
|
75
79
|
token = payload_buyer_bootstrap_token(payload)
|
|
76
80
|
if not token:
|
|
@@ -83,7 +87,7 @@ def require_buyer_bootstrap_token(payload: dict[str, Any], digest_fn: Any) -> st
|
|
|
83
87
|
def channel_token_map() -> dict[str, str]:
|
|
84
88
|
tokens: dict[str, str] = {}
|
|
85
89
|
global_token = str(os.environ.get("SHOPPING_CHANNEL_TOKEN") or "").strip()
|
|
86
|
-
if
|
|
90
|
+
if _runtime_secret_is_usable(global_token):
|
|
87
91
|
tokens["*"] = global_token
|
|
88
92
|
raw = str(os.environ.get("SHOPPING_CHANNEL_TOKENS") or "").strip()
|
|
89
93
|
if not raw:
|
|
@@ -95,7 +99,7 @@ def channel_token_map() -> dict[str, str]:
|
|
|
95
99
|
if isinstance(decoded, dict):
|
|
96
100
|
for channel, token in decoded.items():
|
|
97
101
|
normalized = normalize_channel(str(channel))
|
|
98
|
-
if normalized and
|
|
102
|
+
if normalized and _runtime_secret_is_usable(str(token or "")):
|
|
99
103
|
tokens[normalized] = str(token).strip()
|
|
100
104
|
return tokens
|
|
101
105
|
for part in raw.replace("\n", ",").split(","):
|
|
@@ -107,7 +111,7 @@ def channel_token_map() -> dict[str, str]:
|
|
|
107
111
|
continue
|
|
108
112
|
channel, token = text.split(separator, 1)
|
|
109
113
|
normalized = normalize_channel(channel)
|
|
110
|
-
if normalized and
|
|
114
|
+
if normalized and _runtime_secret_is_usable(token):
|
|
111
115
|
tokens[normalized] = token.strip()
|
|
112
116
|
return tokens
|
|
113
117
|
|
|
@@ -12,9 +12,11 @@ block).
|
|
|
12
12
|
from __future__ import annotations
|
|
13
13
|
|
|
14
14
|
import logging
|
|
15
|
+
import sqlite3
|
|
15
16
|
from typing import Any
|
|
16
17
|
|
|
17
18
|
from shopping_cli.api.error_response import build_error_response
|
|
19
|
+
from shopping_cli.api.sqlite_contention import CONTENTION_MESSAGE, is_sqlite_contention
|
|
18
20
|
from shopping_cli.core.errors import (
|
|
19
21
|
AuthError,
|
|
20
22
|
ConflictError,
|
|
@@ -97,11 +99,19 @@ def register_error_handlers(
|
|
|
97
99
|
def shopping_cli_error_handler(_request: Any, exc: ShoppingCliError) -> Any:
|
|
98
100
|
return _json_error_response(json_response, 400, str(exc))
|
|
99
101
|
|
|
102
|
+
@app.exception_handler(sqlite3.OperationalError)
|
|
103
|
+
def sqlite_operation_handler(_request: Any, exc: sqlite3.OperationalError) -> Any:
|
|
104
|
+
if is_sqlite_contention(exc):
|
|
105
|
+
return build_error_response(503, CONTENTION_MESSAGE, json_response, headers={"Retry-After": "1"})
|
|
106
|
+
return _json_error_response(json_response, 500, "internal server error")
|
|
107
|
+
|
|
100
108
|
if request_validation_error is not None: # pragma: no cover - exercised with fastapi installed
|
|
101
109
|
@app.exception_handler(request_validation_error)
|
|
102
110
|
def request_validation_error_handler(request: Any, exc: Exception) -> Any:
|
|
103
111
|
# 不回显 str(exc):包含 schema 内部结构并回显调用方输入。
|
|
104
|
-
|
|
112
|
+
errors: list[Any] = getattr(exc, "errors", lambda: [])()
|
|
113
|
+
safe_types = [str(error.get("type", "validation_error")) for error in errors if isinstance(error, dict)]
|
|
114
|
+
logger.warning("request validation failed on schema (%s): types=%s", type(exc).__name__, safe_types)
|
|
105
115
|
return _json_error_response(json_response, 400, "invalid request body")
|
|
106
116
|
|
|
107
117
|
if starlette_http_exception is not None: # pragma: no cover - exercised with fastapi installed
|
|
@@ -11,12 +11,16 @@ def build_error_response(
|
|
|
11
11
|
status_code: int,
|
|
12
12
|
error: str,
|
|
13
13
|
response_factory: Callable[..., Any] | None = None,
|
|
14
|
+
*, headers: dict[str, str] | None = None,
|
|
14
15
|
) -> Any:
|
|
15
16
|
"""Build the existing JSON error envelope for FastAPI or fallback mode."""
|
|
16
17
|
payload = {"ok": False, "error": error}
|
|
17
18
|
if response_factory is not None:
|
|
19
|
+
if headers:
|
|
20
|
+
return response_factory(status_code=status_code, content=payload, headers=headers)
|
|
18
21
|
return response_factory(status_code=status_code, content=payload)
|
|
19
22
|
return SimpleNamespace(
|
|
20
23
|
status_code=status_code,
|
|
21
24
|
body=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
|
|
25
|
+
headers=headers or {},
|
|
22
26
|
)
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
from shopping_cli.api.sqlite_contention import CONTENTION_MESSAGE
|
|
6
|
+
|
|
5
7
|
import asyncio
|
|
6
8
|
import hashlib
|
|
7
9
|
import json
|
|
@@ -93,6 +95,14 @@ class MarketplaceASGIApp:
|
|
|
93
95
|
return self._route_resolver
|
|
94
96
|
|
|
95
97
|
async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
|
|
98
|
+
if scope.get("type") == "lifespan":
|
|
99
|
+
while True:
|
|
100
|
+
event = await receive()
|
|
101
|
+
if event.get("type") == "lifespan.startup":
|
|
102
|
+
await send({"type": "lifespan.startup.complete"})
|
|
103
|
+
elif event.get("type") == "lifespan.shutdown":
|
|
104
|
+
await send({"type": "lifespan.shutdown.complete"})
|
|
105
|
+
return
|
|
96
106
|
if scope.get("type") != "http":
|
|
97
107
|
await send({"type": "http.response.start", "status": 404, "headers": [(b"content-type", b"application/json")]})
|
|
98
108
|
await send({"type": "http.response.body", "body": b'{"ok":false,"error":"unsupported scope"}'})
|
|
@@ -213,6 +223,7 @@ class MarketplaceASGIApp:
|
|
|
213
223
|
(b"content-type", b"application/json"),
|
|
214
224
|
(b"etag", etag.encode("ascii")),
|
|
215
225
|
(b"content-length", str(len(body)).encode("ascii")),
|
|
226
|
+
*([(b"retry-after", b"1")] if status == 503 and response.get("error") == CONTENTION_MESSAGE else []),
|
|
216
227
|
],
|
|
217
228
|
}
|
|
218
229
|
)
|
|
@@ -34,6 +34,7 @@ from shopping_cli.api.route_table import (
|
|
|
34
34
|
_create_human_review,
|
|
35
35
|
_create_merchant,
|
|
36
36
|
_create_product,
|
|
37
|
+
_create_product_exact,
|
|
37
38
|
_fail_agent_message,
|
|
38
39
|
_get_agent,
|
|
39
40
|
_get_conversation,
|
|
@@ -42,6 +43,8 @@ from shopping_cli.api.route_table import (
|
|
|
42
43
|
_get_merchant,
|
|
43
44
|
_get_merchant_private_config,
|
|
44
45
|
_get_product,
|
|
46
|
+
_get_product_exact,
|
|
47
|
+
_get_product_operation_exact,
|
|
45
48
|
_health,
|
|
46
49
|
_human_review_queue,
|
|
47
50
|
_ingest_channel_message,
|
|
@@ -49,7 +52,9 @@ from shopping_cli.api.route_table import (
|
|
|
49
52
|
_list_agents,
|
|
50
53
|
_list_listing_projections,
|
|
51
54
|
_list_merchants,
|
|
55
|
+
_list_products_exact,
|
|
52
56
|
_merchant_conversations,
|
|
57
|
+
_merchant_token_status,
|
|
53
58
|
_negotiation_abandon_claim,
|
|
54
59
|
_negotiation_abandon_stale_claims,
|
|
55
60
|
_negotiation_claim,
|
|
@@ -59,6 +64,8 @@ from shopping_cli.api.route_table import (
|
|
|
59
64
|
_negotiation_pending_messages,
|
|
60
65
|
_negotiation_snapshot,
|
|
61
66
|
_negotiation_submit_decision,
|
|
67
|
+
_prepare_merchant_token_rotation,
|
|
68
|
+
_confirm_merchant_token_rotation,
|
|
62
69
|
_recover_merchant_token,
|
|
63
70
|
_record_tool_call_audit,
|
|
64
71
|
_resolve_human_review,
|
|
@@ -72,6 +79,9 @@ from shopping_cli.api.route_table import (
|
|
|
72
79
|
_sync_erp,
|
|
73
80
|
_update_merchant,
|
|
74
81
|
_update_product,
|
|
82
|
+
_update_product_inventory_exact,
|
|
83
|
+
_update_product_listing_exact,
|
|
84
|
+
_update_product_money_exact,
|
|
75
85
|
)
|
|
76
86
|
|
|
77
87
|
try: # pragma: no cover - exercised when optional dependency is installed
|
|
@@ -159,6 +169,10 @@ def register_fastapi_routes(app: Any, db_path: str | Path) -> None:
|
|
|
159
169
|
api_auth.payload_with_auth({}, authorization),
|
|
160
170
|
)
|
|
161
171
|
|
|
172
|
+
@app.get("/merchants/{merchant_id}/token/status")
|
|
173
|
+
def merchant_token_status(merchant_id: str, authorization: str = AUTHORIZATION_HEADER) -> dict[str, Any]:
|
|
174
|
+
return _merchant_token_status(db_path, merchant_id, api_auth.payload_with_auth({}, authorization))
|
|
175
|
+
|
|
162
176
|
@app.post("/merchants/{merchant_id}/token/rotate")
|
|
163
177
|
def rotate_merchant_token(
|
|
164
178
|
merchant_id: str,
|
|
@@ -171,6 +185,14 @@ def register_fastapi_routes(app: Any, db_path: str | Path) -> None:
|
|
|
171
185
|
api_auth.payload_with_auth(payload, authorization),
|
|
172
186
|
)
|
|
173
187
|
|
|
188
|
+
@app.post("/merchants/{merchant_id}/token/rotate/prepare")
|
|
189
|
+
def prepare_merchant_token_rotation(merchant_id: str, payload: dict[str, Any], authorization: str = AUTHORIZATION_HEADER) -> dict[str, Any]:
|
|
190
|
+
return _prepare_merchant_token_rotation(db_path, merchant_id, api_auth.payload_with_auth(payload, authorization))
|
|
191
|
+
|
|
192
|
+
@app.post("/merchants/{merchant_id}/token/rotate/confirm")
|
|
193
|
+
def confirm_merchant_token_rotation(merchant_id: str, payload: dict[str, Any], authorization: str = AUTHORIZATION_HEADER) -> dict[str, Any]:
|
|
194
|
+
return _confirm_merchant_token_rotation(db_path, merchant_id, api_auth.payload_with_auth(payload, authorization))
|
|
195
|
+
|
|
174
196
|
@app.post("/merchants/{merchant_id}/token/revoke")
|
|
175
197
|
def revoke_merchant_tokens(
|
|
176
198
|
merchant_id: str,
|
|
@@ -225,6 +247,81 @@ def register_fastapi_routes(app: Any, db_path: str | Path) -> None:
|
|
|
225
247
|
) -> dict[str, Any]:
|
|
226
248
|
return _update_product(db_path, sku, api_auth.payload_with_auth(payload, authorization))
|
|
227
249
|
|
|
250
|
+
@app.get("/v1/merchant/products/exact")
|
|
251
|
+
def list_products_exact(
|
|
252
|
+
merchant_id: str,
|
|
253
|
+
limit: int = 50,
|
|
254
|
+
offset: int = 0,
|
|
255
|
+
authorization: str = AUTHORIZATION_HEADER,
|
|
256
|
+
) -> dict[str, Any]:
|
|
257
|
+
return _list_products_exact(
|
|
258
|
+
db_path,
|
|
259
|
+
{"merchant_id": merchant_id, "limit": limit, "offset": offset},
|
|
260
|
+
api_auth.payload_with_auth({}, authorization),
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
@app.post("/v1/merchant/products/exact")
|
|
264
|
+
def create_product_exact(
|
|
265
|
+
payload: dict[str, Any], authorization: str = AUTHORIZATION_HEADER
|
|
266
|
+
) -> dict[str, Any]:
|
|
267
|
+
return _create_product_exact(
|
|
268
|
+
db_path, api_auth.payload_with_auth(payload, authorization)
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
@app.get("/v1/merchant/products/{sku}/exact")
|
|
272
|
+
def get_product_exact(
|
|
273
|
+
sku: str,
|
|
274
|
+
merchant_id: str,
|
|
275
|
+
authorization: str = AUTHORIZATION_HEADER,
|
|
276
|
+
) -> dict[str, Any]:
|
|
277
|
+
return _get_product_exact(
|
|
278
|
+
db_path,
|
|
279
|
+
sku,
|
|
280
|
+
api_auth.payload_with_auth({"merchant_id": merchant_id}, authorization),
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
@app.patch("/v1/merchant/products/{sku}/money")
|
|
284
|
+
def update_product_money_exact(
|
|
285
|
+
sku: str,
|
|
286
|
+
payload: dict[str, Any],
|
|
287
|
+
authorization: str = AUTHORIZATION_HEADER,
|
|
288
|
+
) -> dict[str, Any]:
|
|
289
|
+
return _update_product_money_exact(
|
|
290
|
+
db_path, sku, api_auth.payload_with_auth(payload, authorization)
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
@app.patch("/v1/merchant/products/{sku}/inventory")
|
|
294
|
+
def update_product_inventory_exact(
|
|
295
|
+
sku: str,
|
|
296
|
+
payload: dict[str, Any],
|
|
297
|
+
authorization: str = AUTHORIZATION_HEADER,
|
|
298
|
+
) -> dict[str, Any]:
|
|
299
|
+
return _update_product_inventory_exact(
|
|
300
|
+
db_path, sku, api_auth.payload_with_auth(payload, authorization)
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
@app.patch("/v1/merchant/products/{sku}/listing")
|
|
304
|
+
def update_product_listing_exact(
|
|
305
|
+
sku: str,
|
|
306
|
+
payload: dict[str, Any],
|
|
307
|
+
authorization: str = AUTHORIZATION_HEADER,
|
|
308
|
+
) -> dict[str, Any]:
|
|
309
|
+
return _update_product_listing_exact(
|
|
310
|
+
db_path, sku, api_auth.payload_with_auth(payload, authorization)
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
@app.get("/v1/merchant/product-operations/{operation_id}")
|
|
314
|
+
def get_product_operation_exact(
|
|
315
|
+
operation_id: str,
|
|
316
|
+
merchant_id: str,
|
|
317
|
+
authorization: str = AUTHORIZATION_HEADER,
|
|
318
|
+
) -> dict[str, Any]:
|
|
319
|
+
return _get_product_operation_exact(
|
|
320
|
+
db_path,
|
|
321
|
+
operation_id,
|
|
322
|
+
api_auth.payload_with_auth({"merchant_id": merchant_id}, authorization),
|
|
323
|
+
)
|
|
324
|
+
|
|
228
325
|
@app.get("/v1/merchant/listings/projections")
|
|
229
326
|
def merchant_listing_projections(
|
|
230
327
|
merchant_id: str = "",
|