fusion-artifacts-engine 0.7.18__py3-none-any.whl

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. fusion_artifacts_engine/__init__.py +0 -0
  2. fusion_artifacts_engine/__main__.py +263 -0
  3. fusion_artifacts_engine/ai_client.py +54 -0
  4. fusion_artifacts_engine/auto_identifier.py +148 -0
  5. fusion_artifacts_engine/compactor.py +164 -0
  6. fusion_artifacts_engine/config.py +462 -0
  7. fusion_artifacts_engine/default_config.yaml +144 -0
  8. fusion_artifacts_engine/dsl_parser.py +231 -0
  9. fusion_artifacts_engine/engine.py +1372 -0
  10. fusion_artifacts_engine/gateway_client.py +396 -0
  11. fusion_artifacts_engine/ipc_consumer.py +321 -0
  12. fusion_artifacts_engine/long_context.py +392 -0
  13. fusion_artifacts_engine/metrics.py +144 -0
  14. fusion_artifacts_engine/models.py +168 -0
  15. fusion_artifacts_engine/office_ingest.py +365 -0
  16. fusion_artifacts_engine/rate_limiter.py +82 -0
  17. fusion_artifacts_engine/ref_parser.py +77 -0
  18. fusion_artifacts_engine/render.py +184 -0
  19. fusion_artifacts_engine/rpc/__init__.py +0 -0
  20. fusion_artifacts_engine/rpc/errors.py +61 -0
  21. fusion_artifacts_engine/rpc/event_bus.py +95 -0
  22. fusion_artifacts_engine/rpc/methods.py +1365 -0
  23. fusion_artifacts_engine/rpc/server.py +1279 -0
  24. fusion_artifacts_engine/section_index.py +189 -0
  25. fusion_artifacts_engine/share.py +326 -0
  26. fusion_artifacts_engine/storage/__init__.py +0 -0
  27. fusion_artifacts_engine/storage/base.py +270 -0
  28. fusion_artifacts_engine/storage/sqlite_storage.py +2813 -0
  29. fusion_artifacts_engine/token_budget.py +119 -0
  30. fusion_artifacts_engine/token_counter.py +80 -0
  31. fusion_artifacts_engine/tracing.py +132 -0
  32. fusion_artifacts_engine/utils.py +170 -0
  33. fusion_artifacts_engine/visual_dispatcher.py +135 -0
  34. fusion_artifacts_engine/visual_error_boundary.py +52 -0
  35. fusion_artifacts_engine/visual_primitives/__init__.py +34 -0
  36. fusion_artifacts_engine/visual_primitives/array_grid.py +66 -0
  37. fusion_artifacts_engine/visual_primitives/base.py +79 -0
  38. fusion_artifacts_engine/visual_primitives/bucket_divider.py +66 -0
  39. fusion_artifacts_engine/visual_primitives/data_chart.py +65 -0
  40. fusion_artifacts_engine/visual_primitives/flow_card.py +101 -0
  41. fusion_artifacts_engine/visual_primitives/geometry_2d.py +80 -0
  42. fusion_artifacts_engine/visual_primitives/isometric_3d.py +82 -0
  43. fusion_artifacts_engine/visual_primitives/tape_diagram.py +58 -0
  44. fusion_artifacts_engine/visual_primitives/track_timeline.py +58 -0
  45. fusion_artifacts_engine/webui_dist/assets/abnfDiagram-WEYOIA3C-2ebtMp5N.js +1 -0
  46. fusion_artifacts_engine/webui_dist/assets/architectureDiagram-ZHVYKT53-COvSzFYy.js +36 -0
  47. fusion_artifacts_engine/webui_dist/assets/blockDiagram-RJAE7QA3-CsO2Iy8b.js +140 -0
  48. fusion_artifacts_engine/webui_dist/assets/c4Diagram-XDPPPE54-dFggQosH.js +38 -0
  49. fusion_artifacts_engine/webui_dist/assets/channel-BXYZthxM.js +1 -0
  50. fusion_artifacts_engine/webui_dist/assets/chunk-2E7WHVMD-B93QdjG6.js +88 -0
  51. fusion_artifacts_engine/webui_dist/assets/chunk-2Q5K7J3B-DHEJLJup.js +1 -0
  52. fusion_artifacts_engine/webui_dist/assets/chunk-4EMNKR2T-OGUUH-PY.js +1 -0
  53. fusion_artifacts_engine/webui_dist/assets/chunk-55XCU76K-CKbux1-g.js +1 -0
  54. fusion_artifacts_engine/webui_dist/assets/chunk-5VM5RSS4-CPHhHyIF.js +15 -0
  55. fusion_artifacts_engine/webui_dist/assets/chunk-JWPE2WC7-CJSxuarC.js +1 -0
  56. fusion_artifacts_engine/webui_dist/assets/chunk-VQ5W62QI-LHItmtfv.js +1 -0
  57. fusion_artifacts_engine/webui_dist/assets/chunk-XXDRQBXY-BRYBW56M.js +1 -0
  58. fusion_artifacts_engine/webui_dist/assets/chunk-ZCHMQSOR-cGbkforM.js +2 -0
  59. fusion_artifacts_engine/webui_dist/assets/classDiagram-v2-4MYWR3UA-RVdXT7ne.js +217 -0
  60. fusion_artifacts_engine/webui_dist/assets/cose-bilkent-JH36ORCC-C1hy4K0b.js +1 -0
  61. fusion_artifacts_engine/webui_dist/assets/cynefin-EF2NZ3EQ-D8ytFvIy.js +141 -0
  62. fusion_artifacts_engine/webui_dist/assets/cynefinDiagram-WF24UDRP-9iOV04Va.js +62 -0
  63. fusion_artifacts_engine/webui_dist/assets/cytoscape.esm-BLAcgzS2.js +331 -0
  64. fusion_artifacts_engine/webui_dist/assets/dagre-NK4GIZVX-zE4dzUJh.js +4 -0
  65. fusion_artifacts_engine/webui_dist/assets/defaultLocale-5voVPcsN.js +1 -0
  66. fusion_artifacts_engine/webui_dist/assets/diagram-CBK3MWTC-BrXmQtKM.js +24 -0
  67. fusion_artifacts_engine/webui_dist/assets/diagram-I5XIIV2D-Bctxj8zx.js +24 -0
  68. fusion_artifacts_engine/webui_dist/assets/diagram-ODIL2UCW-DfDzzeod.js +30 -0
  69. fusion_artifacts_engine/webui_dist/assets/diagram-PFBEJUXE-BGZKfFXu.js +3 -0
  70. fusion_artifacts_engine/webui_dist/assets/diagram-RJA3I4VV-CXB6A2jx.js +41 -0
  71. fusion_artifacts_engine/webui_dist/assets/diagram-TYUNFSNR-gfqyjmIj.js +200 -0
  72. fusion_artifacts_engine/webui_dist/assets/ebnfDiagram-V4P3TTPT-CZ1BZkcl.js +1 -0
  73. fusion_artifacts_engine/webui_dist/assets/elk-QONTBCTQ-C5YzS41r.js +27 -0
  74. fusion_artifacts_engine/webui_dist/assets/erDiagram-KYQIGQAA-B-DYTd4O.js +99 -0
  75. fusion_artifacts_engine/webui_dist/assets/flowDiagram-IUGLLWBU-IRAKfxcJ.js +213 -0
  76. fusion_artifacts_engine/webui_dist/assets/ganttDiagram-R7GPNTJY-DRdmsg6i.js +292 -0
  77. fusion_artifacts_engine/webui_dist/assets/gitGraphDiagram-PDYL7XHY-B0QL_KrV.js +106 -0
  78. fusion_artifacts_engine/webui_dist/assets/graph-Bn3Yngep.js +1 -0
  79. fusion_artifacts_engine/webui_dist/assets/index-CCsQ6nhB.js +374 -0
  80. fusion_artifacts_engine/webui_dist/assets/index-Cw23dyL1.css +1 -0
  81. fusion_artifacts_engine/webui_dist/assets/infoDiagram-MVDRKAX5-DMlVkZRb.js +2 -0
  82. fusion_artifacts_engine/webui_dist/assets/init-DDsq4BXF.js +1 -0
  83. fusion_artifacts_engine/webui_dist/assets/ishikawaDiagram-HPEHV2GE-yZW7Bvw7.js +70 -0
  84. fusion_artifacts_engine/webui_dist/assets/journeyDiagram-BOSHW7O7-C0UaOGz2.js +139 -0
  85. fusion_artifacts_engine/webui_dist/assets/kanban-definition-FNSA4HC5-D2VjWSCv.js +89 -0
  86. fusion_artifacts_engine/webui_dist/assets/katex-Be3d8Y4U.js +257 -0
  87. fusion_artifacts_engine/webui_dist/assets/linear-B0L4ZWGd.js +1 -0
  88. fusion_artifacts_engine/webui_dist/assets/mermaid.core-C0Fw4Tzk.js +314 -0
  89. fusion_artifacts_engine/webui_dist/assets/mindmap-definition-6OY57UG3-Dy3WTB5p.js +98 -0
  90. fusion_artifacts_engine/webui_dist/assets/ordinal-_ShbN0yz.js +1 -0
  91. fusion_artifacts_engine/webui_dist/assets/pegDiagram-ECIUJNBX-Cdm0XnAV.js +1 -0
  92. fusion_artifacts_engine/webui_dist/assets/pieDiagram-GNMPY74T-TrdpBRYl.js +39 -0
  93. fusion_artifacts_engine/webui_dist/assets/quadrantDiagram-D57K4MC3-N1OmHTjQ.js +7 -0
  94. fusion_artifacts_engine/webui_dist/assets/railroadDiagram-Y72NRBL7-DhZcDSX6.js +1 -0
  95. fusion_artifacts_engine/webui_dist/assets/requirementDiagram-EQYSW5RA-CGmfo0LK.js +84 -0
  96. fusion_artifacts_engine/webui_dist/assets/sankeyDiagram-SY24JHO5-CnAXR6RI.js +40 -0
  97. fusion_artifacts_engine/webui_dist/assets/sequenceDiagram-BLEHNHQU-Divp82Qv.js +169 -0
  98. fusion_artifacts_engine/webui_dist/assets/sizeCapture-INFHLROL-BxUSO2gs.js +1 -0
  99. fusion_artifacts_engine/webui_dist/assets/stateDiagram-v2-A6IESKWZ-Ch2o3gee.js +291 -0
  100. fusion_artifacts_engine/webui_dist/assets/swimlanes-B3ENRKFQ-CBnYOtut.js +1 -0
  101. fusion_artifacts_engine/webui_dist/assets/swimlanesDiagram-AYQRV4AK-Bdp49byx.js +8 -0
  102. fusion_artifacts_engine/webui_dist/assets/timeline-definition-JXYKGLGB-Cp8DPlck.js +120 -0
  103. fusion_artifacts_engine/webui_dist/assets/usecaseDiagram-WPOLBNNX-CcF_Y4cE.js +370 -0
  104. fusion_artifacts_engine/webui_dist/assets/vennDiagram-Q3Y3IDCW-Dplzp3gZ.js +34 -0
  105. fusion_artifacts_engine/webui_dist/assets/wardleyDiagram-IVAIDKWA-fKoKxoZw.js +78 -0
  106. fusion_artifacts_engine/webui_dist/assets/xychartDiagram-4URNHDU4-DRVZF7Gc.js +7 -0
  107. fusion_artifacts_engine/webui_dist/favicon.svg +1 -0
  108. fusion_artifacts_engine/webui_dist/index.html +14 -0
  109. fusion_artifacts_engine-0.7.18.dist-info/METADATA +1115 -0
  110. fusion_artifacts_engine-0.7.18.dist-info/RECORD +114 -0
  111. fusion_artifacts_engine-0.7.18.dist-info/WHEEL +5 -0
  112. fusion_artifacts_engine-0.7.18.dist-info/entry_points.txt +2 -0
  113. fusion_artifacts_engine-0.7.18.dist-info/licenses/LICENSE +201 -0
  114. fusion_artifacts_engine-0.7.18.dist-info/top_level.txt +1 -0
