Files
Jyotisha/scripts/ondemand_calc/contract.py
T
ClaudeandClaude Opus 5.5 c84d143088 fix(accept): #173 natal Moon is never the transit Moon; unknown ayanamsa blocks
transit_date counted house_from_moon from the transit Moon when the caller gave
no natal Moon; the natal reference is now only what the caller supplied.
resolve_profile now refuses an unsupported ayanamsa name instead of passing it
to the engine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-09 09:58:59 +08:00

296 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""按需计算共用合同:输出信封、输入校验、输入指纹(#173,2026-11-09)。
占星师 2026-11-07 Q9 / 2026-11-08 第五轮第 9 条:聊天要能按需求算指定日期行运等六类,
而且**岁差、交点、位置口径、地点、时区必须显式传入,不能让默认值替用户做选择**。
## 输出信封(所有按需工具返回同一个形状)
```
{
"schema": "jyotish.ondemand_calc.v1",
"tool": "<工具名>",
"calculation_status": "executed" | "partial" | "blocked",
"profile": {
"ayanamsa": "lahiri", # 实际生效
"node_mode": "mean", # mean | true
"position_mode": "apparent", # apparent | mean
"lat": 28.6139, "lon": 77.2090,
"tz": 5.5, # 小时数;给 timezone_id 时按当天换算
"timezone_id": null,
"location_source": "user_supplied" | "birth_place_fallback",
"profile_source": "caller_supplied" | "product_default_explicit",
"time_source": "caller_supplied" | "local_noon_default"
},
"requested": { ...调用方原样传入的参数... },
"input_fingerprint": "<sha256>",
"engine_version": "<字符串>",
"raw": { ...原始计算结果,不做解释性加工... },
"gaps": [{"field": "...", "reason": "..."}],
"computed_at_utc": "YYYY-MM-DDTHH:MM:SSZ"
}
```
规则:
1. **缺参数不猜默认值**:日期、地点、时区(`tz` 或 `timezone_id` 之一)、岁差缺任何一项,
都返回 `calculation_status = "blocked"` 并在 `gaps` 里点名缺哪一项;
`raw` 为空对象,不出现任何推断出来的日期。
2. **只有节点口径与位置口径有产品默认值**(产品负责人 2026-11-09 拍板:`mean` / `apparent`)。
调用方没传时用默认值,并在 `profile.profile_source` 写 `product_default_explicit`;
传了写 `caller_supplied`。不得写成「与本命同口径」。
3. **算不出来的口径要阻塞,不许偷偷换口径**:例如引擎现在只能算 `apparent`,
请求 `position_mode = "mean"` 时返回 `blocked`,`gaps` 写 `position_mode_unsupported`。
4. 失败信封里只能回显 `requested` 里调用方给的日期,不得出现任何推断的日期或时刻。
## 新工具怎么加(#174–#178 照做)
1. 在 `scripts/ondemand_calc/` 新建 `<tool>.py`,实现 `run(body: dict) -> dict`,
内部用 `validate_common(body)` 做公共校验、`resolve_profile(body)` 取口径、
`build_envelope(...)` 组装信封。工具自己的参数校验失败时抛 `OnDemandInputError`,
或者按本文件规则返回 `blocked` 信封。
2. 在 `registry.py` 的 `TOOLS` 里加一行:`"<tool>": <tool>_module.run`。
3. 工具的必填参数写进 `TOOLS` 旁的注释,并在 `PROGRESS` 里记一句。
前端接入(`frontend/src/mastra/ondemand-tools/`)等本骨架与「本命显式传口径」那单合完再另开单,
不要在这个包里引前端。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime, timedelta, timezone as dt_timezone
from typing import Any, Dict, List, Optional
SCHEMA = 'jyotish.ondemand_calc.v1'
ENGINE_VERSION = 'jyotish_engine.py'
# 产品负责人 2026-11-09 拍板:本命现在实际在用的就是这两个值。
PRODUCT_DEFAULT_NODE_MODE = 'mean'
PRODUCT_DEFAULT_POSITION_MODE = 'apparent'
NODE_MODES = ('mean', 'true')
POSITION_MODES = ('apparent', 'mean')
SUPPORTED_POSITION_MODES = ('apparent',) # 引擎目前只能算 apparent
MAX_RANGE_DAYS = 63
class OnDemandInputError(ValueError):
"""输入不合法。消息里点名出问题的字段,不补默认值。"""
def __init__(self, message: str, field: Optional[str] = None) -> None:
super().__init__(message)
self.field = field
def _gap(field: str, reason: str) -> Dict[str, str]:
return {'field': field, 'reason': reason}
def _require(body: Dict[str, Any], key: str) -> Any:
value = body.get(key)
if value is None or (isinstance(value, str) and not value.strip()):
raise OnDemandInputError(f'missing required field: {key}', key)
return value
def _number(value: Any, field: str, low: float, high: float) -> float:
try:
number = float(value)
except (TypeError, ValueError) as exc:
raise OnDemandInputError(f'{field} must be a number', field) from exc
if number < low or number > high:
raise OnDemandInputError(f'{field} must be between {low} and {high}', field)
return number
def parse_date(value: Any, field: str = 'date') -> datetime:
try:
return datetime.strptime(str(value)[:10], '%Y-%m-%d')
except ValueError as exc:
raise OnDemandInputError(f'{field} must be YYYY-MM-DD', field) from exc
def parse_time(value: Any) -> Optional[str]:
if value is None or value == '':
return None
text = str(value).strip()
parts = text.split(':')
if len(parts) != 2:
raise OnDemandInputError('time must be HH:MM', 'time')
try:
hour, minute = int(parts[0]), int(parts[1])
except ValueError as exc:
raise OnDemandInputError('time must be HH:MM', 'time') from exc
if not (0 <= hour <= 23 and 0 <= minute <= 59):
raise OnDemandInputError('time must be HH:MM', 'time')
return f'{hour:02d}:{minute:02d}'
def offset_hours(day: datetime, tz: Optional[float], timezone_id: Optional[str]) -> float:
"""当地 UTC 偏移。给了 timezone_id 就按那一天换算,夏令时自动生效。"""
if timezone_id:
try:
from zoneinfo import ZoneInfo
except ImportError as exc: # pragma: no cover - Python < 3.9
raise OnDemandInputError('timezone_id needs Python 3.9+ zoneinfo', 'timezone_id') from exc
try:
zone = ZoneInfo(str(timezone_id))
except Exception as exc: # noqa: BLE001 - 未知时区名就是输入错误
raise OnDemandInputError(f'unknown timezone_id: {timezone_id}', 'timezone_id') from exc
local_noon = datetime(day.year, day.month, day.day, 12, 0, tzinfo=zone)
offset = local_noon.utcoffset()
if offset is None: # pragma: no cover
raise OnDemandInputError(f'unknown timezone_id: {timezone_id}', 'timezone_id')
return offset.total_seconds() / 3600.0
return float(tz) # type: ignore[arg-type]
def validate_common(body: Dict[str, Any]) -> Dict[str, Any]:
"""公共参数:日期、地点、时区。缺任何一项都抛 OnDemandInputError(由调用方转成 blocked 信封)。"""
if not isinstance(body, dict):
raise OnDemandInputError('body must be an object')
date = parse_date(_require(body, 'date'), 'date')
place = body.get('place') if isinstance(body.get('place'), dict) else body
lat_value = place.get('lat', body.get('lat'))
lon_value = place.get('lon', body.get('lon'))
if lat_value is None:
raise OnDemandInputError('missing required field: lat', 'lat')
if lon_value is None:
raise OnDemandInputError('missing required field: lon', 'lon')
lat = _number(lat_value, 'lat', -90.0, 90.0)
lon = _number(lon_value, 'lon', -180.0, 180.0)
tz_value = place.get('tz', body.get('tz'))
timezone_id = place.get('timezone_id', body.get('timezone_id'))
if tz_value is None and not timezone_id:
raise OnDemandInputError('missing required field: tz or timezone_id', 'tz')
tz = None if tz_value is None else _number(tz_value, 'tz', -12.0, 14.0)
return {
'date': date,
'lat': lat,
'lon': lon,
'tz': tz,
'timezone_id': str(timezone_id) if timezone_id else None,
}
def resolve_profile(body: Dict[str, Any], common: Dict[str, Any]) -> Dict[str, Any]:
"""口径:岁差必填;节点与位置口径缺省用产品默认值并如实标记来源。"""
ayanamsa_value = _require(body, 'ayanamsa')
ayanamsa = str(ayanamsa_value).strip().lower()
# 验收修正:不认识的岁差名不得交给引擎静默换成别的岁差。
try:
from scripts.ayanamsa_utils import is_supported_ayanamsa_name, normalize_ayanamsa_name
except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution
from ayanamsa_utils import is_supported_ayanamsa_name, normalize_ayanamsa_name
if not is_supported_ayanamsa_name(ayanamsa):
raise OnDemandInputError(f'unknown ayanamsa: {ayanamsa_value}', 'ayanamsa')
ayanamsa = normalize_ayanamsa_name(ayanamsa)
node_mode_value = body.get('node_mode')
position_mode_value = body.get('position_mode')
profile_source = 'product_default_explicit' if node_mode_value is None or position_mode_value is None else 'caller_supplied'
node_mode = str(node_mode_value).strip().lower() if node_mode_value is not None else PRODUCT_DEFAULT_NODE_MODE
position_mode = str(position_mode_value).strip().lower() if position_mode_value is not None else PRODUCT_DEFAULT_POSITION_MODE
if node_mode not in NODE_MODES:
raise OnDemandInputError('node_mode must be mean or true', 'node_mode')
if position_mode not in POSITION_MODES:
raise OnDemandInputError('position_mode must be apparent or mean', 'position_mode')
tz = offset_hours(common['date'], common['tz'], common['timezone_id'])
return {
'ayanamsa': ayanamsa,
'node_mode': node_mode,
'position_mode': position_mode,
'lat': common['lat'],
'lon': common['lon'],
'tz': tz,
'timezone_id': common['timezone_id'],
'location_source': 'user_supplied',
'profile_source': profile_source,
'time_source': 'caller_supplied',
}
def normalized_requested(body: Dict[str, Any]) -> Dict[str, Any]:
"""指纹里用的规范化输入:键排序、浮点固定小数位。"""
def clean(value: Any) -> Any:
if isinstance(value, float):
return round(value, 6)
if isinstance(value, dict):
return {str(key): clean(item) for key, item in sorted(value.items())}
if isinstance(value, list):
return [clean(item) for item in value]
return value
return clean({key: value for key, value in body.items() if value is not None})
def input_fingerprint(requested: Dict[str, Any], profile: Dict[str, Any]) -> str:
payload = {
'requested': normalized_requested(requested),
'profile': {key: profile.get(key) for key in ('ayanamsa', 'node_mode', 'position_mode', 'lat', 'lon', 'tz', 'timezone_id')},
'engine_version': ENGINE_VERSION,
}
canonical = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(',', ':'))
return hashlib.sha256(canonical.encode('utf-8')).hexdigest()
def build_envelope(
*,
tool: str,
requested: Dict[str, Any],
profile: Optional[Dict[str, Any]],
status: str,
raw: Optional[Dict[str, Any]] = None,
gaps: Optional[List[Dict[str, str]]] = None,
time_source: str = 'caller_supplied',
) -> Dict[str, Any]:
fingerprint_profile = profile or {
'ayanamsa': requested.get('ayanamsa'),
'node_mode': requested.get('node_mode', PRODUCT_DEFAULT_NODE_MODE),
'position_mode': requested.get('position_mode', PRODUCT_DEFAULT_POSITION_MODE),
'lat': requested.get('lat'),
'lon': requested.get('lon'),
'tz': requested.get('tz'),
'timezone_id': requested.get('timezone_id'),
}
envelope_profile = None if profile is None else {**profile, 'time_source': time_source}
return {
'schema': SCHEMA,
'tool': tool,
'calculation_status': status,
'profile': envelope_profile,
'requested': dict(requested),
'input_fingerprint': input_fingerprint(requested, fingerprint_profile),
'engine_version': ENGINE_VERSION,
'raw': {} if raw is None else raw,
'gaps': list(gaps or []),
'computed_at_utc': datetime.now(dt_timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
}
def blocked_envelope(
*,
tool: str,
body: Dict[str, Any],
error: OnDemandInputError,
) -> Dict[str, Any]:
"""输入不合法:只回显调用方给的日期与参数,不推断任何日期。"""
requested = dict(body) if isinstance(body, dict) else {}
return build_envelope(
tool=tool,
requested=requested,
profile=None,
status='blocked',
raw={},
gaps=[_gap(error.field or 'input', str(error))],
)
def jd_for_local(day: datetime, local_hours: float, tz: float) -> float:
"""当地时刻 → Julian Day(UT)。"""
utc_hours = local_hours - tz
base = datetime(day.year, day.month, day.day) + timedelta(hours=utc_hours)
return _julday(base)
def _julday(moment: datetime) -> float: # pragma: no cover - 由测试经公共 API 覆盖
import swisseph as swe
return swe.julday(moment.year, moment.month, moment.day, moment.hour + moment.minute / 60.0 + moment.second / 3600.0)