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
@@ -0,0 +1,168 @@
1
+ import logging
2
+ import time
3
+ from typing import Literal
4
+
5
+ from pydantic import BaseModel, Field, field_validator
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ ArtifactType = Literal["code", "markdown", "html", "react", "svg", "mermaid", "data"]
10
+ ArtifactKind = Literal["app", "code", "document", "game", "tool", "template"]
11
+ OwnershipType = Literal["free", "project", "cowork"]
12
+ SnapshotType = Literal["auto", "manual", "named", "rollback"]
13
+
14
+ _TYPE_TO_KIND: dict[str, str] = {
15
+ "html": "app",
16
+ "react": "app",
17
+ "svg": "app",
18
+ "mermaid": "document",
19
+ "markdown": "document",
20
+ "code": "code",
21
+ "data": "tool",
22
+ }
23
+
24
+ # P0-5/H6: metadata structure caps — top-level key count and per-key name length, against DoS-style huge/deeply-nested metadata
25
+ _MAX_METADATA_KEYS = 64
26
+ _MAX_METADATA_KEY_LEN = 128
27
+
28
+
29
+ def infer_kind(artifact_type: str) -> ArtifactKind:
30
+ return _TYPE_TO_KIND.get(artifact_type, "tool")
31
+
32
+
33
+ def _validate_metadata(metadata: dict | None) -> dict | None:
34
+ # P0-5/H6: metadata structure validation — reject non-dict, cap top-level key count and key name length.
35
+ # The byte cap is enforced by the storage layer's _enforce_metadata_limit; this catches malformed structures early.
36
+ if metadata is None:
37
+ return None
38
+ if not isinstance(metadata, dict):
39
+ raise ValueError("metadata must be a dict")
40
+ if len(metadata) > _MAX_METADATA_KEYS:
41
+ logger.warning("Metadata rejected: %d keys > %d", len(metadata), _MAX_METADATA_KEYS)
42
+ raise ValueError(f"metadata has too many keys: {len(metadata)} > {_MAX_METADATA_KEYS}")
43
+ for key in metadata:
44
+ if not isinstance(key, str):
45
+ raise ValueError(f"metadata key must be str, got {type(key).__name__}")
46
+ if len(key) > _MAX_METADATA_KEY_LEN:
47
+ raise ValueError(
48
+ f"metadata key too long: {len(key)} > {_MAX_METADATA_KEY_LEN}"
49
+ )
50
+ return metadata
51
+
52
+
53
+ class Artifact(BaseModel):
54
+ id: str
55
+ session_id: str
56
+ name: str
57
+ type: ArtifactType
58
+ kind: ArtifactKind | None = None
59
+ project_id: str | None = None
60
+ metadata: dict | None = None
61
+
62
+ @field_validator("metadata")
63
+ @classmethod
64
+ def _metadata_validator(cls, v):
65
+ return _validate_metadata(v)
66
+ current_version: int = 1
67
+ summary: str = ""
68
+ created_at: float = Field(default_factory=time.time)
69
+ updated_at: float = Field(default_factory=time.time)
70
+ is_deleted: bool = False
71
+ owner_user_id: str | None = None
72
+ ownership_type: OwnershipType = "free"
73
+ is_starred: bool = False
74
+ is_pinned: bool = False
75
+ pinned_chat_id: str | None = None
76
+ share_id: str | None = None
77
+ in_project_kb: bool = False
78
+ folder_id: str | None = None
79
+ deleted_at: str | None = None
80
+ content_hash: str | None = None
81
+ active_in_session: str | None = None
82
+ source_module: str | None = None
83
+ workspace_id: str | None = None
84
+ workflow_run_id: str | None = None
85
+ # #77: remix lineage — the artifact this one was remixed from (None = original)
86
+ parent_artifact_id: str | None = None
87
+
88
+
89
+ class ArtifactVersion(BaseModel):
90
+ # #100-4: the global auto-increment rowid must not leak (it exposes global artifact volume and shows
91
+ # "another session's v1 already at id=49" in the UI).
92
+ # Field retained for storage-layer internal use; the API identifies versions by the (artifact_id, version_num) pair.
93
+ id: int = Field(default=0, exclude=True)
94
+ artifact_id: str
95
+ version_num: int
96
+ content: str = ""
97
+ content_path: str | None = None
98
+ size_bytes: int = 0
99
+ token_count: int = 0
100
+ section_index: str | None = None
101
+ change_log: str = ""
102
+ source: str = "manual"
103
+ created_at: float = Field(default_factory=time.time)
104
+ snapshot_type: SnapshotType = "auto"
105
+ snapshot_label: str | None = None
106
+ author: str | None = None
107
+ parent_version: int | None = None
108
+
109
+
110
+ class ArtifactRef(BaseModel):
111
+ artifact_id: str
112
+ name: str
113
+ type: ArtifactType
114
+ version: str
115
+ size_bytes: int = 0
116
+ summary: str = ""
117
+
118
+
119
+ class ArtifactShare(BaseModel):
120
+ share_id: str
121
+ artifact_id: str
122
+ created_by: str | None = None
123
+ # E1: created_at/last_access_at are unified float epochs, consistent with Artifact/Version,
124
+ # avoiding float<str TypeError in time sorting/range filtering. expires_at stays an ISO str
125
+ # (parsed via _parse_expires_at/_is_expired, never used in sort comparisons).
126
+ created_at: float | None = None
127
+ expires_at: str | None = None
128
+ revoked: bool = False
129
+ access_count: int = 0
130
+ # E2: the access cap field advertised in the README, stored as max_accesses, None=unlimited.
131
+ # get_shared/get_public_share check access_count>=max_accesses before incrementing.
132
+ max_accesses: int | None = None
133
+ last_access_at: float | None = None
134
+ # #77: share permission level — "view" read-only (default) / "remix" viewer may remix.
135
+ permission: str = "view"
136
+
137
+ @field_validator("permission")
138
+ @classmethod
139
+ def _permission_validator(cls, v):
140
+ if v not in ("view", "remix"):
141
+ raise ValueError(f"share permission must be 'view' or 'remix', got: {v!r}")
142
+ return v
143
+
144
+
145
+ class ArtifactFolder(BaseModel):
146
+ folder_id: str
147
+ name: str
148
+ parent_id: str | None = None
149
+ project_id: str | None = None
150
+ created_at: float | None = None
151
+
152
+
153
+ class ArtifactTag(BaseModel):
154
+ tag_id: str
155
+ name: str
156
+ color: str | None = None
157
+ # L-7: tag scoping — isolated by session_id or project_id, preventing cross-user leaks of same-named tags
158
+ scope: str | None = None
159
+
160
+
161
+ class ArtifactEvent(BaseModel):
162
+ event_id: str
163
+ artifact_id: str | None = None
164
+ session_id: str | None = None
165
+ event_type: str
166
+ payload: dict | None = None
167
+ # E1: unified float epoch, consistent with Artifact/Version/Share/Folder
168
+ created_at: float | None = None
@@ -0,0 +1,365 @@
1
+ import io
2
+ import logging
3
+ import re
4
+ from pathlib import Path
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ # v0.7.0: fusion-office long-context ingest. Office files (docx/xlsx/pptx) are parsed into
9
+ # markdown with `#` headers — directly addressable by section_index (docx=heading levels,
10
+ # xlsx=worksheets, pptx=slides); patch/budget/references all go through the existing pipeline.
11
+ # The write-back direction regenerates patched markdown into the same-format binary (pptx
12
+ # write-back added in v0.7.17, issue #128 — in-process python-pptx, same pattern as
13
+ # docx/openpyxl; fusion-office office-api has no /v1/pptx/write endpoint yet, upstream
14
+ # issue filed) and exports to .outbox/ in the office IPC dir for fusion-office to pick up.
15
+ # Issue #131 (v0.7.18): _parse_pptx now emits the slide title as the section heading so
16
+ # write-back restores it into the title placeholder instead of dropping it.
17
+ # The engine never overwrites the user's original file.
18
+
19
+ _MAX_SHEET_ROWS = 500
20
+ _MAX_SHEET_COLS = 64
21
+ _HEADING_RE = re.compile(r"^(#{1,6})\s+(.+)$", re.MULTILINE)
22
+ _TABLE_ROW_RE = re.compile(r"^\|.*\|$")
23
+
24
+
25
+ def _md_escape_cell(value) -> str:
26
+ text = "" if value is None else str(value)
27
+ return text.replace("|", "\\|").replace("\n", " ").strip()
28
+
29
+
30
+ def parse_office(path: Path) -> tuple[str, str, dict]:
31
+ suffix = path.suffix.lower()
32
+ if suffix == ".docx":
33
+ content = _parse_docx(path)
34
+ elif suffix == ".xlsx":
35
+ content = _parse_xlsx(path)
36
+ elif suffix == ".pptx":
37
+ content = _parse_pptx(path)
38
+ else:
39
+ raise ValueError(f"unsupported office format: {suffix or '(none)'}")
40
+ stats = {
41
+ "format": suffix.lstrip("."),
42
+ "chars": len(content),
43
+ "headings": len(_HEADING_RE.findall(content)),
44
+ }
45
+ logger.info(
46
+ "office parsed %s (%s, %d chars, %d headings)",
47
+ path.name,
48
+ suffix,
49
+ len(content),
50
+ stats["headings"],
51
+ )
52
+ return content, suffix.lstrip("."), stats
53
+
54
+
55
+ def _parse_docx(path: Path) -> str:
56
+ try:
57
+ from docx import Document
58
+ from docx.oxml.ns import qn
59
+ from docx.table import Table
60
+ from docx.text.paragraph import Paragraph
61
+ except ImportError as e:
62
+ raise RuntimeError("python-docx not installed") from e
63
+ document = Document(str(path))
64
+ lines: list[str] = []
65
+ for child in document.element.body.iterchildren():
66
+ if child.tag == qn("w:p"):
67
+ para = Paragraph(child, document)
68
+ text = para.text.strip()
69
+ if not text:
70
+ lines.append("")
71
+ continue
72
+ style = ""
73
+ try:
74
+ style = para.style.name or ""
75
+ except Exception: # noqa: BLE001
76
+ style = ""
77
+ m = re.match(r"^Heading (\d)$", style)
78
+ if m:
79
+ level = min(6, int(m.group(1)) + 1)
80
+ lines.append(f"{'#' * level} {text}")
81
+ else:
82
+ lines.append(text)
83
+ elif child.tag == qn("w:tbl"):
84
+ table = Table(child, document)
85
+ for row in table.rows:
86
+ cells = [_md_escape_cell(c.text) for c in row.cells]
87
+ lines.append("| " + " | ".join(cells) + " |")
88
+ lines.append("")
89
+ return "\n".join(lines).strip() + "\n"
90
+
91
+
92
+ def _parse_xlsx(path: Path) -> str:
93
+ try:
94
+ import openpyxl
95
+ except ImportError as e:
96
+ raise RuntimeError("openpyxl not installed") from e
97
+ workbook = openpyxl.load_workbook(str(path), data_only=True, read_only=True)
98
+ lines: list[str] = []
99
+ for sheet in workbook.worksheets:
100
+ lines.append(f"## {sheet.title}")
101
+ lines.append("")
102
+ rows_written = 0
103
+ for row in sheet.iter_rows(
104
+ max_row=_MAX_SHEET_ROWS, max_col=_MAX_SHEET_COLS, values_only=True
105
+ ):
106
+ cells = [_md_escape_cell(v) for v in row]
107
+ lines.append("| " + " | ".join(cells) + " |")
108
+ if rows_written == 0:
109
+ lines.append("|" + "---|" * len(cells))
110
+ rows_written += 1
111
+ if rows_written == 0:
112
+ lines.append("(empty sheet)")
113
+ elif rows_written >= _MAX_SHEET_ROWS:
114
+ lines.append(f"(truncated at {_MAX_SHEET_ROWS} rows)")
115
+ lines.append("")
116
+ workbook.close()
117
+ return "\n".join(lines).strip() + "\n"
118
+
119
+
120
+ def _parse_pptx(path: Path) -> str:
121
+ try:
122
+ from pptx import Presentation
123
+ except ImportError as e:
124
+ raise RuntimeError("python-pptx not installed") from e
125
+ presentation = Presentation(str(path))
126
+ lines: list[str] = []
127
+ for idx, slide in enumerate(presentation.slides, start=1):
128
+ # Issue #131: emit the slide title as the heading (markdown_to_pptx maps
129
+ # headings back into the title placeholder) instead of flattening it into
130
+ # the body lines — flattening lost the title on write-back. Untitled
131
+ # slides keep the stable "## Slide N" anchor.
132
+ title_text = ""
133
+ title_shape_id = None
134
+ if slide.shapes.title is not None:
135
+ title_text = slide.shapes.title.text.strip()
136
+ title_shape_id = slide.shapes.title.shape_id
137
+ lines.append(f"## {title_text or f'Slide {idx}'}")
138
+ lines.append("")
139
+ for shape in slide.shapes:
140
+ # skip the title shape itself (shape_id compare — shapes.title returns a
141
+ # fresh wrapper object per access, so identity comparison never matches)
142
+ if not getattr(shape, "has_text_frame", False) or shape.shape_id == title_shape_id:
143
+ continue
144
+ for para in shape.text_frame.paragraphs:
145
+ text = "".join(run.text for run in para.runs).strip()
146
+ if text:
147
+ lines.append(text)
148
+ lines.append("")
149
+ return "\n".join(lines).strip() + "\n"
150
+
151
+
152
+ def _blocks(content: str) -> list[dict]:
153
+ blocks: list[dict] = []
154
+ paragraph: list[str] = []
155
+ table: list[list[str]] = []
156
+
157
+ def flush_paragraph():
158
+ if paragraph:
159
+ blocks.append({"kind": "para", "text": " ".join(paragraph)})
160
+ paragraph.clear()
161
+
162
+ def flush_table():
163
+ if table:
164
+ blocks.append({"kind": "table", "rows": [r[:] for r in table]})
165
+ table.clear()
166
+
167
+ for line in content.split("\n"):
168
+ stripped = line.strip()
169
+ heading = _HEADING_RE.match(stripped)
170
+ if heading:
171
+ flush_paragraph()
172
+ flush_table()
173
+ blocks.append(
174
+ {"kind": "heading", "level": len(heading.group(1)), "text": heading.group(2)}
175
+ )
176
+ elif _TABLE_ROW_RE.match(stripped) and "---" not in stripped:
177
+ flush_paragraph()
178
+ cells = [c.replace("\\|", "|").strip() for c in stripped.strip("|").split("|")]
179
+ table.append(cells)
180
+ elif _TABLE_ROW_RE.match(stripped) and "---" in stripped:
181
+ flush_paragraph()
182
+ elif stripped:
183
+ flush_table()
184
+ paragraph.append(stripped)
185
+ else:
186
+ flush_paragraph()
187
+ flush_table()
188
+ flush_paragraph()
189
+ flush_table()
190
+ return blocks
191
+
192
+
193
+ def _safe_sheet_name(name: str, used: set[str]) -> str:
194
+ cleaned = re.sub(r"[\[\]:*?/\\]", "_", name).strip() or "Sheet"
195
+ cleaned = cleaned[:31]
196
+ base = cleaned
197
+ n = 2
198
+ while cleaned.lower() in used:
199
+ suffix = f"~{n}"
200
+ cleaned = base[: 31 - len(suffix)] + suffix
201
+ n += 1
202
+ used.add(cleaned.lower())
203
+ return cleaned
204
+
205
+
206
+ def markdown_to_docx(content: str) -> bytes:
207
+ try:
208
+ from docx import Document
209
+ except ImportError as e:
210
+ raise RuntimeError("python-docx not installed") from e
211
+ document = Document()
212
+ for block in _blocks(content):
213
+ if block["kind"] == "heading":
214
+ document.add_heading(block["text"], level=max(1, block["level"] - 1))
215
+ elif block["kind"] == "para":
216
+ document.add_paragraph(block["text"])
217
+ else:
218
+ rows = block["rows"]
219
+ cols = max(len(r) for r in rows)
220
+ table = document.add_table(rows=len(rows), cols=cols)
221
+ for r, row in enumerate(rows):
222
+ for c in range(cols):
223
+ table.cell(r, c).text = row[c] if c < len(row) else ""
224
+ buf = io.BytesIO()
225
+ document.save(buf)
226
+ return buf.getvalue()
227
+
228
+
229
+ def _coerce_cell(text: str):
230
+ # markdown table cells are strings; coerce back to numbers on xlsx write-back to keep types round-trippable
231
+ stripped = text.strip()
232
+ if not stripped:
233
+ return ""
234
+ try:
235
+ return int(stripped)
236
+ except ValueError:
237
+ pass
238
+ try:
239
+ return float(stripped)
240
+ except ValueError:
241
+ return text
242
+
243
+
244
+ def markdown_to_xlsx(content: str) -> bytes:
245
+ try:
246
+ from openpyxl import Workbook
247
+ except ImportError as e:
248
+ raise RuntimeError("openpyxl not installed") from e
249
+ workbook = Workbook()
250
+ workbook.remove(workbook.active)
251
+ used: set[str] = set()
252
+ current = None
253
+ for block in _blocks(content):
254
+ if block["kind"] == "heading":
255
+ current = workbook.create_sheet(_safe_sheet_name(block["text"], used))
256
+ elif current is None:
257
+ current = workbook.create_sheet(_safe_sheet_name("Sheet1", used))
258
+ elif block["kind"] == "para":
259
+ current.append([block["text"]])
260
+ else:
261
+ for row in block["rows"]:
262
+ current.append([_coerce_cell(c) for c in row])
263
+ if not workbook.worksheets:
264
+ workbook.create_sheet("Sheet1")
265
+ buf = io.BytesIO()
266
+ workbook.save(buf)
267
+ return buf.getvalue()
268
+
269
+
270
+ def markdown_to_pptx(content: str) -> bytes:
271
+ # Issue #128: regenerate a deck from patched markdown. Symmetric with _parse_pptx:
272
+ # every heading starts a new slide (title), paragraphs fill the body placeholder
273
+ # (fallback textbox), tables render as pptx tables below the body.
274
+ try:
275
+ from pptx import Presentation
276
+ from pptx.util import Inches
277
+ except ImportError as e:
278
+ raise RuntimeError("python-pptx not installed") from e
279
+ presentation = Presentation()
280
+ title_and_body = presentation.slide_layouts[1]
281
+ slide = None
282
+ body_frame = None
283
+ body_used = False
284
+
285
+ def new_slide(title_text: str):
286
+ nonlocal body_frame, body_used
287
+ s = presentation.slides.add_slide(title_and_body)
288
+ body_frame = None
289
+ body_used = False
290
+ if s.shapes.title is not None:
291
+ s.shapes.title.text = title_text
292
+ for ph in s.placeholders:
293
+ if ph.placeholder_format.idx == 1:
294
+ body_frame = ph.text_frame
295
+ break
296
+ return s
297
+
298
+ def append_body(text: str):
299
+ nonlocal body_used
300
+ if body_frame is not None:
301
+ if not body_used:
302
+ body_frame.paragraphs[0].text = text
303
+ body_used = True
304
+ else:
305
+ body_frame.add_paragraph().text = text
306
+ else:
307
+ box = slide.shapes.add_textbox(Inches(0.5), Inches(1.8), Inches(9), Inches(4.5))
308
+ box.text_frame.text = text
309
+
310
+ for block in _blocks(content):
311
+ if block["kind"] == "heading":
312
+ slide = new_slide(block["text"])
313
+ elif slide is None:
314
+ slide = new_slide("")
315
+ append_body(block["text"] if block["kind"] == "para" else "")
316
+ elif block["kind"] == "para":
317
+ append_body(block["text"])
318
+ else:
319
+ rows = block["rows"]
320
+ cols = max(len(r) for r in rows)
321
+ shape = slide.shapes.add_table(
322
+ len(rows), cols, Inches(0.5), Inches(1.8), Inches(9), Inches(0.4 * len(rows))
323
+ )
324
+ table = shape.table
325
+ for r, row in enumerate(rows):
326
+ for c in range(cols):
327
+ table.cell(r, c).text = row[c] if c < len(row) else ""
328
+ if not presentation.slides:
329
+ new_slide("")
330
+ buf = io.BytesIO()
331
+ presentation.save(buf)
332
+ return buf.getvalue()
333
+
334
+
335
+ def maybe_write_back(engine, artifact, version_num: int) -> str | None:
336
+ # After patch/update, regenerate the office file per metadata.office_format into
337
+ # .outbox/. Failures only log and do not affect the patch result itself.
338
+ meta = (artifact.metadata or {}) if artifact is not None else {}
339
+ fmt = meta.get("office_format")
340
+ if fmt not in ("docx", "xlsx", "pptx"):
341
+ return None
342
+ version = engine.storage.get_version(artifact.id, version_num)
343
+ if version is None:
344
+ logger.warning("office write-back: version %s v%s not found", artifact.id, version_num)
345
+ return None
346
+ try:
347
+ if fmt == "docx":
348
+ data = markdown_to_docx(version.content)
349
+ elif fmt == "xlsx":
350
+ data = markdown_to_xlsx(version.content)
351
+ else:
352
+ data = markdown_to_pptx(version.content)
353
+ except Exception: # noqa: BLE001
354
+ logger.exception("office write-back failed for %s v%d", artifact.id, version_num)
355
+ return None
356
+ outbox = engine.config.ipc_office_outbox_path
357
+ try:
358
+ outbox.mkdir(parents=True, exist_ok=True)
359
+ path = outbox / f"{artifact.id}_v{version_num}.{fmt}"
360
+ path.write_bytes(data)
361
+ except OSError as e:
362
+ logger.error("office write-back export failed %s v%d: %s", artifact.id, version_num, e)
363
+ return None
364
+ logger.info("office write-back exported %s", path)
365
+ return str(path)
@@ -0,0 +1,82 @@
1
+ import logging
2
+ import threading
3
+ import time
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+
8
+ class TokenBucket:
9
+ # Token bucket: tokens refill at a constant rps rate; bucket capacity burst caps the maximum burst.
10
+ # acquire() takes a token; an empty bucket returns False (caller replies 429), never blocks, never queues.
11
+
12
+ def __init__(self, rps: float, burst: int):
13
+ self.rps = max(0.0, float(rps))
14
+ self.burst = max(1, int(burst))
15
+ self._tokens = float(self.burst)
16
+ self._last = time.monotonic()
17
+ self._lock = threading.Lock()
18
+ self._rejected = 0
19
+
20
+ def _refill(self) -> None:
21
+ now = time.monotonic()
22
+ elapsed = now - self._last
23
+ self._last = now
24
+ self._tokens = min(self.burst, self._tokens + elapsed * self.rps)
25
+
26
+ def acquire(self) -> bool:
27
+ if self.rps <= 0:
28
+ return True
29
+ with self._lock:
30
+ self._refill()
31
+ if self._tokens >= 1.0:
32
+ self._tokens -= 1.0
33
+ return True
34
+ self._rejected += 1
35
+ return False
36
+
37
+ def snapshot(self) -> dict:
38
+ with self._lock:
39
+ self._refill()
40
+ return {
41
+ "rps": self.rps,
42
+ "burst": self.burst,
43
+ "tokens": round(self._tokens, 2),
44
+ "rejected": self._rejected,
45
+ }
46
+
47
+
48
+ class RateLimiter:
49
+ # Two buckets: default covers JSON-RPC + authed REST; public covers unauthenticated public share endpoints.
50
+ # public has an isolated quota — public endpoints are prone to flooding and must not drag down the authed backend.
51
+ # rps=0 means unlimited (default).
52
+
53
+ def __init__(self, rps: float = 0, burst: int = 0,
54
+ public_rps: float = 0, public_burst: int = 0):
55
+ self.default = TokenBucket(rps, burst if burst else max(1, int(rps)))
56
+ self.public = TokenBucket(
57
+ public_rps, public_burst if public_burst else max(1, int(public_rps))
58
+ )
59
+ self.enabled = rps > 0
60
+ self.public_enabled = public_rps > 0
61
+
62
+ def check_default(self) -> bool:
63
+ if not self.enabled:
64
+ return True
65
+ ok = self.default.acquire()
66
+ if not ok:
67
+ logger.warning("Rate limit hit (default bucket)")
68
+ return ok
69
+
70
+ def check_public(self) -> bool:
71
+ if not self.public_enabled:
72
+ return True
73
+ ok = self.public.acquire()
74
+ if not ok:
75
+ logger.warning("Rate limit hit (public bucket)")
76
+ return ok
77
+
78
+ def metrics(self) -> dict:
79
+ return {
80
+ "default": self.default.snapshot(),
81
+ "public": self.public.snapshot(),
82
+ }
@@ -0,0 +1,77 @@
1
+ import logging
2
+ import re
3
+
4
+ from fusion_artifacts_engine.models import ArtifactRef
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ _TOOL_RESULT_PATTERN = re.compile(
9
+ r"\[Artifact:\s*(?P<name>[^|]+)\s*\|\s*ID:\s*(?P<id>\w+)\s*\|\s*Version:\s*v(?P<version>\d+)\s*\|\s*Type:\s*(?P<type>\w+)\s*\|\s*Size:\s*(?P<size_bytes>\d+)\s*(?:\|\s*Summary:\s*(?P<summary>.+?))?\]",
10
+ re.IGNORECASE,
11
+ )
12
+
13
+ _XML_ARTIFACT_PATTERN = re.compile(
14
+ r"<artifact\s+id=[\"'](?P<id>[^\"']+)[\"']\s+name=[\"'](?P<name>[^\"']+)[\"']\s+type=[\"'](?P<type>[^\"']+)[\"']\s+version=[\"'](?P<version>[^\"']+)[\"']\s+size_bytes=[\"'](?P<size_bytes>\d+)[\"']\s*>\s*(?:<summary>(?P<summary>[^<]*)</summary>)?\s*</artifact>",
15
+ re.DOTALL,
16
+ )
17
+
18
+
19
+ def parse_refs_from_message(content: str) -> list[ArtifactRef]:
20
+ refs = []
21
+ for m in _TOOL_RESULT_PATTERN.finditer(content):
22
+ ver = m.group("version")
23
+ try:
24
+ ver = str(int(ver))
25
+ except ValueError:
26
+ pass
27
+ # L-19: one reference failing to parse must not drop the rest of the message's references
28
+ try:
29
+ refs.append(
30
+ ArtifactRef(
31
+ artifact_id=m.group("id"),
32
+ name=m.group("name").strip(),
33
+ type=m.group("type").strip(),
34
+ version=ver,
35
+ size_bytes=int(m.group("size_bytes")),
36
+ summary=(m.group("summary") or "").strip(),
37
+ )
38
+ )
39
+ except Exception as e: # noqa: BLE001
40
+ logger.warning("Skip invalid tool-result ref (id=%s): %s", m.group("id"), e)
41
+ for m in _XML_ARTIFACT_PATTERN.finditer(content):
42
+ ver = m.group("version")
43
+ if ver != "latest":
44
+ try:
45
+ ver = str(int(ver))
46
+ except ValueError:
47
+ pass
48
+ try:
49
+ refs.append(
50
+ ArtifactRef(
51
+ artifact_id=m.group("id"),
52
+ name=m.group("name").strip(),
53
+ type=m.group("type").strip(),
54
+ version=ver,
55
+ size_bytes=int(m.group("size_bytes")),
56
+ summary=(m.group("summary") or "").strip(),
57
+ )
58
+ )
59
+ except Exception as e: # noqa: BLE001
60
+ logger.warning("Skip invalid xml ref (id=%s): %s", m.group("id"), e)
61
+ logger.debug("Parsed %s refs from message", len(refs))
62
+ return refs
63
+
64
+
65
+ def generate_ref_text(
66
+ artifact_id: str,
67
+ name: str,
68
+ artifact_type: str,
69
+ version: int,
70
+ size_bytes: int,
71
+ summary: str = "",
72
+ ) -> str:
73
+ text = f"[Artifact: {name} | ID: {artifact_id} | Version: v{version} | Type: {artifact_type} | Size: {size_bytes}"
74
+ if summary:
75
+ text += f" | Summary: {summary[:200]}"
76
+ text += "]"
77
+ return text