shopping-cli 3.2.6__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.
Files changed (114) hide show
  1. {shopping_cli-3.2.6/shopping_cli.egg-info → shopping_cli-3.2.7}/PKG-INFO +1 -1
  2. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/pyproject.toml +2 -2
  3. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/__init__.py +1 -1
  4. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/agents/merchant_agent.py +25 -12
  5. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/agents/merchant_daemon.py +57 -20
  6. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/app.py +7 -0
  7. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/auth.py +10 -6
  8. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/error_handlers.py +11 -1
  9. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/error_response.py +4 -0
  10. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/fallback_asgi.py +11 -0
  11. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/fastapi_routes.py +15 -0
  12. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/catalog.py +119 -0
  13. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/erp.py +20 -1
  14. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/human_review.py +9 -8
  15. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/listings_projection.py +3 -1
  16. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/negotiation.py +9 -0
  17. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/request_limits.py +10 -0
  18. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/route_matching.py +3 -1
  19. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/route_registry.py +3 -0
  20. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/route_table.py +19 -0
  21. shopping_cli-3.2.7/shopping_cli/api/sqlite_contention.py +11 -0
  22. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/cli_agent_commands.py +35 -27
  23. shopping_cli-3.2.7/shopping_cli/contracts/kiwi-contracts.lock.json +7 -0
  24. shopping_cli-3.2.7/shopping_cli/contracts/kiwi-contracts.manifest.json +211 -0
  25. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/money_authority.py +1 -1
  26. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/negotiation_contracts.py +6 -1
  27. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/data_sources/csv_excel_source.py +68 -47
  28. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/data_sources/erp_source.py +27 -8
  29. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/db/migrations.py +37 -1
  30. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/db/models.py +20 -0
  31. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/listings/projection.py +17 -15
  32. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/negotiation.py +30 -7
  33. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/tokens.py +19 -0
  34. {shopping_cli-3.2.6 → shopping_cli-3.2.7/shopping_cli.egg-info}/PKG-INFO +1 -1
  35. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli.egg-info/SOURCES.txt +2 -0
  36. shopping_cli-3.2.6/shopping_cli/contracts/kiwi-contracts.lock.json +0 -7
  37. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/LICENSE +0 -0
  38. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/MANIFEST.in +0 -0
  39. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/README.md +0 -0
  40. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/setup.cfg +0 -0
  41. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/agents/__init__.py +0 -0
  42. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/agents/agent_cli.py +0 -0
  43. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/agents/buyer_cli.py +0 -0
  44. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/agents/merchant_state_helpers.py +0 -0
  45. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/agents/tools.py +0 -0
  46. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/__init__.py +0 -0
  47. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/__init__.py +0 -0
  48. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/agents.py +0 -0
  49. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/audit.py +0 -0
  50. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/buyer.py +0 -0
  51. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/common.py +0 -0
  52. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/handlers/conversations.py +0 -0
  53. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/idempotency.py +0 -0
  54. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/limits.py +0 -0
  55. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/request_dispatch.py +0 -0
  56. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/routes_agents.py +0 -0
  57. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/routes_conversations.py +0 -0
  58. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/routes_marketplace.py +0 -0
  59. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/routes_merchants.py +0 -0
  60. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/api/server.py +0 -0
  61. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/cli.py +0 -0
  62. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/cli_adapter_commands.py +0 -0
  63. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/cli_buyer_commands.py +0 -0
  64. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/cli_catalog_commands.py +0 -0
  65. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/cli_common.py +0 -0
  66. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/cli_conversation_commands.py +0 -0
  67. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/cli_erp_commands.py +0 -0
  68. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/cli_listing_commands.py +0 -0
  69. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/commerce/__init__.py +0 -0
  70. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/commerce/adapters.py +0 -0
  71. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/commerce/data_source.py +0 -0
  72. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/config.py +0 -0
  73. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/contracts/shopping.negotiation/0.1/capabilities.schema.json +0 -0
  74. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/contracts/shopping.negotiation/0.1/decision.schema.json +0 -0
  75. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/contracts/shopping.negotiation/0.1/policy-result.schema.json +0 -0
  76. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/contracts/shopping.negotiation/0.1/snapshot.schema.json +0 -0
  77. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/__init__.py +0 -0
  78. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/catalog.py +0 -0
  79. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/catalog_scoring.py +0 -0
  80. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/catalog_text.py +0 -0
  81. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/catalog_views.py +0 -0
  82. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/channels.py +0 -0
  83. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/conversations.py +0 -0
  84. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/delivery.py +0 -0
  85. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/errors.py +0 -0
  86. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/harness.py +0 -0
  87. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/limits.py +0 -0
  88. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/negotiation.py +0 -0
  89. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/policies.py +0 -0
  90. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/risk.py +0 -0
  91. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/core/tokens.py +0 -0
  92. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/data_sources/__init__.py +0 -0
  93. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/data_sources/adapter.py +0 -0
  94. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/db/__init__.py +0 -0
  95. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/db/provenance.py +0 -0
  96. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/db/session.py +0 -0
  97. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/http_client.py +0 -0
  98. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/listings/__init__.py +0 -0
  99. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/__init__.py +0 -0
  100. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/agents.py +0 -0
  101. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/audit.py +0 -0
  102. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/buyer_bootstrap.py +0 -0
  103. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/conversations.py +0 -0
  104. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/human_review.py +0 -0
  105. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_gates.py +0 -0
  106. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_message.py +0 -0
  107. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_policy_helpers.py +0 -0
  108. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_policy_result.py +0 -0
  109. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_snapshot.py +0 -0
  110. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli/services/negotiation_snapshot_projection.py +0 -0
  111. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli.egg-info/dependency_links.txt +0 -0
  112. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli.egg-info/entry_points.txt +0 -0
  113. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli.egg-info/requires.txt +0 -0
  114. {shopping_cli-3.2.6 → shopping_cli-3.2.7}/shopping_cli.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: shopping-cli
