Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(ci): distribute nightly SDK artifacts with pinned runtime smoke gates
thinhlpg7a8e9125d4b2
diff --git a/.github/workflows/agent-sdk-nightly.yml b/.github/workflows/agent-sdk-nightly.ymlnew file mode 100644index 000000000..47c10da24--- /dev/null+++ b/.github/workflows/agent-sdk-nightly.yml@@ -0,0 +1,137 @@+name: Agent SDK Nightly++on:+ workflow_run:+ workflows: ['Jan Agent CLI - Nightly Build']+ types: [completed]+ branches: [main]+ workflow_dispatch:+ pull_request:+ paths:+ - '.github/workflows/agent-sdk-nightly.yml'+ - 'scripts/sdk-nightly/**'+ - 'packages/agent-sdk/**'+ - 'sdk/python/**'+ - 'protocol/rpc-schema.json'++permissions:+ contents: read++# Only one publisher can advance latest. PR checks do not cancel a release.+concurrency:+ group: sdk-nightly-${{ github.event_name == 'pull_request' && github.event.pull_request.number || 'publish' }}+ cancel-in-progress: false++jobs:+ package:+ if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success'+ runs-on: ubuntu-22.04+ outputs:+ build: ${{ steps.metadata.outputs.build }}+ publish: ${{ steps.metadata.outputs.publish }}+ ref: ${{ steps.metadata.outputs.ref }}+ steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ github.event.workflow_run.head_sha || github.sha }}+ persist-credentials: false+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ - uses: actions/setup-python@v5+ with:+ python-version: '3.11'+ - name: Validate generated SDK types+ working-directory: packages/agent-sdk+ run: |+ npm install --workspaces=false --ignore-scripts+ npm run check-types --workspaces=false+ - name: Install wheel builder+ run: python -m pip install build==1.2.2.post1+ - name: Identify immutable build+ id: metadata+ env:+ SOURCE_REVISION: ${{ github.event.workflow_run.head_sha || github.sha }}+ TRUSTED: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && (github.event_name != 'workflow_run' || github.event.workflow_run.head_repository.full_name == github.repository) }}+ run: |+ echo "ref=$SOURCE_REVISION" >> "$GITHUB_OUTPUT"+ echo "build=$SOURCE_REVISION-$GITHUB_RUN_ID.$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT"+ echo "publish=$TRUSTED" >> "$GITHUB_OUTPUT"+ - name: Package both SDKs and snapshot runtime+ env:+ SOURCE_REVISION: ${{ steps.metadata.outputs.ref }}+ run: >-+ python scripts/sdk-nightly/package.py --output sdk-dist+ --sha "$SOURCE_REVISION" --build "$GITHUB_RUN_ID.$GITHUB_RUN_ATTEMPT"+ - uses: actions/upload-artifact@v4+ with:+ name: sdk-nightly+ path: sdk-dist/+ if-no-files-found: error+ - name: Stage immutable public artifacts+ if: steps.metadata.outputs.publish == 'true'+ env:+ AWS_ACCESS_KEY_ID: ${{ secrets.DELTA_AWS_ACCESS_KEY_ID }}+ AWS_SECRET_ACCESS_KEY: ${{ secrets.DELTA_AWS_SECRET_ACCESS_KEY }}+ AWS_DEFAULT_REGION: ${{ secrets.DELTA_AWS_REGION }}+ AWS_EC2_METADATA_DISABLED: 'true'+ BUCKET: ${{ secrets.DELTA_AWS_S3_BUCKET_NAME }}+ BUILD: ${{ steps.metadata.outputs.build }}+ run: >-+ aws s3 cp sdk-dist/ "s3://$BUCKET/sdk-nightly/$BUILD/" --recursive+ --cache-control 'public,max-age=31536000,immutable'++ smoke:+ needs: package+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-22.04, ubuntu-24.04-arm, macos-15, macos-15-intel, windows-2022]+ runs-on: ${{ matrix.os }}+ steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ needs.package.outputs.ref }}+ persist-credentials: false+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ - uses: actions/setup-python@v5+ with:+ python-version: '3.11'+ - uses: actions/download-artifact@v4+ if: needs.package.outputs.publish != 'true'+ with:+ name: sdk-nightly+ path: sdk-dist+ - name: Smoke public downloads against pinned runtime+ if: needs.package.outputs.publish == 'true'+ env:+ BUILD: ${{ needs.package.outputs.build }}+ run: python scripts/sdk-nightly/smoke.py "https://delta.jan.ai/sdk-nightly/$BUILD/manifest.json"+ shell: bash+ - name: Smoke PR artifacts without publication credentials+ if: needs.package.outputs.publish != 'true'+ run: python scripts/sdk-nightly/smoke.py sdk-dist/manifest.json --artifacts sdk-dist++ promote:+ needs: [package, smoke]+ if: needs.package.outputs.publish == 'true'+ runs-on: ubuntu-22.04+ steps:+ - uses: actions/download-artifact@v4+ with:+ name: sdk-nightly+ path: sdk-dist+ # All versioned assets are already public and tested. A single object PUT+ # switches each discovery document from one complete build to another.+ - name: Advance validated nightly discovery+ env:+ AWS_ACCESS_KEY_ID: ${{ secrets.DELTA_AWS_ACCESS_KEY_ID }}+ AWS_SECRET_ACCESS_KEY: ${{ secrets.DELTA_AWS_SECRET_ACCESS_KEY }}+ AWS_DEFAULT_REGION: ${{ secrets.DELTA_AWS_REGION }}+ AWS_EC2_METADATA_DISABLED: 'true'+ BUCKET: ${{ secrets.DELTA_AWS_S3_BUCKET_NAME }}+ run: |+ aws s3 cp sdk-dist/manifest.json "s3://$BUCKET/sdk-nightly/manifest.json" --content-type application/json --cache-control no-cache+ aws s3 cp sdk-dist/index.html "s3://$BUCKET/sdk-nightly/index.html" --content-type text/html --cache-control no-cachediff --git a/scripts/sdk-nightly/package.py b/scripts/sdk-nightly/package.pynew file mode 100644index 000000000..e773eb243--- /dev/null+++ b/scripts/sdk-nightly/package.py@@ -0,0 +1,118 @@+"""Build versioned SDK artifacts and snapshot their compatible runtime manifest.++Only the workflow promotes manifest.json, after all platform smoke jobs succeed.+The output directory must be new: a release identity is never repackaged in place.+"""+import argparse+import hashlib+import html+import json+from pathlib import Path+import re+import shutil+import subprocess+import sys+import tempfile+import tomllib+from urllib.parse import quote+from urllib.request import urlopen++ROOT = Path(__file__).resolve().parents[2]+PLATFORMS = ["linux-x86_64", "linux-aarch64", "darwin-universal", "windows-x86_64"]+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--build", required=True, help="GitHub run ID and attempt, e.g. 123456.1")+ parser.add_argument("--sha", required=True)+ parser.add_argument("--base-url", default="https://delta.jan.ai/sdk-nightly")+ parser.add_argument("--runtime-manifest", default="https://delta.jan.ai/agent-nightly/manifest.json")+ args = parser.parse_args()+ if not re.fullmatch(r"[0-9]+\.[0-9]+", args.build) or not re.fullmatch(r"[0-9a-f]{40}", args.sha):+ parser.error("build must be run.attempt and sha must be a full lowercase commit SHA")+ identity = f"{args.sha}-{args.build}"+ base_url = f"{args.base_url.rstrip('/')}/{identity}"+ with urlopen(args.runtime_manifest, timeout=60) as response:+ snapshot = response.read()+ runtime = json.loads(snapshot)+ for platform in PLATFORMS:+ entry = runtime["platforms"][platform]+ if not entry["url"].startswith("https://") or not re.fullmatch(r"[0-9a-f]{64}", entry["sha256"]):+ raise ValueError(f"Invalid published runtime for {platform}")+ if not runtime["version"]:+ raise ValueError("Missing runtime version")+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ manifest = {+ "schemaVersion": 1, "channel": "nightly", "build": identity, "sourceRevision": args.sha,+ "protocolVersion": json.loads((ROOT / "protocol/rpc-schema.json").read_text())["protocol_version"],+ "platforms": PLATFORMS,+ "runtime": {"channel": "agent-nightly", "version": runtime["version"],+ "manifestUrl": f"{base_url}/runtime.json", "sha256": hashlib.sha256(snapshot).hexdigest()},+ "packages": {},+ }+ (output / "runtime.json").write_bytes(snapshot)+ with tempfile.TemporaryDirectory(prefix="jan-sdk-package-") as temporary:+ stage = Path(temporary)+ js = stage / "javascript"+ shutil.copytree(ROOT / "packages/agent-sdk", js, ignore=shutil.ignore_patterns("node_modules"))+ package = json.loads((js / "package.json").read_text())+ package["version"] = f'{package["version"].split("-")[0]}-nightly.{args.build}'+ (js / "package.json").write_text(json.dumps(package, indent=2) + "\n")+ subprocess.run(["npm", "pack", "--ignore-scripts", "--pack-destination", str(output)], cwd=js, check=True)+ archive = next(output.glob("*.tgz"))+ manifest["packages"]["javascript"] = {"name": package["name"], "version": package["version"],+ "url": f"{base_url}/{archive.name}", "sha256": hashlib.sha256(archive.read_bytes()).hexdigest()}+ py = stage / "python"+ shutil.copytree(ROOT / "sdk/python", py, ignore=shutil.ignore_patterns("__pycache__", "*.egg-info", "build", "dist"))+ metadata_path = py / "pyproject.toml"+ metadata = metadata_path.read_text()+ project = tomllib.loads(metadata)["project"]+ run, attempt = args.build.split(".")+ version = f'{project["version"]}.dev{run}+g{args.sha[:12]}.{attempt}'+ metadata_path.write_text(metadata.replace(f'version = "{project["version"]}"', f'version = "{version}"', 1))+ subprocess.run([sys.executable, "-m", "build", "--wheel", "--outdir", str(output), str(py)], check=True)+ wheel = next(output.glob("*.whl"))+ manifest["packages"]["python"] = {"name": project["name"], "version": version,+ "url": f"{base_url}/{quote(wheel.name, safe='')}", "sha256": hashlib.sha256(wheel.read_bytes()).hexdigest()}+ (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")+ js_package = manifest["packages"]["javascript"]+ py_package = manifest["packages"]["python"]+ wheel_url = f'{py_package["url"]}#sha256={py_package["sha256"]}'+ # Also a pip --find-links index. Every link points to one immutable build.+ page = f"""<!doctype html>+<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width">+<title>Jan Agent SDK nightly</title>+<style>body{{max-width:72ch;margin:3rem auto;padding:0 1rem;font:17px/1.6 system-ui;overflow-wrap:anywhere}}pre{{overflow:auto;background:#eee;padding:1rem}}code{{font-size:14px}}</style>+<h1>Jan Agent SDK nightly</h1>+<p>Preview build <code>{html.escape(identity)}</code>. No registry publication,+repository checkout, Jan Desktop or Rust compiler required.</p>+<h2>JavaScript (Node.js 20+)</h2>+<pre>npm install {html.escape(js_package["url"])}</pre>+<h2>Python (3.11+, no Node required)</h2>+<p>Use a virtual environment, then:</p>+<pre>python -m pip install "{html.escape(wheel_url)}"</pre>+<p><a href="{html.escape(wheel_url)}">Download Python wheel</a></p>+<h2>Matching runtime</h2>+<p>Package installation does not download or launch a runtime. Explicitly call+<code>installRuntime</code> / <code>install_runtime</code> with version+<code>{html.escape(runtime["version"])}</code> and manifest URL+<a href="{base_url}/runtime.json">{base_url}/runtime.json</a>.+Pass the returned <code>bin</code> to <code>JanRuntime.start</code>.+An existing compatible binary can also be passed explicitly.</p>+<p><a href="{base_url}/manifest.json">Versioned manifest and SHA-256 digests</a> |+<a href="https://jan.ai/docs/agent/sdk">SDK guides</a></p>+<p>Supported: Linux x64/ARM64, macOS Intel/Apple Silicon, Windows x64.+Windows ARM64 is not declared supported by this nightly smoke matrix.</p>+<p>Save this versioned page for repeatable installation. Versioned artifacts are not+overwritten or automatically deleted by the workflow. Missing versions fail;+they are never silently substituted with latest. These are previews, not stable releases.</p>+</html>+"""+ (output / "index.html").write_text(page)+ print(json.dumps(manifest, indent=2))+++if __name__ == "__main__":+ main()diff --git a/scripts/sdk-nightly/smoke.mjs b/scripts/sdk-nightly/smoke.mjsnew file mode 100644index 000000000..023b4c5a0--- /dev/null+++ b/scripts/sdk-nightly/smoke.mjs@@ -0,0 +1,34 @@+// Run from a clean npm project, not from the SDK source tree.+import assert from 'node:assert/strict'+import { execFileSync } from 'node:child_process'+import { JanRuntime, installRuntime } from '@janhq/agent-sdk'++const installed = await installRuntime({+ manifestUrl: process.env.RUNTIME_MANIFEST,+ version: process.env.RUNTIME_VERSION,+})+execFileSync(installed.bin, ['config', 'set', '--provider', 'stub', '--api-key', 'smoke',+ '--base-url', process.env.PROVIDER_URL, '--model', 'stub-model'])+let calls = 0+const runtime = await JanRuntime.start({ bin: installed.bin })+const pid = runtime.pid+try {+ const session = await runtime.createSession({+ model: 'stub-model', ephemeral: true, builtins: false,+ tools: [{+ name: 'measure', description: 'Read the sensor.', capability: 'read',+ parameters: { type: 'object', properties: {}, additionalProperties: false },+ handler: () => { calls++; return { text: 'sensor=42' } },+ }],+ })+ const turn = await session.prompt('Read the sensor.')+ let text = ''+ for await (const event of turn) if (event.type === 'token') text += event.text+ assert.equal((await turn.result()).stopReason, 'completed')+ assert.equal(text, 'The sensor is 42.')+ assert.equal(calls, 1)+} finally {+ await runtime.close()+}+assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' })+console.log('JavaScript: installed artifact -> pinned runtime -> host callback -> streamed result -> reaped process')diff --git a/scripts/sdk-nightly/smoke.py b/scripts/sdk-nightly/smoke.pynew file mode 100644index 000000000..d53f4c6fe--- /dev/null+++ b/scripts/sdk-nightly/smoke.py@@ -0,0 +1,131 @@+"""Install downloaded SDK artifacts and drive their real runtime, without source imports."""+import argparse+import hashlib+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from threading import Thread+from urllib.parse import unquote+from urllib.request import urlopen+++class Provider(BaseHTTPRequestHandler):+ tool_results = []++ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ results = [m for m in body["messages"] if m["role"] == "tool"]+ if results:+ self.tool_results.append(results[-1]["content"])+ delta = {"role": "assistant", "content": "The sensor is 42."}+ finish = "stop"+ else:+ delta = {"role": "assistant", "tool_calls": [{+ "index": 0, "id": "sensor-1", "type": "function",+ "function": {"name": "host__measure", "arguments": "{}"},+ }]}+ finish = "tool_calls"+ chunks = []+ for data, reason in [(delta, None), ({}, finish)]:+ chunks.append("data: " + json.dumps({+ "id": "smoke", "object": "chat.completion.chunk", "created": 1,+ "model": "stub-model", "choices": [{"index": 0, "delta": data, "finish_reason": reason}],+ }) + "\n\n")+ payload = ("".join(chunks) + "data: [DONE]\n\n").encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+++def download(url):+ with urlopen(url, timeout=120) as response:+ return response.read()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("manifest", help="Public URL or local manifest path (PR verification)")+ parser.add_argument("--artifacts", type=Path, help="PR-only local artifact directory")+ args = parser.parse_args()+ manifest = json.loads(args.artifacts.joinpath("manifest.json").read_text() if args.artifacts else download(args.manifest))+ node, npm = shutil.which("node"), shutil.which("npm")+ assert node and npm, "Node/npm required for the JS smoke"+ scripts = Path(__file__).resolve().parent+ with tempfile.TemporaryDirectory(prefix="jan-sdk-artifact-") as directory:+ root = Path(directory)+ artifacts = {}+ for language in ["javascript", "python"]:+ entry = manifest["packages"][language]+ name = unquote(entry["url"].rsplit("/", 1)[1])+ data = args.artifacts.joinpath(name).read_bytes() if args.artifacts else download(entry["url"])+ assert hashlib.sha256(data).hexdigest() == entry["sha256"], f"{language} digest mismatch"+ artifacts[language] = root / name+ artifacts[language].write_bytes(data)+ snapshot = args.artifacts.joinpath("runtime.json").read_bytes() if args.artifacts else download(manifest["runtime"]["manifestUrl"])+ assert hashlib.sha256(snapshot).hexdigest() == manifest["runtime"]["sha256"], "runtime manifest digest mismatch"+ # A private HTTP endpoint makes the same immutable snapshot usable by both installers in PRs.+ class RuntimeManifest(BaseHTTPRequestHandler):+ def log_message(self, *unused):+ pass++ def do_GET(self):+ self.send_response(200)+ self.send_header("Content-Length", str(len(snapshot)))+ self.end_headers()+ self.wfile.write(snapshot)++ runtime_server = ThreadingHTTPServer(("127.0.0.1", 0), RuntimeManifest)+ provider = ThreadingHTTPServer(("127.0.0.1", 0), Provider)+ threads = [Thread(target=s.serve_forever, daemon=True) for s in (runtime_server, provider)]+ for thread in threads:+ thread.start()+ try:+ env = {k: v for k, v in os.environ.items() if not k.startswith(("JAN_", "PYTHON"))}+ home = root / "home"+ home.mkdir()+ env.update(HOME=str(home), USERPROFILE=str(home), JAN_AGENT_HOME=str(root / "runtimes"),+ JAN_CLI_NO_UPDATE_CHECK="1", RUNTIME_VERSION=manifest["runtime"]["version"],+ RUNTIME_MANIFEST=f"http://127.0.0.1:{runtime_server.server_port}/runtime.json",+ PROVIDER_URL=f"http://127.0.0.1:{provider.server_port}/v1")+ js = root / "js"+ js.mkdir()+ (js / "package.json").write_text('{"private":true,"type":"module"}')+ # .cmd launchers need cmd.exe on Windows; arguments are generated local paths only.+ subprocess.run([npm, "install", "--ignore-scripts", "--no-audit", "--no-fund", str(artifacts["javascript"])],+ cwd=js, env=env, check=True, timeout=120, shell=os.name == "nt")+ shutil.copyfile(scripts / "smoke.mjs", js / "smoke.mjs")+ subprocess.run([node, "smoke.mjs"], cwd=js, env=env, check=True, timeout=180)+ venv = root / "venv"+ subprocess.run([sys.executable, "-m", "venv", str(venv)], check=True, timeout=120)+ python = venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ subprocess.run([str(python), "-m", "pip", "install", "--no-deps", str(artifacts["python"])],+ cwd=root, env=env, check=True, timeout=120)+ shutil.copyfile(scripts / "smoke_client.py", root / "smoke_client.py")+ # Keep Windows DLL utilities available but remove every Node search path.+ env["PATH"] = str(python.parent) + (os.pathsep + str(Path(os.environ["SystemRoot"]) / "System32") if os.name == "nt" else ":/usr/bin:/bin")+ # Some Linux images put Node in /usr/bin; Python and the installed runtime need no PATH executables.+ if os.name != "nt":+ env["PATH"] = str(python.parent)+ subprocess.run([str(python), "smoke_client.py"], cwd=root, env=env, check=True, timeout=180)+ assert Provider.tool_results == ["sensor=42", "sensor=42"], Provider.tool_results+ print("Both installed artifacts delivered their host result to the provider.")+ finally:+ for server in (runtime_server, provider):+ server.shutdown()+ server.server_close()+ for thread in threads:+ thread.join()+++if __name__ == "__main__":+ main()diff --git a/scripts/sdk-nightly/smoke_client.py b/scripts/sdk-nightly/smoke_client.pynew file mode 100644index 000000000..00cfdcca5--- /dev/null+++ b/scripts/sdk-nightly/smoke_client.py@@ -0,0 +1,56 @@+"""Copied into a clean environment and executed without Node on PATH."""+import os+import shutil+import subprocess++from jan_agent_sdk import HostTool, JanRuntime, install_runtime++assert shutil.which("node") is None, "Python smoke must not have Node available"+installed = install_runtime(+ manifest_url=os.environ["RUNTIME_MANIFEST"], version=os.environ["RUNTIME_VERSION"]+)+subprocess.run([+ installed.bin, "config", "set", "--provider", "stub", "--api-key", "smoke",+ "--base-url", os.environ["PROVIDER_URL"], "--model", "stub-model",+], check=True)+calls = []+++def measure(args, call):+ calls.append(args)+ return {"text": "sensor=42"}+++with JanRuntime.start(bin=installed.bin) as runtime:+ session = runtime.create_session(+ model="stub-model", ephemeral=True, builtins=False,+ tools=[HostTool(+ name="measure", description="Read the sensor.", capability="read",+ parameters={"type": "object", "properties": {}, "additionalProperties": False},+ handler=measure,+ )],+ )+ turn = session.prompt("Read the sensor.")+ text = "".join(event["text"] for event in turn if event["type"] == "token")+ assert turn.result().stop_reason == "completed"+ assert text == "The sensor is 42."+ assert calls == [{}]+# close() waits for the owned process; use its public pid for an independent check.+if os.name == "nt":+ import ctypes+ handle = ctypes.windll.kernel32.OpenProcess(0x1000, False, runtime.pid)+ if handle:+ try:+ code = ctypes.c_ulong()+ assert ctypes.windll.kernel32.GetExitCodeProcess(handle, ctypes.byref(code))+ assert code.value != 259, "runtime is still active"+ finally:+ ctypes.windll.kernel32.CloseHandle(handle)+else:+ try:+ os.kill(runtime.pid, 0)+ except ProcessLookupError:+ pass+ else:+ raise AssertionError("runtime was not reaped")+print("Python: installed wheel -> pinned runtime -> host callback -> streamed result -> reaped process; no Node")