File without changes
@@ -0,0 +1,263 @@
1
+ import argparse
2
+ import logging
3
+ import signal
4
+ import sys
5
+ import threading
6
+ import time
7
+ from pathlib import Path
8
+
9
+ from fusion_artifacts_engine.config import load_config
10
+ from fusion_artifacts_engine.engine import ArtifactEngine
11
+ from fusion_artifacts_engine.rpc.server import ArtifactRPCServer
12
+ from fusion_artifacts_engine.utils import get_package_version, setup_logging
13
+
14
+ # User instruction: "Every project must have a config file; config belongs in the config file, never hardcoded in code"
15
+ # Importers/callers: CLI entry point, calls load_config() from config.py, passes config to ArtifactEngine and ArtifactRPCServer
16
+ # Affected API: argparse --host/--port/--config flags; status command reads config instead of hardcoded URL
17
+ # Data schemas: ArtifactEngineConfig with server_host/server_port fields
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ def _set_process_title(title: str) -> None:
23
+ # #68: on macOS homebrew Python, comm shows bare "Python" and operators cannot tell products apart.
24
+ # Prefer fusion_core.proc (shared helper); fall back to a direct setproctitle import
25
+ # when fusion_core is missing (isolated CI); if both are missing, skip silently (acceptance #3: fallback safe).
26
+ try:
27
+ from fusion_core.proc import set_process_title
28
+
29
+ set_process_title(title)
30
+ return
31
+ except ImportError:
32
+ pass
33
+ except Exception as e: # noqa: BLE001
34
+ logger.debug("fusion_core set_process_title failed: %s", e)
35
+ try:
36
+ import setproctitle
37
+
38
+ setproctitle.setproctitle(title)
39
+ except ImportError:
40
+ logger.debug("setproctitle not installed, process title stays default (pip install '.[proc]')")
41
+ except Exception as e: # noqa: BLE001
42
+ logger.debug("setproctitle failed, process title stays default: %s", e)
43
+
44
+
45
+ def _run_once(config, host, port) -> int:
46
+ # P0-8: single engine run, returns an exit code. 0=graceful stop, non-0=crash (watch loop restarts on it).
47
+ # P2-5: configure OTel tracing from config at startup (optional; no SDK or enabled=false → no-op).
48
+ import fusion_artifacts_engine.tracing as tracing
49
+
50
+ tracing.configure_tracing(config.tracing_enabled, config.tracing_service_name)
51
+ engine = ArtifactEngine(config)
52
+ server = ArtifactRPCServer(engine, host=host, port=port)
53
+
54
+ # #84: fusion-design [Save to Artifacts] file-IPC consumer. Runs within the engine lifecycle;
55
+ # rebuilt around the new engine after watch restart (consumer holds an engine reference).
56
+ ipc_consumer = None
57
+ if getattr(config, "ipc_enabled", True):
58
+ from fusion_artifacts_engine.ipc_consumer import DesignIPCConsumer
59
+
60
+ try:
61
+ ipc_consumer = DesignIPCConsumer(
62
+ engine, config.ipc_design_path, config.ipc_poll_interval
63
+ )
64
+ ipc_consumer.start()
65
+ except Exception as e: # noqa: BLE001
66
+ logger.warning("design IPC consumer start failed (non-fatal): %s", e)
67
+ ipc_consumer = None
68
+
69
+ # v0.7.0: fusion-office file ingest (read path) + .outbox write-back dir. Also non-fatal.
70
+ office_consumer = None
71
+ if getattr(config, "ipc_enabled", True) and getattr(config, "ipc_office_enabled", True):
72
+ from fusion_artifacts_engine.ipc_consumer import OfficeIPCConsumer
73
+
74
+ try:
75
+ office_consumer = OfficeIPCConsumer(
76
+ engine, config.ipc_office_path, config.ipc_poll_interval
77
+ )
78
+ office_consumer.start()
79
+ except Exception as e: # noqa: BLE001
80
+ logger.warning("office IPC consumer start failed (non-fatal): %s", e)
81
+ office_consumer = None
82
+
83
+ # C-13: calling shutdown() from a signal handler on the same thread that runs serve_forever deadlocks
84
+ # (socketserver docs forbid same-thread shutdown). Instead start_async runs the server on a background
85
+ # thread while the main thread blocks on threading.Event; the signal handler sets the Event, the main
86
+ # thread wakes up and stops.
87
+ stop_event = threading.Event()
88
+ graceful = {"yes": False}
89
+
90
+ def shutdown(sig, frame):
91
+ logger.info("Received signal %s, shutting down", sig)
92
+ graceful["yes"] = True
93
+ stop_event.set()
94
+
95
+ if threading.current_thread() is threading.main_thread():
96
+ signal.signal(signal.SIGINT, shutdown)
97
+ signal.signal(signal.SIGTERM, shutdown)
98
+ else:
99
+ logger.warning(
100
+ "Not main thread, skip signal handlers (SIGINT/SIGTERM won't stop daemon)"
101
+ )
102
+
103
+ logger.info("fusion-artifacts-engine starting...")
104
+ server.start_async()
105
+ code = 0
106
+ try:
107
+ stop_event.wait()
108
+ except KeyboardInterrupt:
109
+ graceful["yes"] = True
110
+ except Exception as e: # noqa: BLE001
111
+ logger.exception("engine crashed: %s", e)
112
+ code = 1
113
+ finally:
114
+ try:
115
+ if office_consumer is not None:
116
+ office_consumer.stop()
117
+ if ipc_consumer is not None:
118
+ ipc_consumer.stop()
119
+ server.stop()
120
+ engine.close()
121
+ except Exception as e: # noqa: BLE001
122
+ logger.exception("error during shutdown: %s", e)
123
+ code = 1
124
+ try:
125
+ tracing.shutdown()
126
+ except Exception as e: # noqa: BLE001
127
+ logger.debug("tracing shutdown: %s", e)
128
+ logger.info("fusion-artifacts-engine stopped")
129
+ if not graceful["yes"]:
130
+ code = 1
131
+ return code
132
+
133
+
134
+ def main():
135
+ parser = argparse.ArgumentParser(prog="fusion-artifacts-engine")
136
+ sub = parser.add_subparsers(dest="command")
137
+
138
+ start_parser = sub.add_parser("start", help="Start the artifact engine daemon")
139
+ start_parser.add_argument("--host", default=None)
140
+ start_parser.add_argument("--port", type=int, default=None)
141
+ start_parser.add_argument("--storage-root", default=None)
142
+ start_parser.add_argument("--config", default=None, help="Path to config YAML file")
143
+ # P0-8: automatic crash restart. If the engine exits abnormally (non-0), restart after backoff seconds;
144
+ # SIGTERM/SIGINT graceful stop (stop_event set) returns 0 and the watch loop stops restarting.
145
+ start_parser.add_argument(
146
+ "--watch", action="store_true",
147
+ help="Restart daemon on crash (backoff between restarts)",
148
+ )
149
+ start_parser.add_argument(
150
+ "--restart-backoff", type=float, default=3.0,
151
+ help="Seconds to wait between crash restarts (default 3.0)",
152
+ )
153
+
154
+ sub.add_parser("status", help="Check if daemon is running")
155
+ sub.add_parser("version", help="Print version")
156
+
157
+ args = parser.parse_args()
158
+
159
+ if args.command == "start":
160
+ setup_logging(logging.INFO)
161
+ user_config = Path(args.config) if args.config else None
162
+ config = load_config(user_config_path=user_config)
163
+
164
+ if args.storage_root:
165
+ config.storage_root = Path(args.storage_root)
166
+ host = args.host or config.server_host
167
+ port = args.port or config.server_port
168
+
169
+ # #68: set the process title to the product name so ps/Activity Monitor no longer shows bare "Python".
170
+ # Outside the watch loop — restarts do not change the port, no need to set it again.
171
+ _set_process_title(f"fusion-artifacts-engine serve :{port}")
172
+
173
+ # #75: web-shell integration. When enabled, self-registers the manifest to fusion-gateway + heartbeat.
174
+ # Register/heartbeat threads are independent of the engine lifecycle (watch restarts do not re-register).
175
+ gateway_client = None
176
+ if config.gateway_enabled:
177
+ from fusion_artifacts_engine.gateway_client import GatewayClient
178
+
179
+ gateway_client = GatewayClient(config, host, port)
180
+ try:
181
+ gateway_client.start()
182
+ except Exception as e: # noqa: BLE001
183
+ # Hardening surface: gateway unreachable must not block engine startup
184
+ logger.warning("gateway client start failed (non-fatal): %s", e)
185
+ gateway_client = None
186
+
187
+ # P1-1/H4: rate-limit production warning. rps==0 means unlimited — unthrottled in production, explicit WARN at startup.
188
+ # default_config.yaml already sets production defaults (rps:200/burst:400, public_rps:50/burst:100),
189
+ # but user configs or test environments may fall back to 0; this is the safety-net warning.
190
+ if config.rate_limit_rps == 0:
191
+ logger.warning(
192
+ "rate_limit.rps=0 (unlimited) — JSON-RPC/REST endpoints unthrottled; "
193
+ "set rate_limit.rps>0 in production"
194
+ )
195
+ if config.public_rate_limit_rps == 0:
196
+ logger.warning(
197
+ "rate_limit.public_rps=0 (unlimited) — public share endpoints unthrottled; "
198
+ "set rate_limit.public_rps>0 in production"
199
+ )
200
+
201
+ # P0-8: watch loop wraps a single run. With --watch, a non-0 engine exit code restarts after backoff.
202
+ # Exit code 0 (graceful stop) breaks out of the loop. A single run includes signal registration and stop_event logic.
203
+ try:
204
+ while True:
205
+ code = _run_once(config, host, port)
206
+ if not getattr(args, "watch", False):
207
+ sys.exit(code)
208
+ if code == 0:
209
+ logger.info("watch: engine exited 0 (graceful), watcher exiting")
210
+ sys.exit(0)
211
+ backoff = getattr(args, "restart_backoff", 3.0)
212
+ logger.warning("watch: engine crashed (code=%s), restart in %ss", code, backoff)
213
+ time.sleep(backoff)
214
+ finally:
215
+ if gateway_client is not None:
216
+ try:
217
+ gateway_client.stop()
218
+ except Exception as e: # noqa: BLE001
219
+ logger.debug("gateway client stop: %s", e)
220
+
221
+ elif args.command == "status":
222
+ import os
223
+
224
+ import httpx
225
+
226
+ config = load_config()
227
+ host = config.server_host
228
+ port = config.server_port
229
+ headers = {}
230
+ # C-4 precedence, same as rpc/server.py: env first (runtime rotation),
231
+ # then config.api_key — otherwise a bare `status` pings unauthenticated
232
+ # and misreports a healthy daemon as not running (start.sh probe bug class)
233
+ api_key = os.environ.get("FUSION_ARTIFACTS_API_KEY", "") or (config.api_key or "")
234
+ if api_key:
235
+ headers["X-API-Key"] = api_key
236
+ healthy = False
237
+ try:
238
+ resp = httpx.post(
239
+ f"http://{host}:{port}",
240
+ json={"jsonrpc": "2.0", "method": "ping", "id": 1},
241
+ headers=headers,
242
+ timeout=3.0,
243
+ )
244
+ data = resp.json()
245
+ if "result" in data and data["result"].get("pong"):
246
+ healthy = True
247
+ print(f"Running: version={data['result'].get('version', 'unknown')}")
248
+ else:
249
+ print("Not running or error")
250
+ except Exception as e: # noqa: BLE001
251
+ print(f"Not running: {e}")
252
+ # L-20: health-check exit code — 0 healthy, 1 not running; start.sh relies on $?
253
+ sys.exit(0 if healthy else 1)
254
+
255
+ elif args.command == "version":
256
+ print(f"fusion-artifacts-engine {get_package_version()}")
257
+
258
+ else:
259
+ parser.print_help()
260
+
261
+
262
+ if __name__ == "__main__":
263
+ main()
@@ -0,0 +1,54 @@
1
+ import logging
2
+
3
+ import httpx
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ DEFAULT_BASE_URL = "http://127.0.0.1:11434"
8
+
9
+
10
+ async def list_models(
11
+ base_url: str, timeout: float = 10.0, api_key: str | None = None
12
+ ) -> list[str]:
13
+ headers = {}
14
+ if api_key:
15
+ headers["Authorization"] = f"Bearer {api_key}"
16
+ async with httpx.AsyncClient(timeout=timeout) as client:
17
+ resp = await client.get(f"{base_url.rstrip('/')}/v1/models", headers=headers)
18
+ resp.raise_for_status()
19
+ data = resp.json()
20
+ models = [m.get("id") for m in data.get("data", []) if m.get("id")]
21
+ logger.info("Listed models from %s: %d available", base_url, len(models))
22
+ return models
23
+
24
+
25
+ async def chat(
26
+ base_url: str,
27
+ model: str,
28
+ messages: list[dict],
29
+ timeout: float = 120.0,
30
+ api_key: str | None = None,
31
+ max_tokens: int = 4096,
32
+ temperature: float = 0.7,
33
+ ) -> str:
34
+ headers = {}
35
+ if api_key:
36
+ headers["Authorization"] = f"Bearer {api_key}"
37
+ payload = {
38
+ "model": model,
39
+ "messages": messages,
40
+ "max_tokens": max_tokens,
41
+ "temperature": temperature,
42
+ }
43
+ logger.info("AI chat request: model=%s messages=%d", model, len(messages))
44
+ async with httpx.AsyncClient(timeout=timeout) as client:
45
+ resp = await client.post(
46
+ f"{base_url.rstrip('/')}/v1/chat/completions",
47
+ json=payload,
48
+ headers=headers,
49
+ )
50
+ resp.raise_for_status()
51
+ data = resp.json()
52
+ text = data["choices"][0]["message"]["content"]
53
+ logger.info("AI chat done: model=%s chars=%d", model, len(text or ""))
54
+ return text or ""
@@ -0,0 +1,148 @@
1
+ import logging
2
+ import re
3
+
4
+ from fusion_artifacts_engine.models import ArtifactType
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ _RENDERABLE_SVG_RE = re.compile(r"^\s*<svg[\s>]", re.IGNORECASE)
9
+ _RENDERABLE_MERMAID_RE = re.compile(
10
+ r"^\s*(graph\s+[A-Za-z]+|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|gitgraph|flowchart)",
11
+ re.IGNORECASE | re.MULTILINE,
12
+ )
13
+ _RENDERABLE_REACT_RE = re.compile(
14
+ # M-2: require stronger positive signals — import from react / hooks like useState / capitalized JSX component names
15
+ # Capitalized-first JSX components are a React convention; use explicit [A-Z] without IGNORECASE to avoid <html> false positives
16
+ r"(import\s+[^;]*\bfrom\s+['\"]react['\"]|"
17
+ r"from\s+['\"]react['\"]|"
18
+ r"\b(?:useState|useEffect|useMemo|useCallback|useRef|useContext)\s*\(|"
19
+ r"<(?:[A-Z]\w*|React\.\w+)[\s/>])",
20
+ )
21
+ _RENDERABLE_HTML_RE = re.compile(r"^\s*(<!DOCTYPE\s+html|<html[\s>])", re.IGNORECASE)
22
+
23
+ _CODE_LANGS = {
24
+ "python",
25
+ "py",
26
+ "javascript",
27
+ "js",
28
+ "typescript",
29
+ "ts",
30
+ "rust",
31
+ "go",
32
+ "java",
33
+ "c",
34
+ "cpp",
35
+ "c++",
36
+ "csharp",
37
+ "cs",
38
+ "ruby",
39
+ "rb",
40
+ "php",
41
+ "swift",
42
+ "kotlin",
43
+ "shell",
44
+ "bash",
45
+ "sh",
46
+ "sql",
47
+ "yaml",
48
+ "yml",
49
+ "toml",
50
+ "json",
51
+ "xml",
52
+ "html",
53
+ "css",
54
+ "scss",
55
+ "dockerfile",
56
+ }
57
+
58
+ _DATA_EXTS = {".json", ".csv", ".tsv", ".yaml", ".yml", ".toml", ".xml"}
59
+
60
+ _HTML_EXTS = {".html", ".htm"}
61
+
62
+ _REACT_EXTS = {".jsx", ".tsx"}
63
+
64
+
65
+ def should_create_artifact(
66
+ content: str,
67
+ content_type: str = "text",
68
+ threshold_lines: int = 30,
69
+ threshold_chars: int = 1500,
70
+ ) -> bool:
71
+ if content_type == "code":
72
+ line_count = content.count("\n") + 1
73
+ return line_count >= threshold_lines
74
+ return len(content) >= threshold_chars
75
+
76
+
77
+ def detect_artifact_type(name: str, content: str = "") -> ArtifactType:
78
+ name_lower = name.lower()
79
+ for ext in _REACT_EXTS:
80
+ if name_lower.endswith(ext):
81
+ return "react"
82
+ for ext in _HTML_EXTS:
83
+ if name_lower.endswith(ext):
84
+ return "html"
85
+ for ext in _DATA_EXTS:
86
+ if name_lower.endswith(ext):
87
+ return "data"
88
+ if name_lower.endswith((".md", ".markdown")):
89
+ return "markdown"
90
+ _, _, ext = name_lower.rpartition(".")
91
+ if ext in _CODE_LANGS:
92
+ return "code"
93
+ if content.strip().startswith("<!DOCTYPE") or content.strip().startswith("<html"):
94
+ return "html"
95
+ if content.strip().startswith("# ") or content.strip().startswith("## "):
96
+ return "markdown"
97
+ return "code"
98
+
99
+
100
+ def detect_renderable_type(content: str, name: str = "") -> str | None:
101
+ if name:
102
+ name_lower = name.lower()
103
+ if name_lower.endswith(".svg"):
104
+ return "svg"
105
+ if name_lower.endswith((".jsx", ".tsx")):
106
+ return "react"
107
+ if name_lower.endswith((".html", ".htm")):
108
+ return "html"
109
+ if name_lower.endswith((".mermaid", ".mmd")):
110
+ return "mermaid"
111
+ if _RENDERABLE_SVG_RE.search(content):
112
+ return "svg"
113
+ if _RENDERABLE_MERMAID_RE.search(content):
114
+ return "mermaid"
115
+ if _RENDERABLE_REACT_RE.search(content):
116
+ return "react"
117
+ if _RENDERABLE_HTML_RE.search(content):
118
+ return "html"
119
+ return None
120
+
121
+
122
+ def extract_name_hint(content: str, lang_hint: str = "") -> str:
123
+ lines = content.strip().split("\n")
124
+ for line in lines[:5]:
125
+ line = line.strip()
126
+ if line.startswith(("# filename:", "// filename:")):
127
+ return line.split(":", 1)[1].strip()
128
+ if line.startswith(("# file:", "// file:")):
129
+ return line.split(":", 1)[1].strip()
130
+ ext_map = {
131
+ "python": ".py",
132
+ "py": ".py",
133
+ "javascript": ".js",
134
+ "js": ".js",
135
+ "typescript": ".ts",
136
+ "ts": ".ts",
137
+ "rust": ".rs",
138
+ "go": ".go",
139
+ "html": ".html",
140
+ "css": ".css",
141
+ "shell": ".sh",
142
+ "bash": ".sh",
143
+ "sql": ".sql",
144
+ "markdown": ".md",
145
+ "md": ".md",
146
+ }
147
+ ext = ext_map.get(lang_hint.lower(), ".txt")
148
+ return f"artifact{ext}"
@@ -0,0 +1,164 @@
1
+ import logging
2
+ import re
3
+
4
+ from fusion_artifacts_engine.token_counter import count_tokens, estimate_tokens
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ def compact_content(content: str, artifact_type: str, token_budget: int) -> str:
10
+ original_tokens = count_tokens(content)
11
+ if original_tokens <= token_budget:
12
+ logger.debug(
13
+ "Content already within budget: %d <= %d", original_tokens, token_budget
14
+ )
15
+ return content
16
+
17
+ result = content
18
+ result = _remove_comments(result, artifact_type)
19
+ if estimate_tokens(result) <= token_budget and count_tokens(result) <= token_budget:
20
+ return result
21
+
22
+ result = _collapse_blank_lines(result)
23
+ if estimate_tokens(result) <= token_budget and count_tokens(result) <= token_budget:
24
+ return result
25
+
26
+ result = _remove_decorators(result, artifact_type)
27
+ if estimate_tokens(result) <= token_budget and count_tokens(result) <= token_budget:
28
+ return result
29
+
30
+ result = _truncate_sections(result, artifact_type, token_budget)
31
+ return result
32
+
33
+
34
+ def compact_and_count(content: str, artifact_type: str, token_budget: int) -> tuple[str, int]:
35
+ # F3: combines compaction + exact counting so the engine can offload to a thread pool; returns the compacted
36
+ # result and token count in one shot, avoiding a second full count_tokens(compacted_content) encode in the engine
37
+ compacted = compact_content(content, artifact_type, token_budget)
38
+ return compacted, count_tokens(compacted)
39
+
40
+
41
+ def _remove_comments(content: str, artifact_type: str) -> str:
42
+ lines = content.split("\n")
43
+ out = []
44
+ if artifact_type == "code":
45
+ # L-17: strips only whole-line # comments, preserving #! shebang and # -*- coding -*- declarations;
46
+ # skips lines starting with # inside triple-quoted strings to avoid breaking Python multiline strings
47
+ in_triple = False
48
+ triple_delims = ('"""', "'''")
49
+ for idx, line in enumerate(lines):
50
+ stripped = line.lstrip()
51
+ for delim in triple_delims:
52
+ count = line.count(delim)
53
+ if count and not in_triple:
54
+ if count % 2 == 1:
55
+ in_triple = True
56
+ out.append(line)
57
+ break
58
+ elif count and in_triple:
59
+ if count % 2 == 1:
60
+ in_triple = False
61
+ out.append(line)
62
+ break
63
+ else:
64
+ if in_triple:
65
+ out.append(line)
66
+ continue
67
+ if idx == 0 and stripped.startswith("#!"):
68
+ out.append(line)
69
+ continue
70
+ if stripped.startswith(("# -*-", "#coding")):
71
+ out.append(line)
72
+ continue
73
+ if stripped.startswith("#"):
74
+ continue
75
+ out.append(line)
76
+ elif artifact_type == "markdown":
77
+ for line in lines:
78
+ stripped = line.lstrip()
79
+ if stripped.startswith("<!--") and "-->" in stripped:
80
+ continue
81
+ out.append(line)
82
+ else:
83
+ return content
84
+ logger.debug(
85
+ "Removed comments: %d -> %d lines for %s", len(lines), len(out), artifact_type
86
+ )
87
+ return "\n".join(out)
88
+
89
+
90
+ def _collapse_blank_lines(content: str) -> str:
91
+ result = re.sub(r"\n{3,}", "\n\n", content)
92
+ result = result.strip() + "\n"
93
+ return result
94
+
95
+
96
+ def _remove_decorators(content: str, artifact_type: str) -> str:
97
+ if artifact_type != "markdown":
98
+ return content
99
+ lines = content.split("\n")
100
+ out = [
101
+ line
102
+ for line in lines
103
+ if line.strip() not in ("---", "***", "___", "- - -", "* * *")
104
+ ]
105
+ logger.debug("Removed decorators: %d -> %d lines", len(lines), len(out))
106
+ return "\n".join(out)
107
+
108
+
109
+ def _truncate_sections(content: str, artifact_type: str, token_budget: int) -> str:
110
+ lines = content.split("\n")
111
+ sections = []
112
+ i = 0
113
+ while i < len(lines):
114
+ matched = False
115
+ level = 0
116
+ anchor = ""
117
+ if artifact_type == "markdown":
118
+ m = re.match(r"^(#{1,6})\s+(.+)$", lines[i])
119
+ if m:
120
+ anchor = m.group(2).strip()
121
+ level = len(m.group(1))
122
+ matched = True
123
+ elif artifact_type == "code":
124
+ m = re.match(r"^(?:async\s+)?(?:def|class|func)\s+(\w+)", lines[i])
125
+ if m:
126
+ anchor = m.group(1)
127
+ level = 1
128
+ matched = True
129
+ if matched:
130
+ sections.append({"start": i, "anchor": anchor, "level": level})
131
+ i += 1
132
+
133
+ # F3: incremental per-line token counting + prefix sums, avoiding re-join + full encode at every section boundary (O(n^2)).
134
+ # Each line is encoded once within this function; before the final return, count_tokens validates the joined result exactly once.
135
+ line_tokens = [count_tokens(line) for line in lines]
136
+ prefix = [0] * (len(lines) + 1)
137
+ for idx, t in enumerate(line_tokens):
138
+ prefix[idx + 1] = prefix[idx] + t
139
+
140
+ if not sections:
141
+ total = prefix[len(lines)]
142
+ if total <= token_budget:
143
+ return "\n".join(lines)
144
+ ratio = token_budget / max(1, total)
145
+ cut = int(len(lines) * ratio)
146
+ candidate = "\n".join(lines[:cut])
147
+ if count_tokens(candidate) <= token_budget:
148
+ return candidate
149
+ while cut > 0 and count_tokens("\n".join(lines[:cut])) > token_budget:
150
+ cut -= 1
151
+ return "\n".join(lines[:cut])
152
+
153
+ sections.reverse()
154
+ for sec in sections:
155
+ if prefix[sec["start"]] <= token_budget:
156
+ current = "\n".join(lines[: sec["start"]])
157
+ if count_tokens(current) <= token_budget:
158
+ logger.info(
159
+ "Truncated sections from anchor='%s' to meet budget=%d",
160
+ sec["anchor"],
161
+ token_budget,
162
+ )
163
+ return current
164
+ return "\n".join(lines[:1]) if lines else ""