qbraid-cli 0.17.2__tar.gz → 0.17.3__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.
- {qbraid_cli-0.17.2/qbraid_cli.egg-info → qbraid_cli-0.17.3}/PKG-INFO +4 -4
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/pyproject.toml +7 -4
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/agents/app.py +162 -5
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/artifacts/app.py +42 -5
- qbraid_cli-0.17.3/qbraid_cli/artifacts/mermaid.py +202 -0
- qbraid_cli-0.17.3/qbraid_cli/artifacts/pele.LICENSE +40 -0
- qbraid_cli-0.17.3/qbraid_cli/artifacts/pele.global.js +150 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3/qbraid_cli.egg-info}/PKG-INFO +4 -4
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli.egg-info/SOURCES.txt +3 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli.egg-info/requires.txt +3 -3
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/LICENSE +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/README.md +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/_build_info.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/_version.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/account/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/account/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/admin/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/admin/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/admin/headers.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/admin/validation.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/agents/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/agents/keep_alive.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/agents/permission_response.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/agents/provider_children.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/agents/queue.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/agents/work.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/ai/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/ai/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/ai/token.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/artifacts/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/comms/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/comms/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/compute/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/compute/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/compute/instances.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/compute/profiles.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/compute/server.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/compute/ssh.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/configure/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/configure/actions.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/configure/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/devices/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/devices/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/devices/validation.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/envs/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/envs/activate.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/envs/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/envs/create.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/envs/data_handling.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/envs/groups.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/envs/publish.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/envs/registry.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/envs/share.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/exceptions.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/handlers.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/jobs/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/jobs/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/jobs/groups.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/kernels/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/kernels/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/lab/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/lab/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/main.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/pip/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/pip/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/pip/hooks.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/projects/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/projects/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/py.typed +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/skills/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/skills/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/troubleshoot/__init__.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli/troubleshoot/app.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli.egg-info/dependency_links.txt +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli.egg-info/entry_points.txt +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/qbraid_cli.egg-info/top_level.txt +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/setup.cfg +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/tests/test_cli_e2e.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/tests/test_register_client.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/tests/test_status_colors.py +0 -0
- {qbraid_cli-0.17.2 → qbraid_cli-0.17.3}/tests/test_version.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: qbraid-cli
|
|
3
|
-
Version: 0.17.
|
|
3
|
+
Version: 0.17.3
|
|
4
4
|
Summary: Command Line Interface for interacting with all parts of the qBraid platform.
|
|
5
5
|
Author-email: qBraid Development Team <contact@qbraid.com>
|
|
6
6
|
License-Expression: LicenseRef-Proprietary
|
|
@@ -30,11 +30,11 @@ Requires-Dist: typer>=0.12.1
|
|
|
30
30
|
Requires-Dist: rich>=10.11.0
|
|
31
31
|
Requires-Dist: click<=8.5.1
|
|
32
32
|
Requires-Dist: questionary>=2.0.0
|
|
33
|
-
Requires-Dist: qbraid-core>=0.6.
|
|
33
|
+
Requires-Dist: qbraid-core>=0.6.57
|
|
34
34
|
Provides-Extra: compute
|
|
35
|
-
Requires-Dist: qbraid-core[compute]>=0.6.
|
|
35
|
+
Requires-Dist: qbraid-core[compute]>=0.6.57; extra == "compute"
|
|
36
36
|
Provides-Extra: envs
|
|
37
|
-
Requires-Dist: qbraid-core[environments]>=0.6.
|
|
37
|
+
Requires-Dist: qbraid-core[environments]>=0.6.57; extra == "envs"
|
|
38
38
|
Provides-Extra: dev
|
|
39
39
|
Requires-Dist: isort; extra == "dev"
|
|
40
40
|
Requires-Dist: black; extra == "dev"
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "qbraid-cli"
|
|
7
|
-
version = "0.17.
|
|
7
|
+
version = "0.17.3"
|
|
8
8
|
description = "Command Line Interface for interacting with all parts of the qBraid platform."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
authors = [{ name = "qBraid Development Team", email = "contact@qbraid.com" }]
|
|
@@ -32,7 +32,7 @@ dependencies = [
|
|
|
32
32
|
"rich>=10.11.0",
|
|
33
33
|
"click<=8.5.1",
|
|
34
34
|
"questionary>=2.0.0",
|
|
35
|
-
"qbraid-core>=0.6.
|
|
35
|
+
"qbraid-core>=0.6.57",
|
|
36
36
|
]
|
|
37
37
|
requires-python = ">= 3.10"
|
|
38
38
|
|
|
@@ -43,8 +43,8 @@ Documentation = "https://docs.qbraid.com/v2/cli/api-reference/qbraid"
|
|
|
43
43
|
Discord = "https://discord.gg/KugF6Cnncm"
|
|
44
44
|
|
|
45
45
|
[project.optional-dependencies]
|
|
46
|
-
compute = ["qbraid-core[compute]>=0.6.
|
|
47
|
-
envs = ["qbraid-core[environments]>=0.6.
|
|
46
|
+
compute = ["qbraid-core[compute]>=0.6.57"]
|
|
47
|
+
envs = ["qbraid-core[environments]>=0.6.57"]
|
|
48
48
|
dev = ["isort", "black", "pytest", "pytest-cov", "pytest-asyncio"]
|
|
49
49
|
|
|
50
50
|
[project.scripts]
|
|
@@ -53,6 +53,9 @@ qbraid = "qbraid_cli.main:app"
|
|
|
53
53
|
# through the full CLI would import every command group to print one string.
|
|
54
54
|
qbraid-ai-token = "qbraid_cli.ai.token:main"
|
|
55
55
|
|
|
56
|
+
[tool.setuptools.package-data]
|
|
57
|
+
qbraid_cli = ["artifacts/pele.global.js", "artifacts/pele.LICENSE"]
|
|
58
|
+
|
|
56
59
|
[tool.black]
|
|
57
60
|
line-length = 110
|
|
58
61
|
target-version = ["py310", "py311", "py312", "py313"]
|
|
@@ -972,6 +972,10 @@ def agents_list(
|
|
|
972
972
|
for row, session in zip(output, sessions):
|
|
973
973
|
row["parent_agent_id"] = parents.get(session.session_id)
|
|
974
974
|
row["children"] = children.get(agent_of(session), [])
|
|
975
|
+
# How mail reaches each one now (qbraid-core wake_status); absent on older Core.
|
|
976
|
+
for row, wake in zip(output, _wakes_of(registry, sessions)):
|
|
977
|
+
if wake is not None:
|
|
978
|
+
row["wake_status"] = wake
|
|
975
979
|
print(json.dumps(output, indent=2))
|
|
976
980
|
return
|
|
977
981
|
|
|
@@ -2056,6 +2060,62 @@ class TrustTool(str, Enum):
|
|
|
2056
2060
|
CODEX = "codex"
|
|
2057
2061
|
|
|
2058
2062
|
|
|
2063
|
+
def _trust_folder_remote(compute: str, folder: Optional[str], tool: str, no: bool, json_output: bool) -> None:
|
|
2064
|
+
"""``trust-folder --compute``: the person's decision, recorded on the remote.
|
|
2065
|
+
|
|
2066
|
+
Person-only in the strict sense: an agent caller is refused, and a terminal
|
|
2067
|
+
is required (the question is asked here, never skipped with --yes), since a
|
|
2068
|
+
remote launch is always unattended and this is the one way to unblock
|
|
2069
|
+
NEEDS_TRUST_DECISION there. The remote runs its own ``trust-folder --yes
|
|
2070
|
+
--json``; its refusals (a folder above home, the root) come back as-is.
|
|
2071
|
+
"""
|
|
2072
|
+
import shlex # pylint: disable=import-outside-toplevel
|
|
2073
|
+
|
|
2074
|
+
if _caller_agent_reason() or _calling_session(_get_registry(), refuse_ambiguous=False):
|
|
2075
|
+
typer.echo("Only the person decides whether to trust a folder; an agent cannot.", err=True)
|
|
2076
|
+
raise typer.Exit(1)
|
|
2077
|
+
if _bad_alias(compute):
|
|
2078
|
+
typer.echo(f"--compute: invalid SSH alias {compute!r}.", err=True)
|
|
2079
|
+
raise typer.Exit(2)
|
|
2080
|
+
if not folder:
|
|
2081
|
+
typer.echo("--compute needs the remote folder to decide about.", err=True)
|
|
2082
|
+
raise typer.Exit(2)
|
|
2083
|
+
if folder.startswith("-") or any(ch in folder for ch in "\n\r\0"):
|
|
2084
|
+
typer.echo(f"Not a folder path: {folder!r}.", err=True)
|
|
2085
|
+
raise typer.Exit(2)
|
|
2086
|
+
if not _can_ask():
|
|
2087
|
+
typer.echo("Refusing to decide about a remote folder without a terminal to ask you.", err=True)
|
|
2088
|
+
raise typer.Exit(1)
|
|
2089
|
+
if no:
|
|
2090
|
+
question = f"Stop trusting {folder} on {compute}?"
|
|
2091
|
+
else:
|
|
2092
|
+
question = (
|
|
2093
|
+
f"Trust {folder} on {compute} for {tool}? Its own settings, hooks and MCP servers "
|
|
2094
|
+
"will run there without asking, including in unattended launches."
|
|
2095
|
+
)
|
|
2096
|
+
if not typer.confirm(question, default=False, err=True):
|
|
2097
|
+
typer.echo("Nothing changed.", err=True)
|
|
2098
|
+
raise typer.Exit(1)
|
|
2099
|
+
remote = f"qbraid agents trust-folder {shlex.quote(folder)} --tool {shlex.quote(tool)} --yes --json" + (
|
|
2100
|
+
" --no" if no else ""
|
|
2101
|
+
)
|
|
2102
|
+
stdout = _ssh_cmd(compute, remote)
|
|
2103
|
+
line = next((row for row in reversed(stdout.splitlines()) if row.strip().startswith("{")), "")
|
|
2104
|
+
try:
|
|
2105
|
+
result = json.loads(line)
|
|
2106
|
+
except ValueError:
|
|
2107
|
+
typer.echo(f"The remote recorded no decision ({compute}): {_remote_failure(stdout, '')}", err=True)
|
|
2108
|
+
raise typer.Exit(1) from None
|
|
2109
|
+
if json_output:
|
|
2110
|
+
print(json.dumps({**result, "compute": compute}))
|
|
2111
|
+
return
|
|
2112
|
+
shown = result.get("trustedAs") or result.get("folder") or folder
|
|
2113
|
+
if not result.get("trusted", not no):
|
|
2114
|
+
typer.echo(f"{shown} on {compute} is no longer trusted by your choice.")
|
|
2115
|
+
else:
|
|
2116
|
+
typer.echo(f"{shown} on {compute} is trusted for {tool}.")
|
|
2117
|
+
|
|
2118
|
+
|
|
2059
2119
|
@agents_app.command("trust-folder")
|
|
2060
2120
|
def agents_trust_folder(
|
|
2061
2121
|
folder: Optional[str] = typer.Argument(None, help="Folder to decide about (default: here)."),
|
|
@@ -2063,6 +2123,16 @@ def agents_trust_folder(
|
|
|
2063
2123
|
no: bool = typer.Option(False, "--no", help="Undo: stop trusting your home folder."),
|
|
2064
2124
|
yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation question."),
|
|
2065
2125
|
json_output: bool = typer.Option(False, "--json", help="Print the recorded decision."),
|
|
2126
|
+
compute: Optional[str] = typer.Option(
|
|
2127
|
+
None,
|
|
2128
|
+
"--compute",
|
|
2129
|
+
"-c",
|
|
2130
|
+
help=(
|
|
2131
|
+
"Decide for a folder on this compute server (SSH alias) instead of here. Launches "
|
|
2132
|
+
"there are unattended, so a folder they start in needs your decision first. You are "
|
|
2133
|
+
"asked at this terminal; --yes does not replace the question for a remote folder."
|
|
2134
|
+
),
|
|
2135
|
+
),
|
|
2066
2136
|
):
|
|
2067
2137
|
"""Decide whether an agent trusts a folder.
|
|
2068
2138
|
|
|
@@ -2071,7 +2141,14 @@ def agents_trust_folder(
|
|
|
2071
2141
|
your home folder the decision is standing (it covers every launch there,
|
|
2072
2142
|
including unattended ones) and is recorded with when and how; undo it with
|
|
2073
2143
|
--no. Only you can decide: an agent calling this is refused.
|
|
2144
|
+
|
|
2145
|
+
With --compute the decision is recorded on that server (the folder path is
|
|
2146
|
+
the remote one): a launch there with ``--compute`` has nobody at its
|
|
2147
|
+
terminal and fails with NEEDS_TRUST_DECISION until you decide.
|
|
2074
2148
|
"""
|
|
2149
|
+
if compute is not None:
|
|
2150
|
+
_trust_folder_remote(compute, folder, tool_choice.value, no, json_output)
|
|
2151
|
+
return
|
|
2075
2152
|
try:
|
|
2076
2153
|
from qbraid_core.services.agents.trust import ( # type: ignore[attr-defined]
|
|
2077
2154
|
HOME_TRUST_WARNING,
|
|
@@ -3754,6 +3831,8 @@ def _send_to_inbox( # pylint: disable=too-many-arguments
|
|
|
3754
3831
|
"request_id": request_id,
|
|
3755
3832
|
"already_delivered": bool(result.get("alreadyDelivered")),
|
|
3756
3833
|
"nudge": result["nudge"],
|
|
3834
|
+
# As the remote form of this command reports them.
|
|
3835
|
+
**({"wake": result["wakeStatus"]} if isinstance(result.get("wakeStatus"), dict) else {}),
|
|
3757
3836
|
}
|
|
3758
3837
|
)
|
|
3759
3838
|
return
|
|
@@ -3762,6 +3841,9 @@ def _send_to_inbox( # pylint: disable=too-many-arguments
|
|
|
3762
3841
|
f"[dim](id={_plain(result['messageId'])})[/dim]",
|
|
3763
3842
|
soft_wrap=True,
|
|
3764
3843
|
)
|
|
3844
|
+
wake = _wake_line(result.get("wakeStatus"))
|
|
3845
|
+
if wake:
|
|
3846
|
+
console.print(f" [{_wake_style(result['wakeStatus'])}]{_plain(wake)}[/]", soft_wrap=True)
|
|
3765
3847
|
_print_nudge(result["nudge"])
|
|
3766
3848
|
|
|
3767
3849
|
|
|
@@ -4040,6 +4122,7 @@ def agents_watch(
|
|
|
4040
4122
|
|
|
4041
4123
|
Streams live transcript from an agent session.
|
|
4042
4124
|
"""
|
|
4125
|
+
watching = False # this watch registered as a permission watcher
|
|
4043
4126
|
try:
|
|
4044
4127
|
# Remote watch: SSH and stream from remote
|
|
4045
4128
|
if compute:
|
|
@@ -4172,7 +4255,8 @@ def agents_watch(
|
|
|
4172
4255
|
from qbraid_core.services.agents.permissions import start_watching, stop_watching
|
|
4173
4256
|
|
|
4174
4257
|
if can_prompt or can_notify:
|
|
4175
|
-
start_watching(perm_session_id)
|
|
4258
|
+
start_watching(perm_session_id) # raises WatchLockBusy, registering nothing
|
|
4259
|
+
watching = True # only a start that registered has a stop (core #693)
|
|
4176
4260
|
|
|
4177
4261
|
if not stream:
|
|
4178
4262
|
sid_short = session.session_id[:8]
|
|
@@ -4461,7 +4545,7 @@ def agents_watch(
|
|
|
4461
4545
|
try:
|
|
4462
4546
|
from qbraid_core.services.agents.permissions import stop_watching
|
|
4463
4547
|
|
|
4464
|
-
if
|
|
4548
|
+
if watching:
|
|
4465
4549
|
stop_watching(perm_session_id)
|
|
4466
4550
|
except Exception:
|
|
4467
4551
|
pass
|
|
@@ -4991,6 +5075,54 @@ _WAIT_WHY = {
|
|
|
4991
5075
|
}
|
|
4992
5076
|
|
|
4993
5077
|
|
|
5078
|
+
def _wake_line(record) -> Optional[str]:
|
|
5079
|
+
"""Core's ``wake_status`` ({state, reason, detail, route}) as one plain line,
|
|
5080
|
+
or None on a Core without it (qbraid-core < 0.6.57)."""
|
|
5081
|
+
if not isinstance(record, dict) or "state" not in record:
|
|
5082
|
+
return None
|
|
5083
|
+
try:
|
|
5084
|
+
# pylint: disable-next=import-outside-toplevel
|
|
5085
|
+
from qbraid_core.services.agents.wake_route import describe # type: ignore[attr-defined]
|
|
5086
|
+
|
|
5087
|
+
return describe(record)
|
|
5088
|
+
except ImportError:
|
|
5089
|
+
detail = record.get("detail")
|
|
5090
|
+
return str(detail) if detail else str(record.get("state"))
|
|
5091
|
+
|
|
5092
|
+
|
|
5093
|
+
def _wake_style(record) -> str:
|
|
5094
|
+
state = record.get("state") if isinstance(record, dict) else None
|
|
5095
|
+
return {"will_read_now": "green", "waits_next_turn": "yellow", "held": "red"}.get(str(state), "dim")
|
|
5096
|
+
|
|
5097
|
+
|
|
5098
|
+
def _wakes_of(registry, sessions) -> list:
|
|
5099
|
+
"""``wake_status`` per session in one pass (shared state read once), or
|
|
5100
|
+
Nones on an older Core."""
|
|
5101
|
+
try:
|
|
5102
|
+
# pylint: disable-next=import-outside-toplevel
|
|
5103
|
+
from qbraid_core.services.agents.wake_route import wake_statuses # type: ignore[attr-defined]
|
|
5104
|
+
except ImportError:
|
|
5105
|
+
return [_wake_of(registry, s.session_id) for s in sessions]
|
|
5106
|
+
try:
|
|
5107
|
+
found = wake_statuses(registry, list(sessions))
|
|
5108
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
5109
|
+
return [None for _ in sessions]
|
|
5110
|
+
return [found.get(s.session_id) for s in sessions]
|
|
5111
|
+
|
|
5112
|
+
|
|
5113
|
+
def _wake_of(registry, session_id: str) -> Optional[dict]:
|
|
5114
|
+
"""``wake_status`` for a session on this machine, or None on an older Core."""
|
|
5115
|
+
try:
|
|
5116
|
+
# pylint: disable-next=import-outside-toplevel
|
|
5117
|
+
from qbraid_core.services.agents.wake_route import wake_status # type: ignore[attr-defined]
|
|
5118
|
+
except ImportError:
|
|
5119
|
+
return None
|
|
5120
|
+
try:
|
|
5121
|
+
return wake_status(registry, session_id)
|
|
5122
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
5123
|
+
return None
|
|
5124
|
+
|
|
5125
|
+
|
|
4994
5126
|
def _mail_wakes_label(wakes) -> Optional[str]:
|
|
4995
5127
|
"""whoami's ``mail_wakes`` (qbraid-core #606) as one line, or None."""
|
|
4996
5128
|
if not isinstance(wakes, dict) or "count" not in wakes:
|
|
@@ -5066,6 +5198,7 @@ def _deliver_to_many(
|
|
|
5066
5198
|
failed: list[tuple[str, str]] = []
|
|
5067
5199
|
forwards: dict = {}
|
|
5068
5200
|
waits: dict = {}
|
|
5201
|
+
wakes: dict = {}
|
|
5069
5202
|
for target_sid in targets:
|
|
5070
5203
|
try:
|
|
5071
5204
|
msg = send_message(
|
|
@@ -5082,6 +5215,7 @@ def _deliver_to_many(
|
|
|
5082
5215
|
forwarded = getattr(msg, "forwarded_from", None)
|
|
5083
5216
|
forwards[msg.id] = forwarded if isinstance(forwarded, str) else None
|
|
5084
5217
|
waits[msg.id] = _waits_for_next_turn(registry, msg)
|
|
5218
|
+
wakes[msg.id] = getattr(msg, "wake_status", None)
|
|
5085
5219
|
if isinstance(forwarded, str) and forwarded and not as_json:
|
|
5086
5220
|
old_sid, new_sid = str(forwarded), str(msg.to_session)
|
|
5087
5221
|
console.print(
|
|
@@ -5103,6 +5237,7 @@ def _deliver_to_many(
|
|
|
5103
5237
|
"type": message_type,
|
|
5104
5238
|
"forwarded_from": forwards.get(mid),
|
|
5105
5239
|
**({"held": waits[mid]} if waits.get(mid) else {}),
|
|
5240
|
+
**({"wake": wakes[mid]} if isinstance(wakes.get(mid), dict) else {}),
|
|
5106
5241
|
}
|
|
5107
5242
|
for sid, mid in delivered
|
|
5108
5243
|
],
|
|
@@ -5117,6 +5252,11 @@ def _deliver_to_many(
|
|
|
5117
5252
|
f"[green]→[/green] Sent to [bold]{_plain(sid)}[/bold] "
|
|
5118
5253
|
f"[dim](id={_plain(mid)}, type={_plain(message_type)})[/dim]"
|
|
5119
5254
|
)
|
|
5255
|
+
wake = _wake_line(wakes.get(mid))
|
|
5256
|
+
if wake:
|
|
5257
|
+
# Core's one answer to "when will it see this?" (wake_status).
|
|
5258
|
+
console.print(f" [{_wake_style(wakes[mid])}]{_plain(wake)}[/]", soft_wrap=True)
|
|
5259
|
+
continue
|
|
5120
5260
|
if waits.get(mid):
|
|
5121
5261
|
reason = str(waits[mid])
|
|
5122
5262
|
console.print(
|
|
@@ -5236,6 +5376,7 @@ def _send_remote( # pylint: disable=too-many-arguments
|
|
|
5236
5376
|
"request_id": result.get("requestId"),
|
|
5237
5377
|
"already_delivered": bool(result.get("alreadyDelivered")),
|
|
5238
5378
|
"nudge": result.get("nudge"),
|
|
5379
|
+
**({"wake": result["wakeStatus"]} if isinstance(result.get("wakeStatus"), dict) else {}),
|
|
5239
5380
|
}
|
|
5240
5381
|
)
|
|
5241
5382
|
return
|
|
@@ -5251,6 +5392,11 @@ def _send_remote( # pylint: disable=too-many-arguments
|
|
|
5251
5392
|
"machine": result.get("machineId"),
|
|
5252
5393
|
"request_id": result.get("requestId"),
|
|
5253
5394
|
"already_delivered": bool(result.get("alreadyDelivered")),
|
|
5395
|
+
**(
|
|
5396
|
+
{"wake": result["wakeStatus"]}
|
|
5397
|
+
if isinstance(result.get("wakeStatus"), dict)
|
|
5398
|
+
else {}
|
|
5399
|
+
),
|
|
5254
5400
|
}
|
|
5255
5401
|
],
|
|
5256
5402
|
"failed": [],
|
|
@@ -5265,6 +5411,9 @@ def _send_remote( # pylint: disable=too-many-arguments
|
|
|
5265
5411
|
+ f", request={_plain(result['requestId'])})[/dim]",
|
|
5266
5412
|
soft_wrap=True,
|
|
5267
5413
|
)
|
|
5414
|
+
wake = _wake_line(result.get("wakeStatus"))
|
|
5415
|
+
if wake:
|
|
5416
|
+
console.print(f" [{_wake_style(result['wakeStatus'])}]{_plain(wake)}[/]", soft_wrap=True)
|
|
5268
5417
|
if nudge:
|
|
5269
5418
|
_print_nudge(result.get("nudge"))
|
|
5270
5419
|
|
|
@@ -6388,6 +6537,7 @@ def agents_whoami(
|
|
|
6388
6537
|
("Inbox", info.get("inbox_path")),
|
|
6389
6538
|
("Canonical id", info.get("canonical_session_id")),
|
|
6390
6539
|
("Resumed from", info.get("resumed_from")),
|
|
6540
|
+
("Wake", _wake_line(info.get("wake_status"))),
|
|
6391
6541
|
("Mail waiting", _held_label(info.get("nudges_held"))),
|
|
6392
6542
|
("Mail wakes", _mail_wakes_label(info.get("mail_wakes"))),
|
|
6393
6543
|
(
|
|
@@ -6493,10 +6643,11 @@ def agents_team(
|
|
|
6493
6643
|
title=f"Team: {_plain(team_id)} ({len(members)} member{'s' if len(members) != 1 else ''})",
|
|
6494
6644
|
)
|
|
6495
6645
|
table.add_column("You", justify="center", no_wrap=True)
|
|
6496
|
-
table.add_column("Session", style="cyan", no_wrap=
|
|
6646
|
+
table.add_column("Session", style="cyan", no_wrap=True)
|
|
6497
6647
|
table.add_column("Type", style="yellow", no_wrap=True)
|
|
6498
6648
|
table.add_column("Status", no_wrap=True)
|
|
6499
6649
|
table.add_column("Unread", justify="right", no_wrap=True)
|
|
6650
|
+
table.add_column("Wake", no_wrap=True)
|
|
6500
6651
|
table.add_column("Last msg from", style="dim")
|
|
6501
6652
|
table.add_column("Last msg text", style="dim")
|
|
6502
6653
|
|
|
@@ -6517,15 +6668,21 @@ def agents_team(
|
|
|
6517
6668
|
session_display = s.session_id if wide else s.session_id[:12]
|
|
6518
6669
|
last_from = (last.from_session if wide else last.from_session[:12]) if last else "-"
|
|
6519
6670
|
last_text = (last.text[:60] + "…") if last and len(last.text) > 60 else (last.text if last else "-")
|
|
6520
|
-
|
|
6671
|
+
status_text = getattr(s.status, "value", s.status) or "unknown"
|
|
6672
|
+
status_style = status_styles.get(status_text, "dim")
|
|
6521
6673
|
unread_style = "bold red" if unread_count else "dim"
|
|
6674
|
+
wake = _wake_of(registry, s.session_id)
|
|
6675
|
+
wake_text = {"will_read_now": "now", "waits_next_turn": "next turn", "held": "held"}.get(
|
|
6676
|
+
str((wake or {}).get("state")), "-"
|
|
6677
|
+
)
|
|
6522
6678
|
|
|
6523
6679
|
table.add_row(
|
|
6524
6680
|
"★" if s.session_id == me_sid else "",
|
|
6525
6681
|
_plain(session_display),
|
|
6526
6682
|
_plain(s.agent_type or "worker"),
|
|
6527
|
-
f"[{status_style}]{
|
|
6683
|
+
f"[{status_style}]{_plain(status_text)}[/{status_style}]",
|
|
6528
6684
|
f"[{unread_style}]{unread_count}[/{unread_style}]",
|
|
6685
|
+
f"[{_wake_style(wake)}]{_plain(wake_text)}[/]",
|
|
6529
6686
|
_plain(last_from),
|
|
6530
6687
|
_plain(last_text),
|
|
6531
6688
|
)
|
|
@@ -6,6 +6,7 @@ import json
|
|
|
6
6
|
import re
|
|
7
7
|
from enum import Enum
|
|
8
8
|
from pathlib import Path
|
|
9
|
+
from tempfile import TemporaryDirectory
|
|
9
10
|
from typing import Callable, Optional, TypeVar
|
|
10
11
|
|
|
11
12
|
import typer
|
|
@@ -14,6 +15,7 @@ from rich.table import Table
|
|
|
14
15
|
from rich.text import Text
|
|
15
16
|
|
|
16
17
|
from qbraid_cli.agents.work import _safe
|
|
18
|
+
from qbraid_cli.artifacts.mermaid import PageError, with_pele
|
|
17
19
|
from qbraid_cli.handlers import handle_error
|
|
18
20
|
|
|
19
21
|
artifacts_app = typer.Typer(
|
|
@@ -24,6 +26,7 @@ CORE_MODULE = "qbraid_core.services.artifacts"
|
|
|
24
26
|
OLD_CORE = "qbraid artifacts requires qbraid-core 0.6.43 or newer; run: pip install -U qbraid-core"
|
|
25
27
|
PUBLIC_NOTE = "Anyone with the link can view this artifact."
|
|
26
28
|
MAX_ERROR = 300
|
|
29
|
+
MAX_HTML_BYTES = 5 * 1024 * 1024
|
|
27
30
|
_ID = re.compile(r"[a-f0-9]{32}")
|
|
28
31
|
_EMAIL = re.compile(r"[^@\s]+@[^@\s]+\.[^@\s]+")
|
|
29
32
|
# An error page (HTML/XML) rather than an API message: show the status instead.
|
|
@@ -56,7 +59,7 @@ def _error_text(err: Exception) -> str:
|
|
|
56
59
|
if isinstance(err, UnicodeDecodeError):
|
|
57
60
|
return "The file is not valid UTF-8; save it as UTF-8 and try again"
|
|
58
61
|
text = str(err)
|
|
59
|
-
if _MARKUP.search(text):
|
|
62
|
+
if _MARKUP.search(text) and not isinstance(err, PageError):
|
|
60
63
|
status = getattr(err, "status_code", None)
|
|
61
64
|
text = "Artifact request failed" + (f" (HTTP {status})" if status else "")
|
|
62
65
|
return text + "; the API returned a non-JSON error page"
|
|
@@ -98,6 +101,33 @@ def _check_file(path: Optional[Path]) -> None:
|
|
|
98
101
|
_fail("Provide one .html or .htm file")
|
|
99
102
|
|
|
100
103
|
|
|
104
|
+
def _with_mermaid(file: Optional[Path], send: Callable[[Optional[Path]], _Result]) -> _Result:
|
|
105
|
+
"""Send the file, or a same-named copy with Pele inlined when it has Mermaid blocks.
|
|
106
|
+
|
|
107
|
+
The file is read with Core's own reader (a bounded read of one regular
|
|
108
|
+
file, not through a symbolic link, and never blocking on a FIFO). The copy
|
|
109
|
+
keeps the name because Core titles an artifact after its file.
|
|
110
|
+
"""
|
|
111
|
+
if file is None:
|
|
112
|
+
return send(file)
|
|
113
|
+
from qbraid_core.services.artifacts import read_artifact_html
|
|
114
|
+
|
|
115
|
+
html = read_artifact_html(file)
|
|
116
|
+
rendered = with_pele(html)
|
|
117
|
+
if rendered is html:
|
|
118
|
+
return send(file)
|
|
119
|
+
data = rendered.encode("utf-8")
|
|
120
|
+
if len(data) > MAX_HTML_BYTES:
|
|
121
|
+
raise PageError(
|
|
122
|
+
"The file has Mermaid diagrams, and with the Pele renderer added it is over 5 MiB; "
|
|
123
|
+
"make the file smaller, or render the diagrams to SVG yourself"
|
|
124
|
+
)
|
|
125
|
+
with TemporaryDirectory() as tmp:
|
|
126
|
+
copy = Path(tmp, file.name)
|
|
127
|
+
copy.write_bytes(data) # bytes: no newline translation on Windows
|
|
128
|
+
return send(copy)
|
|
129
|
+
|
|
130
|
+
|
|
101
131
|
def _check_email(email: str) -> str:
|
|
102
132
|
if not _EMAIL.fullmatch(email):
|
|
103
133
|
raise typer.BadParameter("Provide a valid email address")
|
|
@@ -135,11 +165,15 @@ def publish(
|
|
|
135
165
|
"""Publish one standalone HTML file.
|
|
136
166
|
|
|
137
167
|
Publishing is immediate; there is no review queue. Publishing the same file
|
|
138
|
-
with the same title and access returns the existing artifact.
|
|
168
|
+
with the same title and access returns the existing artifact. Mermaid blocks
|
|
169
|
+
(<pre class="mermaid">) are drawn by an inlined copy of Pele.
|
|
139
170
|
"""
|
|
140
171
|
_check_file(file)
|
|
141
172
|
artifact = _run(
|
|
142
|
-
lambda client:
|
|
173
|
+
lambda client: _with_mermaid(
|
|
174
|
+
file,
|
|
175
|
+
lambda path: client.publish(path, title=title, visibility=visibility.value, duplicate=new),
|
|
176
|
+
)
|
|
143
177
|
)
|
|
144
178
|
if artifact.created is False and not as_json:
|
|
145
179
|
print("Already published")
|
|
@@ -192,8 +226,11 @@ def update(
|
|
|
192
226
|
"""
|
|
193
227
|
_check_file(file)
|
|
194
228
|
artifact = _run(
|
|
195
|
-
lambda client:
|
|
196
|
-
|
|
229
|
+
lambda client: _with_mermaid(
|
|
230
|
+
file,
|
|
231
|
+
lambda path: client.update(
|
|
232
|
+
slug, path=path, title=title, visibility=visibility.value if visibility else None
|
|
233
|
+
),
|
|
197
234
|
)
|
|
198
235
|
)
|
|
199
236
|
_emit(artifact, as_json)
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
# Copyright (c) 2026, qBraid Development Team
|
|
2
|
+
# All rights reserved.
|
|
3
|
+
"""Render an artifact's Mermaid blocks with an inlined copy of Pele.
|
|
4
|
+
|
|
5
|
+
The artifact sandbox blocks network requests, so a renderer must ship inside
|
|
6
|
+
the file. ``pele.global.js`` is Pele 1.13.0 (MIT, https://github.com/obsidianmd/pele).
|
|
7
|
+
|
|
8
|
+
The page is read with a small HTML tokenizer rather than a regular expression,
|
|
9
|
+
so a ``</body>`` or ``class="mermaid"`` inside a comment, a script, a
|
|
10
|
+
``<textarea>`` or a ``<template>`` is not taken for the real thing, and the
|
|
11
|
+
scan is linear in the size of the page.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from importlib.resources import files # nosemgrep
|
|
16
|
+
from typing import NamedTuple, Optional
|
|
17
|
+
|
|
18
|
+
PELE_MARKER = "/*! Pele "
|
|
19
|
+
# Elements whose content the browser does not parse as markup (with scripting on).
|
|
20
|
+
_RAW_TEXT = frozenset(
|
|
21
|
+
{"script", "style", "xmp", "iframe", "noembed", "noframes", "noscript", "textarea", "title"}
|
|
22
|
+
)
|
|
23
|
+
# Browsers use ASCII rules here: no Unicode case folding ("\u017f" is not "s")
|
|
24
|
+
# and no Unicode whitespace (NBSP is not a separator).
|
|
25
|
+
_SPACE = " \t\n\f\r"
|
|
26
|
+
_NAME_END = re.compile(r"[\s/>]", re.ASCII)
|
|
27
|
+
_ATTR_NAME_END = re.compile(r"[\s/>=]", re.ASCII)
|
|
28
|
+
_UNQUOTED_END = re.compile(r"[\s>]", re.ASCII)
|
|
29
|
+
_COMMENT_END = re.compile(r"--!?>")
|
|
30
|
+
_RAW_END = {name: re.compile(rf"</{name}[\s/>]", re.I | re.ASCII) for name in _RAW_TEXT}
|
|
31
|
+
_CLASS_SPLIT = re.compile(r"[ \t\n\f\r]+")
|
|
32
|
+
# Pele shows a parse error in place of a bad diagram and keeps rendering the rest.
|
|
33
|
+
# It mounts once the document is parsed, so blocks after the last </body> count too.
|
|
34
|
+
_MOUNT = (
|
|
35
|
+
"<script>(function () { function mount() {"
|
|
36
|
+
" for (const el of document.querySelectorAll('pre.mermaid, div.mermaid'))"
|
|
37
|
+
" pele.mount(el, el.textContent); }"
|
|
38
|
+
" if (document.readyState === 'loading')"
|
|
39
|
+
" document.addEventListener('DOMContentLoaded', mount); else mount(); })();</script>"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class PageError(ValueError):
|
|
44
|
+
"""The page cannot carry the renderer; the message is for the person, as is."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class _Tag(NamedTuple):
|
|
48
|
+
name: str
|
|
49
|
+
attrs: dict[str, str]
|
|
50
|
+
self_closing: bool
|
|
51
|
+
end: int # index just past the tag's ">"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _Scan(NamedTuple):
|
|
55
|
+
has_mermaid: bool
|
|
56
|
+
body_end: Optional[int] # start of the last real </body>, outside template/svg/math
|
|
57
|
+
open_at_end: Optional[str] # what the page ends inside of, if anything
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _skip_space(html: str, at: int) -> int:
|
|
61
|
+
while at < len(html) and html[at] in _SPACE:
|
|
62
|
+
at += 1
|
|
63
|
+
return at
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _is_letter(char: str) -> bool:
|
|
67
|
+
return char.isascii() and char.isalpha()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _tag(html: str, at: int) -> Optional[_Tag]:
|
|
71
|
+
"""The tag whose name starts at *at* (just past ``<`` or ``</``); None when unclosed."""
|
|
72
|
+
match = _NAME_END.search(html, at)
|
|
73
|
+
if match is None:
|
|
74
|
+
return None
|
|
75
|
+
name, at = html[at : match.start()].lower(), match.start()
|
|
76
|
+
attrs: dict[str, str] = {}
|
|
77
|
+
while True:
|
|
78
|
+
at = _skip_space(html, at)
|
|
79
|
+
if at >= len(html):
|
|
80
|
+
return None
|
|
81
|
+
if html[at] == ">":
|
|
82
|
+
return _Tag(name, attrs, html[at - 1] == "/", at + 1)
|
|
83
|
+
if html[at] == "/":
|
|
84
|
+
at += 1
|
|
85
|
+
continue
|
|
86
|
+
match = _ATTR_NAME_END.search(html, at + 1)
|
|
87
|
+
if match is None:
|
|
88
|
+
return None
|
|
89
|
+
key, at = html[at : match.start()].lower(), _skip_space(html, match.start())
|
|
90
|
+
value = ""
|
|
91
|
+
if at < len(html) and html[at] == "=":
|
|
92
|
+
at = _skip_space(html, at + 1)
|
|
93
|
+
if at < len(html) and html[at] in "\"'":
|
|
94
|
+
close = html.find(html[at], at + 1)
|
|
95
|
+
if close < 0:
|
|
96
|
+
return None
|
|
97
|
+
value, at = html[at + 1 : close], close + 1
|
|
98
|
+
else:
|
|
99
|
+
match = _UNQUOTED_END.search(html, at)
|
|
100
|
+
if match is None:
|
|
101
|
+
return None
|
|
102
|
+
value, at = html[at : match.start()], match.start()
|
|
103
|
+
attrs.setdefault(key, value) # the first of a repeated attribute wins
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _scan(html: str) -> _Scan: # pylint: disable=too-many-branches,too-many-return-statements
|
|
107
|
+
"""Walk the page's markup once, as a browser's tokenizer would (closely enough)."""
|
|
108
|
+
has_mermaid, body_end = False, None
|
|
109
|
+
template = foreign = 0
|
|
110
|
+
at = 0
|
|
111
|
+
while True:
|
|
112
|
+
at = html.find("<", at)
|
|
113
|
+
if at < 0:
|
|
114
|
+
break
|
|
115
|
+
if html.startswith("<!--", at):
|
|
116
|
+
if html.startswith(("<!-->", "<!--->"), at):
|
|
117
|
+
at += 5
|
|
118
|
+
continue
|
|
119
|
+
match = _COMMENT_END.search(html, at + 4)
|
|
120
|
+
if match is None:
|
|
121
|
+
return _Scan(has_mermaid, body_end, "a comment")
|
|
122
|
+
at = match.end()
|
|
123
|
+
continue
|
|
124
|
+
nxt = html[at + 1 : at + 2]
|
|
125
|
+
closing = nxt == "/"
|
|
126
|
+
letter = html[at + 2 : at + 3] if closing else nxt
|
|
127
|
+
if nxt in ("!", "?") or (closing and letter not in ("", ">") and not _is_letter(letter)):
|
|
128
|
+
close = html.find(">", at + 1) # a bogus comment ends at the next ">"
|
|
129
|
+
if close < 0:
|
|
130
|
+
return _Scan(has_mermaid, body_end, "a comment")
|
|
131
|
+
at = close + 1
|
|
132
|
+
continue
|
|
133
|
+
if not _is_letter(letter):
|
|
134
|
+
at += 3 if closing and letter == ">" else 1 # "</>" is dropped; "<" alone is text
|
|
135
|
+
continue
|
|
136
|
+
start = at
|
|
137
|
+
tag = _tag(html, at + (2 if closing else 1))
|
|
138
|
+
if tag is None:
|
|
139
|
+
return _Scan(has_mermaid, body_end, "a tag")
|
|
140
|
+
at = tag.end
|
|
141
|
+
if closing:
|
|
142
|
+
if tag.name == "template":
|
|
143
|
+
template = max(template - 1, 0)
|
|
144
|
+
elif tag.name in ("svg", "math"):
|
|
145
|
+
foreign = max(foreign - 1, 0)
|
|
146
|
+
elif tag.name == "body" and not template and not foreign:
|
|
147
|
+
body_end = start
|
|
148
|
+
continue
|
|
149
|
+
if tag.name == "plaintext":
|
|
150
|
+
return _Scan(has_mermaid, body_end, "a <plaintext> element")
|
|
151
|
+
if tag.name in _RAW_TEXT:
|
|
152
|
+
match = _RAW_END[tag.name].search(html, at)
|
|
153
|
+
if match is None:
|
|
154
|
+
return _Scan(has_mermaid, body_end, f"a <{tag.name}> element")
|
|
155
|
+
at = match.start() # its end tag is read on the next pass
|
|
156
|
+
continue
|
|
157
|
+
if tag.name == "template":
|
|
158
|
+
template += 1
|
|
159
|
+
elif tag.name in ("svg", "math") and not tag.self_closing:
|
|
160
|
+
foreign += 1
|
|
161
|
+
elif tag.name in ("pre", "div") and not template:
|
|
162
|
+
# What the mount loop's "pre.mermaid, div.mermaid" selects (the API
|
|
163
|
+
# serves every artifact in standards mode: class names match exactly).
|
|
164
|
+
has_mermaid = has_mermaid or "mermaid" in _CLASS_SPLIT.split(tag.attrs.get("class", ""))
|
|
165
|
+
if template:
|
|
166
|
+
return _Scan(has_mermaid, body_end, "a <template> element")
|
|
167
|
+
if foreign:
|
|
168
|
+
return _Scan(has_mermaid, body_end, "an <svg> or <math> element")
|
|
169
|
+
return _Scan(has_mermaid, body_end, None)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def with_pele(html: str) -> str:
|
|
173
|
+
"""Return ``html`` with Pele inlined when it has Mermaid blocks and no Pele yet.
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
html: The artifact's HTML.
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
The same string object when nothing changes, otherwise a copy with the
|
|
180
|
+
Pele library and a mount loop inserted before the last real ``</body>``
|
|
181
|
+
(or at the end when there is none).
|
|
182
|
+
|
|
183
|
+
Raises:
|
|
184
|
+
PageError: The page has Mermaid blocks but no ``</body>``, and ends
|
|
185
|
+
inside a comment, tag or element where the scripts would not run.
|
|
186
|
+
"""
|
|
187
|
+
if PELE_MARKER in html:
|
|
188
|
+
return html
|
|
189
|
+
scan = _scan(html)
|
|
190
|
+
if not scan.has_mermaid:
|
|
191
|
+
return html
|
|
192
|
+
at = scan.body_end
|
|
193
|
+
if at is None:
|
|
194
|
+
if scan.open_at_end:
|
|
195
|
+
raise PageError(
|
|
196
|
+
f"The file has Mermaid diagrams but ends inside {scan.open_at_end}, where "
|
|
197
|
+
"the Pele renderer would not run; close it, or end the page with </body>"
|
|
198
|
+
)
|
|
199
|
+
at = len(html)
|
|
200
|
+
library = files(__package__).joinpath("pele.global.js").read_text("utf-8")
|
|
201
|
+
scripts = "<script>" + library.replace("</script", "<\\/script") + "</script>" + _MOUNT
|
|
202
|
+
return html[:at] + scripts + html[at:]
|