3
- Version: 3.2.6
3
+ Version: 3.2.7
4
4
  Summary: Standalone local-commerce AI consultation marketplace runtime
5
5
  License: Apache License
6
6
  Version 2.0, January 2004
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "shopping-cli"
7
- version = "3.2.6"
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"]
@@ -1,3 +1,3 @@
1
1
  """Standalone shopping-cli consultation runtime."""
2
2
 
3
- VERSION = "3.2.6"
3
+ VERSION = "3.2.7"
@@ -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 _effective_floor_price(product: dict[str, Any]) -> float | None:
119
- """解析商家授权的最低成交价(v26 结构化优先)。
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
- 优先级:``product.floor_price > 0`` → 用它;否则
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 = _safe_non_negative_float(product.get("max_discount_percent"))
129
+ discount = amount(product.get("max_discount_percent"))
130
130
  if 0 < discount <= 100:
131
- return _safe_non_negative_float(product.get("price")) * (1 - discount / 100)
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
- return float(free_text)
136
- except (TypeError, ValueError):
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
- existing_state = read_json(paths["state_file"], {})
433
- existing_matches = (
434
- state_matches_pid_record(existing_state, pid_record, merchant_id)
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
- state_before_stop = read_json(paths["state_file"], {})
578
- state_launch_token = str(state_before_stop.get("launch_token") or "")
579
- was_running = bool(
580
- launch_token
581
- and state_launch_token == launch_token
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
- running = same_launch and pid_record_matches_process(current_record, merchant_id) and state_after_stop.get("running") is not False
622
- if not running and same_launch and paths["pid_file"].exists():
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": running,
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 secret_is_usable(expected):
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 secret_is_usable(expected):
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 secret_is_usable(global_token):
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 secret_is_usable(str(token or "")):
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 secret_is_usable(token):
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
- logger.warning("request validation failed on %s: %s", getattr(request, "url", "?"), exc)
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
  )
@@ -54,6 +54,7 @@ from shopping_cli.api.route_table import (
54
54
  _list_merchants,
55
55
  _list_products_exact,
56
56
  _merchant_conversations,
57
+ _merchant_token_status,
57
58
  _negotiation_abandon_claim,
58
59
  _negotiation_abandon_stale_claims,
59
60
  _negotiation_claim,
@@ -63,6 +64,8 @@ from shopping_cli.api.route_table import (
63
64
  _negotiation_pending_messages,
64
65
  _negotiation_snapshot,
65
66
  _negotiation_submit_decision,
67
+ _prepare_merchant_token_rotation,
68
+ _confirm_merchant_token_rotation,
66
69
  _recover_merchant_token,
67
70
  _record_tool_call_audit,
68
71
  _resolve_human_review,
@@ -166,6 +169,10 @@ def register_fastapi_routes(app: Any, db_path: str | Path) -> None:
166
169
  api_auth.payload_with_auth({}, authorization),
167
170
  )
168
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
+
169
176
  @app.post("/merchants/{merchant_id}/token/rotate")
170
177
  def rotate_merchant_token(
171
178
  merchant_id: str,
@@ -178,6 +185,14 @@ def register_fastapi_routes(app: Any, db_path: str | Path) -> None:
178
185
  api_auth.payload_with_auth(payload, authorization),
179
186
  )
180
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
+
181
196
  @app.post("/merchants/{merchant_id}/token/revoke")
182
197
  def revoke_merchant_tokens(
183
198
  merchant_id: str,
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from pathlib import Path
6
+ from datetime import datetime, timezone
6
7
  import hashlib
7
8
  import hmac
8
9
  import json
@@ -198,6 +199,124 @@ def rotate_merchant_token(
198
199
  return {"ok": True, "merchant_id": merchant_id, "merchant_token": token, "rotated": True}
199
200
 
200
201
 
202
+ def merchant_token_status(db_path: str | Path, merchant_id: str, payload: dict[str, Any]) -> dict[str, Any]:
203
+ """Return non-secret expiry metadata for the authenticated merchant token only."""
204
+ with db_session(db_path) as conn:
205
+ catalog.require_merchant(conn, merchant_id)
206
+ authenticated = token_service.require_merchant_token(conn, merchant_id, api_auth.payload_token(payload))
207
+ row = conn.execute(
208
+ "select token_prefix, created_at, expires_at from api_tokens where token_hash=? and merchant_id=? and role='merchant' and revoked_at=''",
209
+ (authenticated["token_hash"], merchant_id),
210
+ ).fetchone()
211
+ if row is None:
212
+ raise AuthError("invalid merchant token")
213
+ def utc_iso(value: str) -> str:
214
+ if not value:
215
+ return ""
216
+ parsed = datetime.fromisoformat(value)
217
+ return parsed.astimezone(timezone.utc).isoformat()
218
+ return {
219
+ "ok": True,
220
+ "merchant_id": merchant_id,
221
+ "token_prefix": str(row["token_prefix"] or ""),
222
+ "created_at": utc_iso(str(row["created_at"] or "")),
223
+ "expires_at": utc_iso(str(row["expires_at"] or "")),
224
+ "active": True,
225
+ }
226
+
227
+
228
+ def prepare_merchant_token_rotation(
229
+ db_path: str | Path, merchant_id: str, payload: dict[str, Any], require_admin_token: Any,
230
+ ) -> dict[str, Any]:
231
+ """Install a client-generated replacement alongside the caller's current token.
232
+
233
+ The caller must durably retain replacement_token before sending it. Only its
234
+ digest is stored; retrying the same rotation_id and token safely recovers the
235
+ pending status after a lost response.
236
+ """
237
+ from datetime import datetime, timedelta
238
+ from shopping_cli.core.tokens import token_digest, token_prefix
239
+
240
+ rotation_id = str(payload.get("rotation_id") or "")
241
+ replacement = str(payload.get("replacement_token") or "")
242
+ if not (22 <= len(rotation_id) <= 128) or not rotation_id.isascii() or not all(c.isalnum() or c in "_-" for c in rotation_id):
243
+ raise ValidationError("rotation_id must be 22-128 URL-safe characters")
244
+ if not replacement.startswith("shopping_merchant_") or len(replacement) < 48 or not replacement.isascii() or any(c.isspace() for c in replacement):
245
+ raise ValidationError("replacement_token is not a valid merchant credential")
246
+ with db_session(db_path) as conn:
247
+ conn.execute("begin immediate")
248
+ catalog.require_merchant(conn, merchant_id)
249
+ actor = "admin"
250
+ try:
251
+ require_admin_token(payload)
252
+ previous_hash = str(payload.get("previous_token_hash") or "")
253
+ if len(previous_hash) != 64 or any(c not in "0123456789abcdef" for c in previous_hash):
254
+ raise ValidationError("admin rotation requires previous_token_hash")
255
+ row = conn.execute("select token_hash from api_tokens where token_hash=? and merchant_id=? and role='merchant' and revoked_at=''", (previous_hash, merchant_id)).fetchone()
256
+ if row is None:
257
+ raise AuthError("previous merchant token is not active")
258
+ except AuthError:
259
+ caller = token_service.require_merchant_token(conn, merchant_id, api_auth.payload_token(payload))
260
+ previous_hash = str(caller["token_hash"])
261
+ actor = merchant_id
262
+ replacement_hash = token_digest(replacement)
263
+ existing = conn.execute("select * from merchant_token_rotations where rotation_id=?", (rotation_id,)).fetchone()
264
+ if existing is not None:
265
+ if existing["merchant_id"] != merchant_id or existing["previous_token_hash"] != previous_hash or existing["replacement_token_hash"] != replacement_hash:
266
+ raise ConflictError("rotation_id was already used for a different rotation")
267
+ if existing["status"] == "pending" and datetime.fromisoformat(existing["expires_at"]) <= datetime.now():
268
+ conn.execute("update merchant_token_rotations set status='expired' where rotation_id=? and status='pending'", (rotation_id,))
269
+ conn.execute("update api_tokens set revoked_at=? where token_hash=? and revoked_at=''", (now_iso(), replacement_hash))
270
+ return {"ok": True, "merchant_id": merchant_id, "rotation_id": rotation_id, "status": "expired", "recovery": "start a new rotation while the previous credential remains active"}
271
+ return {"ok": True, "merchant_id": merchant_id, "rotation_id": rotation_id, "status": existing["status"], "replacement_token_prefix": token_prefix(replacement)}
272
+ old = conn.execute("select token_hash from api_tokens where token_hash=? and merchant_id=? and role='merchant' and revoked_at=''", (previous_hash, merchant_id)).fetchone()
273
+ if old is None:
274
+ raise ConflictError("previous merchant credential is no longer active")
275
+ pending = conn.execute("select rotation_id from merchant_token_rotations where previous_token_hash=? and status='pending'", (previous_hash,)).fetchone()
276
+ if pending is not None:
277
+ raise ConflictError("a merchant token rotation is already pending for this credential")
278
+ collision = conn.execute("select merchant_id, role from api_tokens where token_hash=?", (replacement_hash,)).fetchone()
279
+ if collision is not None:
280
+ raise ConflictError("replacement credential already exists")
281
+ expires_at = (datetime.now() + timedelta(minutes=15)).replace(microsecond=0).isoformat()
282
+ token_service.store_merchant_token(conn, replacement, merchant_id)
283
+ conn.execute("insert into merchant_token_rotations(rotation_id,merchant_id,previous_token_hash,replacement_token_hash,status,expires_at,created_at) values(?,?,?,?,'pending',?,?)", (rotation_id, merchant_id, previous_hash, replacement_hash, expires_at, now_iso()))
284
+ token_service.append_agent_token_audit(conn, merchant_id, "merchant_token_rotation_prepared", {"rotation_id": rotation_id, "previous_token_hash_prefix": previous_hash[:24], "replacement_token_prefix": token_prefix(replacement), "expires_at": expires_at, "actor": actor})
285
+ return {"ok": True, "merchant_id": merchant_id, "rotation_id": rotation_id, "status": "pending", "replacement_token_prefix": token_prefix(replacement), "expires_at": expires_at}
286
+
287
+
288
+ def confirm_merchant_token_rotation(db_path: str | Path, merchant_id: str, payload: dict[str, Any]) -> dict[str, Any]:
289
+ from datetime import datetime
290
+ from shopping_cli.core.tokens import token_digest
291
+
292
+ rotation_id = str(payload.get("rotation_id") or "")
293
+ with db_session(db_path) as conn:
294
+ conn.execute("begin immediate")
295
+ catalog.require_merchant(conn, merchant_id)
296
+ caller = token_service.require_merchant_token(conn, merchant_id, api_auth.payload_token(payload))
297
+ replacement_hash = str(caller["token_hash"])
298
+ row = conn.execute("select * from merchant_token_rotations where rotation_id=? and merchant_id=?", (rotation_id, merchant_id)).fetchone()
299
+ if row is None or row["replacement_token_hash"] != replacement_hash:
300
+ raise AuthError("confirmation must be proved by the replacement credential")
301
+ if row["status"] == "confirmed":
302
+ return {"ok": True, "merchant_id": merchant_id, "rotation_id": rotation_id, "status": "confirmed", "revoked_previous": True}
303
+ if row["status"] != "pending":
304
+ raise ConflictError("rotation is no longer pending")
305
+ if datetime.fromisoformat(row["expires_at"]) <= datetime.now():
306
+ conn.execute("update merchant_token_rotations set status='expired' where rotation_id=? and status='pending'", (rotation_id,))
307
+ conn.execute("update api_tokens set revoked_at=? where token_hash=? and revoked_at=''", (now_iso(), replacement_hash))
308
+ return {"ok": True, "merchant_id": merchant_id, "rotation_id": rotation_id, "status": "expired", "revoked_previous": False}
309
+ confirmed_at = now_iso()
310
+ changed = conn.execute("update merchant_token_rotations set status='confirmed', confirmed_at=? where rotation_id=? and status='pending'", (confirmed_at, rotation_id))
311
+ if changed.rowcount != 1:
312
+ raise ConflictError("rotation was confirmed concurrently")
313
+ revoked = conn.execute("update api_tokens set revoked_at=? where token_hash=? and merchant_id=? and role='merchant' and revoked_at=''", (confirmed_at, row["previous_token_hash"], merchant_id))
314
+ if revoked.rowcount != 1:
315
+ raise ConflictError("previous credential changed during rotation")
316
+ token_service.append_agent_token_audit(conn, merchant_id, "merchant_token_rotation_confirmed", {"rotation_id": rotation_id, "previous_token_hash_prefix": row["previous_token_hash"][:24], "replacement_token_hash_prefix": str(caller["token_hash"])[:24]})
317
+ return {"ok": True, "merchant_id": merchant_id, "rotation_id": rotation_id, "status": "confirmed", "revoked_previous": True}
318
+
319
+
201
320
  def recover_merchant_token(
202
321
  db_path: str | Path,
203
322
  merchant_id: str,
@@ -30,12 +30,19 @@ from shopping_cli.services import tokens as token_service
30
30
  _ERP_SYNC_RATE_LIMIT_PER_MINUTE = 3
31
31
  _ERP_SYNC_WINDOW_SECONDS = 60
32
32
  _erp_sync_lock = threading.Lock()
33
+ # Bound process-local credential history; never evict an active limit.
34
+ _ERP_SYNC_BUCKET_CAP = 4096
33
35
  _erp_sync_buckets: dict[str, tuple[float, int]] = {}
34
36
 
35
37
 
36
38
  def _enforce_erp_sync_rate_limit(actor_key: str) -> None:
37
39
  now = time.monotonic()
38
40
  with _erp_sync_lock:
41
+ expired = [key for key, (start, _) in _erp_sync_buckets.items() if now - start >= _ERP_SYNC_WINDOW_SECONDS]
42
+ for key in expired:
43
+ del _erp_sync_buckets[key]
44
+ if actor_key not in _erp_sync_buckets and len(_erp_sync_buckets) >= _ERP_SYNC_BUCKET_CAP:
45
+ raise RateLimitError("rate limit credential capacity exhausted")
39
46
  window_start, count = _erp_sync_buckets.get(actor_key, (0.0, 0))
40
47
  if now - window_start >= _ERP_SYNC_WINDOW_SECONDS:
41
48
  window_start, count = now, 0
@@ -113,8 +120,20 @@ def sync_erp(db_path: str | Path, payload: dict[str, Any]) -> dict[str, Any]:
113
120
  default_merchant_id=default_merchant_id,
114
121
  allowed_merchant_id=allowed_merchant_id,
115
122
  )
123
+
124
+ def recheck_authorization(write_conn: sqlite3.Connection) -> None:
125
+ # Fetching releases the database writer. Recheck the authoritative
126
+ # credentials and merchant existence under the final write lock.
127
+ if is_admin:
128
+ api_auth.require_admin_token(payload)
129
+ if default_merchant_id:
130
+ require_merchant(write_conn, default_merchant_id)
131
+ else:
132
+ token_service.require_merchant_token(write_conn, allowed_merchant_id, api_auth.payload_token(payload))
133
+ require_merchant(write_conn, allowed_merchant_id)
134
+
116
135
  try:
117
- report = sync_erp_products(conn, config)
136
+ report = sync_erp_products(conn, config, before_write=recheck_authorization)
118
137
  except (ErpSourceError, OSError) as exc:
119
138
  # ERP 网络/结构失败统一 fail-closed 信封(200 + ok:false)
120
139
  return {"ok": False, "error": str(exc), "actor": actor}