Circular-safe JSON-able projection. Strings get system-reminder blocks stripped (NOT the broader internal-text tags — matches TS ``safeJsonValue``).
(value: Any, seen: Optional[set] = None)
| 134 | |
| 135 | |
| 136 | def safe_json_value(value: Any, seen: Optional[set] = None) -> Any: |
| 137 | """Circular-safe JSON-able projection. Strings get system-reminder blocks |
| 138 | stripped (NOT the broader internal-text tags — matches TS ``safeJsonValue``). |
| 139 | """ |
| 140 | if seen is None: |
| 141 | seen = set() |
| 142 | |
| 143 | if value is None or isinstance(value, (str, int, float, bool)): |
| 144 | if isinstance(value, str): |
| 145 | return strip_system_reminder_blocks(value) |
| 146 | return value |
| 147 | |
| 148 | if isinstance(value, (list, tuple)): |
| 149 | if id(value) in seen: |
| 150 | return "[Circular]" |
| 151 | seen.add(id(value)) |
| 152 | try: |
| 153 | return [safe_json_value(item, seen) for item in value] |
| 154 | except Exception: |
| 155 | return "[Unserializable]" |
| 156 | finally: |
| 157 | seen.discard(id(value)) |
| 158 | |
| 159 | if isinstance(value, Mapping): |
| 160 | if id(value) in seen: |
| 161 | return "[Circular]" |
| 162 | seen.add(id(value)) |
| 163 | try: |
| 164 | result: dict[str, Any] = {} |
| 165 | try: |
| 166 | keys = list(value.keys()) |
| 167 | except Exception: |
| 168 | return "[Unserializable]" |
| 169 | for key in keys: |
| 170 | try: |
| 171 | result[key] = safe_json_value(value[key], seen) |
| 172 | except Exception: |
| 173 | result[key] = "[Unserializable]" |
| 174 | return result |
| 175 | finally: |
| 176 | seen.discard(id(value)) |
| 177 | |
| 178 | if is_dataclass(value) and not isinstance(value, type): |
| 179 | return safe_json_value(content_block_to_dict(value), seen) |
| 180 | |
| 181 | return str(value) |
| 182 | |
| 183 | |
| 184 | def safe_stringify(value: Any, indent: Optional[int] = None) -> str: |
no test coverage detected