Move pack-specific scripts into their pack repos
scripts/outlook-auth.py, playwright-browsers.py, and simplex-address.py now live in pack.outlook/pack.browser/pack.simplex under scripts/. bootstrap.sh, the Outlook bridge hints, and the docs reference packs/<name>/scripts/; the Outlook auth helper locates the checkout (and its default token path) by walking up to the semif_agent package.
This commit is contained in:
1 parent
1329de42c4
commit
16e8583921
11 files changed
+27
-385
No files matched your search
@@ -461,10 +461,10 @@ PY
|
||||
# no working global IPv6 route, even though the CDN serves over IPv4. The
|
||||
# helper fetches the same pinned artifacts over IPv4 and lays them out
|
||||
# where Playwright expects them, so the install becomes a no-op.
|
||||
echo "== retrying over IPv4 (scripts/playwright-browsers.py)" >&2
|
||||
PLAYWRIGHT_BROWSERS_PATH="$BROWSERS" "$PYTHON" "$REPO_ROOT/scripts/playwright-browsers.py" \
|
||||
echo "== retrying over IPv4 (packs/browser/scripts/playwright-browsers.py)" >&2
|
||||
PLAYWRIGHT_BROWSERS_PATH="$BROWSERS" "$PYTHON" "$REPO_ROOT/packs/browser/scripts/playwright-browsers.py" \
|
||||
--browsers-path "$BROWSERS" --engine "$BROWSER_ENGINE" \
|
||||
|| echo "WARN: browser priming failed; re-run: $PYTHON scripts/playwright-browsers.py --browsers-path $BROWSERS" >&2
|
||||
|| echo "WARN: browser priming failed; re-run: $PYTHON packs/browser/scripts/playwright-browsers.py --browsers-path $BROWSERS" >&2
|
||||
else
|
||||
echo "WARN: re-run: PLAYWRIGHT_BROWSERS_PATH=$BROWSERS $PYTHON -m playwright install $BROWSER_ENGINE" >&2
|
||||
fi
|
||||
@@ -581,14 +581,14 @@ if command -v systemctl >/dev/null 2>&1; then
|
||||
if systemctl --user is-active --quiet semif-simplex.service 2>/dev/null; then
|
||||
echo "== ensuring the SimpleX bot contact address exists"
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if SIMPLEX_ADDRESS="$("$PYTHON" "$REPO_ROOT/scripts/simplex-address.py" 2>/dev/null)"; then
|
||||
if SIMPLEX_ADDRESS="$("$PYTHON" "$REPO_ROOT/packs/simplex/scripts/simplex-address.py" 2>/dev/null)"; then
|
||||
printf '%s\n' "$SIMPLEX_ADDRESS" | sed 's/^/ /'
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
if [[ -z "$SIMPLEX_ADDRESS" ]]; then
|
||||
echo "WARN: bot address not ready; run: $PYTHON scripts/simplex-address.py" >&2
|
||||
echo "WARN: bot address not ready; run: $PYTHON packs/simplex/scripts/simplex-address.py" >&2
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
@@ -610,7 +610,7 @@ if [[ -n "$BRIDGE_FORWARD_WS" ]] && command -v systemctl >/dev/null 2>&1; then
|
||||
if systemctl --user is-active --quiet semif-simplex-forward.service 2>/dev/null; then
|
||||
echo "== ensuring the forwarding bridge contact address exists"
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if FORWARD_ADDRESS="$("$PYTHON" "$REPO_ROOT/scripts/simplex-address.py" --ws-url "$BRIDGE_FORWARD_WS" 2>/dev/null)"; then
|
||||
if FORWARD_ADDRESS="$("$PYTHON" "$REPO_ROOT/packs/simplex/scripts/simplex-address.py" --ws-url "$BRIDGE_FORWARD_WS" 2>/dev/null)"; then
|
||||
printf '%s\n' "$FORWARD_ADDRESS" | sed 's/^/ /'
|
||||
break
|
||||
fi
|
||||
@@ -713,7 +713,7 @@ SimpleX command gateway (commands only):
|
||||
systemctl --user status semif-simplex semif-gateway
|
||||
journalctl --user -u semif-gateway -f
|
||||
- Its user contact address is printed above; re-print (creating if needed) with:
|
||||
"$PYTHON" scripts/simplex-address.py
|
||||
"$PYTHON" packs/simplex/scripts/simplex-address.py
|
||||
Add that address as a contact in your SimpleX app.
|
||||
- Then put your contactId/display name in config.json
|
||||
gateway.simplex.allowed_users (discover the id from a 'gateway_denied' trace
|
||||
@@ -739,7 +739,7 @@ SimpleX forwarding bridge (messaging UX for skills):
|
||||
- Runs as 'semif-simplex-forward' (a second bot daemon/profile, port $SIMPLEX_FORWARD_PORT)
|
||||
and 'semif-bridge' (the standalone bridge API). Its contact address is printed
|
||||
above; re-print with:
|
||||
"$PYTHON" scripts/simplex-address.py --ws-url ws://127.0.0.1:$SIMPLEX_FORWARD_PORT
|
||||
"$PYTHON" packs/simplex/scripts/simplex-address.py --ws-url ws://127.0.0.1:$SIMPLEX_FORWARD_PORT
|
||||
- Skills reach it over HTTP at the address derived from bridges.simplex
|
||||
(host/port, default http://127.0.0.1:5227); simplex.connect_link shows its
|
||||
address and simplex.next_message reads messages sent to it.
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Authorize the Outlook bridge with Microsoft (OAuth2 device code flow).
|
||||
|
||||
The bridge reads the user's Microsoft account through Microsoft Graph; that
|
||||
needs an access token, obtained once here with the **device code flow** (a public
|
||||
client, no secret):
|
||||
|
||||
1. register an Entra ID app (see below) and put its client id in
|
||||
`config.json` under `bridges.outlook.client_id`;
|
||||
2. run this script;
|
||||
3. open the printed URL on any device, enter the printed code, and sign in;
|
||||
4. the resulting tokens are saved (0600) to `.runtime/outlook/token.json`,
|
||||
which the bridge loads and refreshes automatically.
|
||||
|
||||
One-time app registration (Entra ID / Azure AD):
|
||||
|
||||
- "App registrations" -> "New registration".
|
||||
- Supported account types: include personal Microsoft accounts if the user
|
||||
has an @outlook.com/@hotmail.com account (e.g. "Accounts in any
|
||||
organizational directory and personal Microsoft accounts").
|
||||
- Authentication -> "Allow public client flows" = Yes (no redirect URI is
|
||||
needed for device code).
|
||||
- No API permissions need adding by hand: the script requests the delegated
|
||||
scopes it needs and the user consents during sign-in.
|
||||
|
||||
Usage (from the checkout):
|
||||
|
||||
.runtime/venv/bin/python scripts/outlook-auth.py [--config config.json]
|
||||
[--client-id ID]
|
||||
[--tenant common]
|
||||
[--token-path PATH]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
from semif_agent.bridges.outlook_client import ( # noqa: E402
|
||||
DEFAULT_TENANT,
|
||||
OutlookError,
|
||||
run_device_code_flow,
|
||||
save_token,
|
||||
)
|
||||
|
||||
DEFAULT_TOKEN_PATH = str(REPO_ROOT / ".runtime" / "outlook" / "token.json")
|
||||
|
||||
|
||||
def _block(config_path: str) -> dict:
|
||||
try:
|
||||
with open(config_path, encoding="utf-8") as handle:
|
||||
config = json.load(handle)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
block = (config.get("bridges", {}) or {}).get("outlook", {}) or {}
|
||||
return block if isinstance(block, dict) else {}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", default="config.json")
|
||||
parser.add_argument("--client-id", default=None, help="override bridges.outlook.client_id")
|
||||
parser.add_argument("--tenant", default=None, help="override bridges.outlook.tenant (default common)")
|
||||
parser.add_argument("--token-path", default=None, help="where to save the tokens")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
block = _block(args.config)
|
||||
client_id = str(args.client_id or block.get("client_id") or "").strip()
|
||||
tenant = str(args.tenant or block.get("tenant") or DEFAULT_TENANT).strip() or DEFAULT_TENANT
|
||||
token_path = str(args.token_path or block.get("token_path") or DEFAULT_TOKEN_PATH)
|
||||
scopes = block.get("scopes") or None
|
||||
|
||||
if not client_id:
|
||||
print(
|
||||
"no Microsoft client id configured: set bridges.outlook.client_id in "
|
||||
f"{args.config} (or pass --client-id)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
try:
|
||||
token = run_device_code_flow(client_id, tenant, scopes)
|
||||
except OutlookError as exc:
|
||||
print(f"authorization failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
except KeyboardInterrupt:
|
||||
print("\ncancelled", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
save_token(token_path, token)
|
||||
print(f"saved Outlook authorization to {token_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,172 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prime Playwright's browser cache over IPv4 (a fallback for `playwright install`).
|
||||
|
||||
`playwright install` downloads through Playwright's own Node fetcher, which
|
||||
forces `autoSelectFamily` with a custom dual-stack resolver that prefers IPv6.
|
||||
On a host that has an IPv6 address (often a ULA) but no working global IPv6
|
||||
route, that first IPv6 connection hangs instead of falling back to IPv4, so the
|
||||
download stalls until the socket timeout and `playwright install` fails even
|
||||
though the CDN is reachable over IPv4.
|
||||
|
||||
This helper downloads the exact pinned artifacts Playwright expects, forcing
|
||||
IPv4, and lays them out under `PLAYWRIGHT_BROWSERS_PATH` with the
|
||||
`INSTALLATION_COMPLETE` marker Playwright checks, so the normal install (and the
|
||||
browser bridge) then works. It reads revisions/versions from the installed
|
||||
Playwright's own `browsers.json`, so it tracks version bumps automatically.
|
||||
|
||||
Idempotent: an artifact with its marker present is skipped. Only Chromium (plus
|
||||
its headless shell and ffmpeg) is handled; Firefox/WebKit have no such helper.
|
||||
|
||||
Usage:
|
||||
scripts/playwright-browsers.py --browsers-path .runtime/browser
|
||||
scripts/playwright-browsers.py --browsers-path .runtime/browser --engine chromium
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
#: The CDN mirror Playwright's fetcher falls back to and that serves the exact
|
||||
#: Chrome-for-Testing layout over a redirect (IPv4 works).
|
||||
CDN = "https://cdn.playwright.dev"
|
||||
|
||||
#: Executables that must stay executable after a pure-Python unzip (which does
|
||||
#: not preserve permissions). Relative to each browser's directory.
|
||||
_EXECUTABLES = {
|
||||
"chromium": ("chrome-linux64/chrome",),
|
||||
"chromium_headless_shell": ("chrome-headless-shell-linux64/chrome-headless-shell",),
|
||||
"ffmpeg": ("ffmpeg-linux",),
|
||||
}
|
||||
|
||||
|
||||
def _arch_suffix() -> str:
|
||||
machine = platform.machine().lower()
|
||||
return "arm64" if machine in ("aarch64", "arm64") else "x64"
|
||||
|
||||
|
||||
def _cft_paths(arch: str) -> dict[str, str]:
|
||||
if arch == "arm64":
|
||||
return {
|
||||
"chromium": "linux-arm64/chrome-linux-arm64.zip",
|
||||
"chromium_headless_shell": "linux-arm64/chrome-headless-shell-linux-arm64.zip",
|
||||
"ffmpeg": "ffmpeg-linux-arm64.zip",
|
||||
}
|
||||
return {
|
||||
"chromium": "linux64/chrome-linux64.zip",
|
||||
"chromium_headless_shell": "linux64/chrome-headless-shell-linux64.zip",
|
||||
"ffmpeg": "ffmpeg-linux.zip",
|
||||
}
|
||||
|
||||
|
||||
def _browsers_json() -> dict:
|
||||
import playwright # the package the venv already has
|
||||
|
||||
path = Path(playwright.__file__).resolve().parent / "driver" / "package" / "browsers.json"
|
||||
with open(path) as handle:
|
||||
return json.load(handle)
|
||||
|
||||
|
||||
def _artifacts(browsers_json: dict, arch: str) -> list[tuple[str, str]]:
|
||||
"""List of `(directory_name, download_path)` Playwright expects."""
|
||||
suffixes = _cft_paths(arch)
|
||||
wanted = {
|
||||
"chromium": ("chromium", "chromium"),
|
||||
"chromium-headless-shell": ("chromium_headless_shell", "chromium_headless_shell"),
|
||||
"ffmpeg": ("ffmpeg", "ffmpeg"),
|
||||
}
|
||||
out: list[tuple[str, str]] = []
|
||||
for browser in browsers_json.get("browsers", []):
|
||||
name = browser.get("name")
|
||||
if name not in wanted or not browser.get("installByDefault", True):
|
||||
continue
|
||||
slug, key = wanted[name]
|
||||
revision = browser["revision"]
|
||||
if key == "ffmpeg":
|
||||
path = f"builds/ffmpeg/{revision}/{suffixes['ffmpeg']}"
|
||||
else:
|
||||
path = f"builds/cft/{browser['browserVersion']}/{suffixes[key]}"
|
||||
out.append((f"{slug}-{revision}", path))
|
||||
return out
|
||||
|
||||
|
||||
def _download(url: str, dest: str) -> None:
|
||||
if shutil.which("curl"):
|
||||
subprocess.run(
|
||||
["curl", "-4", "-fL", "--retry", "3", "-m", "600", "-o", dest, url],
|
||||
check=True,
|
||||
)
|
||||
return
|
||||
# No curl: urllib may pick IPv6 on a broken host, but it is the best we have.
|
||||
print(f" (curl not found; using urllib for {url})", flush=True)
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "semif-bootstrap"})
|
||||
with urllib.request.urlopen(request, timeout=600) as response, open(dest, "wb") as handle:
|
||||
shutil.copyfileobj(response, handle)
|
||||
|
||||
|
||||
def _extract(archive: str, target: Path, directory_name: str) -> None:
|
||||
if shutil.which("unzip"):
|
||||
subprocess.run(["unzip", "-q", "-o", archive, "-d", str(target)], check=True)
|
||||
else:
|
||||
with zipfile.ZipFile(archive) as zf:
|
||||
zf.extractall(target)
|
||||
for relative in _EXECUTABLES.get(directory_name.split("-")[0], ()):
|
||||
candidate = target / relative
|
||||
if candidate.is_file():
|
||||
candidate.chmod(candidate.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
||||
|
||||
|
||||
def _install_one(browsers_path: Path, directory_name: str, download_path: str) -> bool:
|
||||
target = browsers_path / directory_name
|
||||
marker = target / "INSTALLATION_COMPLETE"
|
||||
if marker.is_file():
|
||||
print(f" = {directory_name} already installed")
|
||||
return True
|
||||
url = f"{CDN}/{download_path}"
|
||||
print(f" + {directory_name} <- {url}")
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix="semif-browser-") as tmp:
|
||||
archive = os.path.join(tmp, "download.zip")
|
||||
_download(url, archive)
|
||||
_extract(archive, target, directory_name)
|
||||
marker.write_text("")
|
||||
return True
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Prime Playwright's browser cache over IPv4.")
|
||||
parser.add_argument("--browsers-path", required=True, help="PLAYWRIGHT_BROWSERS_PATH to populate")
|
||||
parser.add_argument("--engine", default="chromium", help="only 'chromium' is supported by this helper")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.engine != "chromium":
|
||||
print(f"helper only primes chromium, not {args.engine!r}; nothing to do", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
browsers_path = Path(args.browsers_path).expanduser().resolve()
|
||||
browsers_path.mkdir(parents=True, exist_ok=True)
|
||||
arch = _arch_suffix()
|
||||
artifacts = _artifacts(_browsers_json(), arch)
|
||||
if not artifacts:
|
||||
print("no chromium artifacts found in playwright's browsers.json", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"priming Playwright browsers into {browsers_path} ({arch}, IPv4)")
|
||||
for directory_name, download_path in artifacts:
|
||||
_install_one(browsers_path, directory_name, download_path)
|
||||
print("done; 'playwright install chromium' should now be a no-op")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,87 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Print (creating if needed) the SimpleX bot's contact address.
|
||||
|
||||
The gateway talks to a local `simplex-chat` daemon running as a bot
|
||||
(`--create-bot-display-name`, see simplex_chat in config.json). To connect a
|
||||
phone/client to the bot you need the bot's *user* contact address, not a chat
|
||||
relay address; this queries the daemon's WebSocket API, creating the address on
|
||||
first run, and prints the short link (and full link). Requires the daemon to be
|
||||
running.
|
||||
|
||||
Usage:
|
||||
.runtime/venv/bin/python scripts/simplex-address.py [--config config.json]
|
||||
[--ws-url ws://...]
|
||||
[--user-id 1]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
|
||||
|
||||
def _ws_url(config_path: str) -> str:
|
||||
try:
|
||||
with open(config_path) as fh:
|
||||
cfg = json.load(fh)
|
||||
except (OSError, ValueError):
|
||||
return "ws://127.0.0.1:5226"
|
||||
return str(cfg.get("gateway", {}).get("simplex", {}).get("ws_url") or "ws://127.0.0.1:5226")
|
||||
|
||||
|
||||
async def _resolve(ws_url: str, user_id: int) -> dict:
|
||||
try:
|
||||
import websockets
|
||||
except ImportError:
|
||||
raise SystemExit("the `websockets` package is required (pip install websockets)")
|
||||
async with websockets.connect(ws_url, max_size=None) as ws:
|
||||
|
||||
async def cmd(command: str) -> dict:
|
||||
await ws.send(json.dumps({"corrId": "addr", "cmd": command}))
|
||||
raw = await asyncio.wait_for(ws.recv(), timeout=20)
|
||||
return json.loads(raw).get("resp", {}) or {}
|
||||
|
||||
resp = await cmd(f"/_show_address {user_id}")
|
||||
if resp.get("type") == "userContactLink":
|
||||
return resp.get("contactLink", {}) or {}
|
||||
# No address yet -> create one (APICreateMyAddress).
|
||||
resp = await cmd(f"/_address {user_id}")
|
||||
if resp.get("type") == "userContactLinkCreated":
|
||||
return {"connLinkContact": resp.get("connLinkContact", {}) or {}}
|
||||
raise SystemExit(f"could not read or create address: {json.dumps(resp)[:300]}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("--config", default="config.json")
|
||||
ap.add_argument("--ws-url", default=None)
|
||||
ap.add_argument("--user-id", type=int, default=1)
|
||||
args = ap.parse_args()
|
||||
|
||||
ws_url = args.ws_url or _ws_url(args.config)
|
||||
try:
|
||||
link = asyncio.run(_resolve(ws_url, args.user_id))
|
||||
except OSError as exc:
|
||||
print(f"cannot reach simplex-chat at {ws_url}: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
except asyncio.TimeoutError:
|
||||
print(f"simplex-chat at {ws_url} did not answer", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
conn = link.get("connLinkContact", {}) or link
|
||||
short = conn.get("connShortLink")
|
||||
full = conn.get("connFullLink")
|
||||
if short:
|
||||
print(short)
|
||||
if full:
|
||||
print(full)
|
||||
if not (short or full):
|
||||
print("no contact address found", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user