π OpenHands: AI-Driven Development
fix: populate <RUNTIME_SERVICES> in static builds so automations work (#1125)
Vasco Schiavo7dbe8fd7de59
diff --git a/AGENTS.md b/AGENTS.mdindex 191df3ad36..0f01b459cb 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -55,9 +55,10 @@ Two distinct PostHog systems exist. **Never mix them at a call site.**- Host-side services (ingress, Vite, automation) are reachable as `http://localhost:<port>`.- Agents should treat the `<RUNTIME_SERVICES>` block as authoritative: don't hardcode `localhost:8000` for "the automation server", and don't probe random ports trying to discover services. If the block says automation is not running, skip `/api/automation` calls; otherwise use the listed `url_from_agent` + `api_prefix` (default `/api/automation`) and the `X-Session-API-Key: $OPENHANDS_AUTOMATION_API_KEY` header.- The launcher β frontend β suffix plumbing is:- - `scripts/dev-safe.mjs::buildRuntimeServicesInfo()` β pure helper that constructs the info object.- - `scripts/dev-with-automation.mjs::buildAutomationRuntimeServicesInfo()` β wraps it with automation details; called from both Vite spawn (`startVite`) and the static build (`static-build.mjs`).- - `src/api/agent-server-adapter.ts::buildRuntimeServicesSystemSuffix()` reads `VITE_RUNTIME_SERVICES_INFO` and renders the `<RUNTIME_SERVICES>` markdown block; `createAgentFromSettings()` attaches it to `agent_context.system_message_suffix` when present.+ - `scripts/runtime-services-info.mjs::buildRuntimeServicesInfo()` β dependency-free module that constructs the info object; also runs as a CLI for the Docker entrypoint. Re-exported by `scripts/dev-safe.mjs` for backward compat.+ - `scripts/dev-with-automation.mjs::buildAutomationRuntimeServicesInfo()` β wraps it with automation details; called from Vite spawn (`startVite`), static frontend spawn (`startStaticFrontend` β `--runtime-services-info` flag), and the static build (`static-build.mjs`).+ - `src/api/agent-server-adapter.ts::buildRuntimeServicesSystemSuffix()` reads `VITE_RUNTIME_SERVICES_INFO` (Vite dev) or `window.__AGENT_CANVAS_RUNTIME_SERVICES_INFO__` (static builds, injected by `static-server.mjs`) and renders the `<RUNTIME_SERVICES>` markdown block; `buildAgentContext()` attaches it to `agent_context.system_message_suffix` when present.+ - E2E coverage: the mock-LLM automation test (`tests/e2e/mock-llm/mock-llm-automation.spec.ts`) verifies the `<RUNTIME_SERVICES>` block reaches the LLM via `getMockLLMRequests()` and checks for Agent Server, Automation backend, and `/api/automation` entries.### `VITE_RUNTIME_SERVICES_INFO` shapediff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.tsindex a8cb24d579..8ef3d3096a 100644--- a/__tests__/api/agent-server-adapter.test.ts+++ b/__tests__/api/agent-server-adapter.test.ts@@ -782,6 +782,8 @@ describe("toAppConversation", () => {describe("buildRuntimeServicesSystemSuffix", () => {afterEach(() => {vi.unstubAllEnvs();+ delete (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_RUNTIME_SERVICES_INFO__;});it("returns undefined when VITE_RUNTIME_SERVICES_INFO is unset", () => {@@ -918,6 +920,58 @@ describe("buildRuntimeServicesSystemSuffix", () => {expect(suffix).toBeDefined();expect(suffix).toContain("Automation backend: not running");});++ it("falls back to window.__AGENT_CANVAS_RUNTIME_SERVICES_INFO__ when the env var is unset (static builds)", () => {+ // Static builds (Docker image / published binary) have no+ // VITE_RUNTIME_SERVICES_INFO baked in; scripts/static-server.mjs injects+ // the JSON onto window at serve time instead.+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_RUNTIME_SERVICES_INFO__ = JSON.stringify({+ mode: "docker",+ services: {+ agent_server: { url_from_agent: "http://127.0.0.1:18000" },+ automation: {+ url_from_agent: "http://127.0.0.1:8000",+ api_prefix: "/api/automation",+ auth_env_var: "OPENHANDS_AUTOMATION_API_KEY",+ },+ },+ });+ const suffix = buildRuntimeServicesSystemSuffix();+ expect(suffix).toBeDefined();+ expect(suffix).toContain("<RUNTIME_SERVICES>");+ expect(suffix).toContain("docker");+ expect(suffix).toContain("http://127.0.0.1:18000");+ expect(suffix).toContain("http://127.0.0.1:8000");+ expect(suffix).toContain(+ "X-Session-API-Key: $OPENHANDS_AUTOMATION_API_KEY",+ );+ });++ it("prefers VITE_RUNTIME_SERVICES_INFO over the window fallback", () => {+ vi.stubEnv(+ "VITE_RUNTIME_SERVICES_INFO",+ JSON.stringify({+ mode: "dev:env",+ services: {+ agent_server: { url_from_agent: "http://localhost:18000" },+ },+ }),+ );+ (+ window as unknown as Record<string, unknown>+ ).__AGENT_CANVAS_RUNTIME_SERVICES_INFO__ = JSON.stringify({+ mode: "docker:window",+ services: {+ agent_server: { url_from_agent: "http://127.0.0.1:99999" },+ },+ });+ const suffix = buildRuntimeServicesSystemSuffix();+ expect(suffix).toContain("dev:env");+ expect(suffix).not.toContain("docker:window");+ expect(suffix).not.toContain("99999");+ });});describe("agent_settings runtime services suffix", () => {diff --git a/__tests__/scripts/dev-safe.test.ts b/__tests__/scripts/dev-safe.test.tsindex a6a6e530df..4a45326032 100644--- a/__tests__/scripts/dev-safe.test.ts+++ b/__tests__/scripts/dev-safe.test.ts@@ -987,12 +987,12 @@ describe("buildRuntimeServicesInfo", () => {expect(info.services.automation).toBeUndefined();});- it("throws when agentServerPort is missing", () => {+ it("throws when neither agentServerPort nor agentServerUrl is given", () => {expect(() =>buildRuntimeServicesInfo({mode: "dev:safe",}),- ).toThrow(/agentServerPort is required/);+ ).toThrow(/agentServerPort or agentServerUrl is required/);});it("accepts the legacy vitePort alias for frontendPort", () => {diff --git a/__tests__/scripts/runtime-services-info.test.ts b/__tests__/scripts/runtime-services-info.test.tsnew file mode 100644index 0000000000..0c073003bf--- /dev/null+++ b/__tests__/scripts/runtime-services-info.test.ts@@ -0,0 +1,140 @@+// @vitest-environment node+import { execFileSync } from "node:child_process";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++import {+ buildRuntimeServicesInfo,+ parseArgs,+} from "../../scripts/runtime-services-info.mjs";++const SCRIPT_PATH = fileURLToPath(+ new URL("../../scripts/runtime-services-info.mjs", import.meta.url),+);++// buildRuntimeServicesInfo comes from a .mjs module, so tsc infers `object`;+// cast to the structural shape we assert on (mirrors dev-safe.test.ts).+interface RuntimeServicesInfoShape {+ mode?: string;+ agent_host_alias: string;+ services: {+ agent_server?: { url_from_agent: string };+ automation?: {+ url_from_agent: string;+ api_prefix: string;+ docs_url: string;+ openapi_url: string;+ auth_env_var: string;+ };+ };+}++describe("runtime-services-info.mjs", () => {+ // Port-based behavior (the dev path) is covered in dev-safe.test.ts. These+ // cover the URL-override path the Docker image uses.+ describe("buildRuntimeServicesInfo β URL overrides", () => {+ it("uses explicit agent-server and automation URLs verbatim", () => {+ const info = buildRuntimeServicesInfo({+ mode: "docker",+ agentHostAlias: "127.0.0.1",+ agentServerUrl: "http://127.0.0.1:18000",+ automation: { url: "http://127.0.0.1:8000" },+ }) as RuntimeServicesInfoShape;+ expect(info.agent_host_alias).toBe("127.0.0.1");+ expect(info.services.agent_server?.url_from_agent).toBe(+ "http://127.0.0.1:18000",+ );+ expect(info.services.automation).toMatchObject({+ url_from_agent: "http://127.0.0.1:8000",+ api_prefix: "/api/automation",+ docs_url: "http://127.0.0.1:8000/api/automation/docs",+ openapi_url: "http://127.0.0.1:8000/api/automation/openapi.json",+ auth_env_var: "OPENHANDS_AUTOMATION_API_KEY",+ });+ });++ it("prefers an explicit agentServerUrl over agentServerPort", () => {+ const info = buildRuntimeServicesInfo({+ agentServerPort: 99999,+ agentServerUrl: "http://127.0.0.1:18000",+ }) as RuntimeServicesInfoShape;+ expect(info.services.agent_server?.url_from_agent).toBe(+ "http://127.0.0.1:18000",+ );+ });++ it("omits automation when neither url nor port is provided", () => {+ const info = buildRuntimeServicesInfo({+ agentServerUrl: "http://127.0.0.1:18000",+ automation: {},+ }) as RuntimeServicesInfoShape;+ expect(info.services.automation).toBeUndefined();+ });++ it("throws when neither port nor url is provided", () => {+ expect(() => buildRuntimeServicesInfo({ mode: "x" })).toThrow(+ /agentServerPort or agentServerUrl is required/,+ );+ });+ });++ describe("parseArgs", () => {+ it("maps flags to builder options", () => {+ const opts = parseArgs([+ "--mode",+ "docker",+ "--agent-host-alias",+ "127.0.0.1",+ "--agent-server-url",+ "http://127.0.0.1:18000",+ "--automation-url",+ "http://127.0.0.1:8000",+ ]);+ expect(opts).toEqual({+ mode: "docker",+ agentHostAlias: "127.0.0.1",+ agentServerUrl: "http://127.0.0.1:18000",+ automation: { url: "http://127.0.0.1:8000" },+ });+ });++ it("omits automation when no --automation-url is given", () => {+ const opts = parseArgs(["--agent-server-url", "http://127.0.0.1:18000"]);+ expect(opts.automation).toBeUndefined();+ });++ it("throws on an unknown flag", () => {+ expect(() => parseArgs(["--nope"])).toThrow(/Unknown flag/);+ });+ });++ describe("CLI", () => {+ // This is the exact path docker/entrypoint.sh relies on: run the module+ // directly and capture the JSON it prints to stdout.+ it("emits valid <RUNTIME_SERVICES> JSON on stdout", () => {+ const stdout = execFileSync(+ process.execPath,+ [+ SCRIPT_PATH,+ "--mode",+ "docker",+ "--agent-host-alias",+ "127.0.0.1",+ "--agent-server-url",+ "http://127.0.0.1:18000",+ "--automation-url",+ "http://127.0.0.1:8000",+ ],+ { encoding: "utf8" },+ );+ const info = JSON.parse(stdout);+ expect(info.mode).toBe("docker");+ expect(info.services.agent_server.url_from_agent).toBe(+ "http://127.0.0.1:18000",+ );+ expect(info.services.automation.url_from_agent).toBe(+ "http://127.0.0.1:8000",+ );+ });+ });+});diff --git a/__tests__/scripts/static-server.test.ts b/__tests__/scripts/static-server.test.tsindex c24298ddbc..6548aa4284 100644--- a/__tests__/scripts/static-server.test.ts+++ b/__tests__/scripts/static-server.test.ts@@ -60,6 +60,95 @@ describe("static-server.mjs", () => {const config = parseArgs(["--session-api-key", ""]);expect(config.sessionApiKey).toBeNull();});++ it("defaults runtimeServicesInfo to null", () => {+ const config = parseArgs([]);+ expect(config.runtimeServicesInfo).toBeNull();+ });++ it("parses --runtime-services-info", () => {+ const json = '{"mode":"docker"}';+ const config = parseArgs(["--runtime-services-info", json]);+ expect(config.runtimeServicesInfo).toBe(json);+ });++ it("treats empty string as null for runtime services info", () => {+ const config = parseArgs(["--runtime-services-info", ""]);+ expect(config.runtimeServicesInfo).toBeNull();+ });+ });++ describe("runtime services info injection", () => {+ async function startServerWithRuntimeInfo(+ dir: string,+ runtimeServicesInfo: string,+ ) {+ const server = await startStaticServer({+ port: 0,+ host: "127.0.0.1",+ dir,+ routes: {},+ runtimeServicesInfo,+ });+ servers.push(server);+ const address = server.address();+ if (!address || typeof address === "string") {+ throw new Error("Static server did not bind to a TCP port");+ }+ return `http://127.0.0.1:${address.port}`;+ }++ // Regression test for the Docker / published-binary path: static builds+ // have no VITE_RUNTIME_SERVICES_INFO baked in, so the agent's+ // <RUNTIME_SERVICES> block is populated from this injected window global+ // (see `parseRuntimeServicesInfo()` in src/api/agent-server-adapter.ts).+ it("exposes the JSON on window.__AGENT_CANVAS_RUNTIME_SERVICES_INFO__", async () => {+ const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));+ tempDirs.push(buildDir);+ writeFileSync(+ path.join(buildDir, "index.html"),+ "<html><head></head><body>app</body></html>",+ );++ const info = JSON.stringify({+ mode: "docker",+ services: {+ agent_server: { url_from_agent: "http://127.0.0.1:18000" },+ },+ });+ const origin = await startServerWithRuntimeInfo(buildDir, info);+ const body = await (await fetch(`${origin}/`)).text();++ expect(body).toContain("window.__AGENT_CANVAS_RUNTIME_SERVICES_INFO__");+ // Stored as a JSON *string* (note the escaped quotes) so the browser can+ // JSON.parse it, exactly like the VITE_RUNTIME_SERVICES_INFO env var.+ expect(body).toContain('\\"mode\\"');+ expect(body).toContain("docker");+ });++ it("does not inject when runtimeServicesInfo is null", async () => {+ const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));+ tempDirs.push(buildDir);+ writeFileSync(+ path.join(buildDir, "index.html"),+ "<html><head></head><body>app</body></html>",+ );++ const server = await startStaticServer({+ port: 0,+ host: "127.0.0.1",+ dir: buildDir,+ routes: {},+ runtimeServicesInfo: null,+ });+ servers.push(server);+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("No port");+ const origin = `http://127.0.0.1:${(address as { port: number }).port}`;++ const body = await (await fetch(`${origin}/`)).text();+ expect(body).not.toContain("__AGENT_CANVAS_RUNTIME_SERVICES_INFO__");+ });});describe("session key injection", () => {diff --git a/docker/Dockerfile b/docker/Dockerfileindex c0ed77a9ae..404e06d18c 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -102,6 +102,10 @@ COPY --from=frontend-build /build/build /opt/agent-canvas/frontend# Copy the static-server script (serves frontend + proxies to backends)COPY scripts/static-server.mjs /opt/agent-canvas/static-server.mjs+# Copy the runtime-services-info builder (entrypoint.sh runs it as a CLI to+# emit the agent's <RUNTIME_SERVICES> block; same builder the dev stack uses).+COPY scripts/runtime-services-info.mjs /opt/agent-canvas/runtime-services-info.mjs+# Copy custom tools (e.g. canvas_ui_tool.py) so the agent-server can import# them via tool_module_qualnames. OH_EXTRA_PYTHON_PATH is set in entrypoint.sh.COPY tools/ /opt/agent-canvas/tools/diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex e22413c1fe..a48f0e2ace 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -228,12 +228,28 @@ wait "$WAIT_PID1" "$WAIT_PID2"# ββ 4. Start static server (frontend + proxy) ββββββββββββββββββββββββββββββββlog "Starting frontend + proxy on port $PORT..."+# Describe the local runtime services so the frontend can populate the agent's+# <RUNTIME_SERVICES> system-prompt block (without it the agent does not know how+# to reach the local automation backend and falls back to the cloud API). These+# URLs are runtime config (overridable at `docker run`), so unlike the dev+# launchers we cannot bake VITE_RUNTIME_SERVICES_INFO into the image at build+# time β we build the JSON here from the sandbox-facing URLs the entrypoint+# already exports and inject it at serve time via+# static-server.mjs --runtime-services-info. The shape comes from the same+# builder the dev stack uses (scripts/runtime-services-info.mjs).+RUNTIME_SERVICES_INFO="$(node /opt/agent-canvas/runtime-services-info.mjs \+ --mode docker \+ --agent-host-alias 127.0.0.1 \+ --agent-server-url "$AGENT_SERVER_URL" \+ --automation-url "$AUTOMATION_BASE_URL")"+# EFFECTIVE_SESSION_KEY is set above from LOCAL_BACKEND_API_KEY or the persisted api-key.txtnode /opt/agent-canvas/static-server.mjs \--port "$PORT" \--host :: \--dir /opt/agent-canvas/frontend \--session-api-key "$EFFECTIVE_SESSION_KEY" \+ --runtime-services-info "$RUNTIME_SERVICES_INFO" \--route "/api/automation=http://127.0.0.1:${AUTOMATION_PORT}" \--route "/api=http://127.0.0.1:${AGENT_SERVER_PORT}" \--route "/server_info=http://127.0.0.1:${AGENT_SERVER_PORT}" \@@ -259,6 +275,7 @@ if [ -n "${PUBLIC_MODE_PORT:-}" ]; then--host :: \--dir /opt/agent-canvas/frontend \--auth-required \+ --runtime-services-info "$RUNTIME_SERVICES_INFO" \--route "/api/automation=http://127.0.0.1:${AUTOMATION_PORT}" \--route "/api=http://127.0.0.1:${AGENT_SERVER_PORT}" \--route "/server_info=http://127.0.0.1:${AGENT_SERVER_PORT}" \diff --git a/scripts/dev-safe.mjs b/scripts/dev-safe.mjsindex ac3a83da40..840d0c040c 100644--- a/scripts/dev-safe.mjs+++ b/scripts/dev-safe.mjs@@ -21,6 +21,10 @@ import {isProcessRunning,signalProcessTree,} from "./dev-process-utils.mjs";+// buildRuntimeServicesInfo moved to its own dependency-free module so the+// Docker entrypoint can run it as a CLI. Re-exported below for back-compat+// (dev-with-automation.mjs and tests still import it from here).+import { buildRuntimeServicesInfo } from "./runtime-services-info.mjs";// ββ Centralized config (single source of truth for versions, ports, etc.) βββconst __dev_safe_dirname = path.dirname(fileURLToPath(import.meta.url));@@ -700,121 +704,10 @@ export function buildAgentServerEnv(config) {};}-/**- * Build a structured description of the dev-stack services that are- * reachable from inside the agent's sandbox. The frontend forwards this- * (verbatim, as a JSON string in `VITE_RUNTIME_SERVICES_INFO`) and renders- * it into the system prompt via `AgentContext.system_message_suffix`, so- * the agent sees a `<RUNTIME_SERVICES>` block listing what's available- * without having to probe.- *- * URLs are written from the *agent's* point of view. The agent-server- * runs on the host, so the host alias is "localhost".- *- * @param {object} options- * @param {string} [options.mode] - Human-readable dev mode label (e.g. "dev:safe").- * @param {string} [options.agentHostAlias="localhost"] - Hostname the agent- * uses to reach services running on the host machine.- * @param {number} [options.agentServerPort] - Port the agent-server listens on.- * Required at runtime; the function throws if missing because the resulting- * URL would otherwise bake `undefined` into the agent's system prompt.- * Typed as optional only so TypeScript callers can negative-test the guard.- * @param {number} [options.ingressPort] - Ingress port (omit if no ingress).- * @param {number} [options.frontendPort] - Frontend port (Vite dev server- * or static-file server). Omit if no frontend is exposed.- * @param {number} [options.vitePort] - Deprecated alias for `frontendPort`,- * accepted for backward compat with older launchers. Remove after one release.- * @param {"vite"|"static"} [options.frontendKind="vite"] - Whether the- * frontend port hosts Vite or a static build. Only affects the- * description shown to the agent.- * @param {object} [options.automation] - Automation backend info. Skipped- * entirely if `.port` is missing, so passing `{}` is safe.- * @param {number} [options.automation.port] - Automation backend port.- * @param {string} [options.automation.apiPrefix="/api/automation"] - Path- * prefix all automation routes are mounted under.- * @param {string} [options.automation.authEnvVar="OPENHANDS_AUTOMATION_API_KEY"]- * - Env var holding the API key.- * @returns {object} A JSON-serializable runtime services info object.- */-export function buildRuntimeServicesInfo(options) {- const {- mode,- agentHostAlias = "localhost",- agentServerPort,- ingressPort,- // Accept legacy `vitePort` for one release so external callers keep working.- vitePort,- frontendPort = vitePort,- frontendKind = "vite",- automation,- } = options;-- if (agentServerPort === undefined || agentServerPort === null) {- // Without this the URL becomes `http://localhost:undefined` and ends up- // verbatim in the agent's system prompt, which is worse than failing fast.- throw new Error(- "buildRuntimeServicesInfo: agentServerPort is required " +- "(otherwise the agent_server URL would be `http://localhost:undefined`).",- );- }-- const services = {- agent_server: {- description:- "The OpenHands Agent Server this agent is running inside. " +- "Tool calls (terminal, file_editor, browser, etc.) execute here.",- // From the agent's POV, the agent-server it's *inside* is on- // localhost, regardless of where the host is.- url_from_agent: `http://localhost:${agentServerPort}`,- },- };-- if (ingressPort !== undefined) {- services.ingress = {- description:- "Unified entry point. Routes /api/automation/* to the automation " +- "backend, /api/* and /sockets to the agent-server, and /* to the " +- "frontend.",- url_from_agent: `http://${agentHostAlias}:${ingressPort}`,- };- }-- if (frontendPort !== undefined) {- services.frontend = {- kind: frontendKind,- description:- frontendKind === "static"- ? "Static-file server hosting the agent-canvas production build."- : "Vite dev server hosting the agent-canvas frontend.",- url_from_agent: `http://${agentHostAlias}:${frontendPort}`,- };- }-- // Require an explicit port so we don't bake `:undefined` into the- // automation URL when the caller passes `automation: {}`.- if (automation?.port !== undefined && automation.port !== null) {- const apiPrefix = automation.apiPrefix ?? "/api/automation";- const authEnvVar = automation.authEnvVar ?? "OPENHANDS_AUTOMATION_API_KEY";- const baseUrl = `http://${agentHostAlias}:${automation.port}`;- services.automation = {- description:- "OpenHands Automations service. All routes are mounted under " +- `'${apiPrefix}'. Authenticate with header ` +- `'X-Session-API-Key: $${authEnvVar}'.`,- url_from_agent: baseUrl,- api_prefix: apiPrefix,- docs_url: `${baseUrl}${apiPrefix}/docs`,- openapi_url: `${baseUrl}${apiPrefix}/openapi.json`,- auth_env_var: authEnvVar,- };- }-- return {- mode,- agent_host_alias: agentHostAlias,- services,- };-}+// Re-export so existing importers (dev-with-automation.mjs, tests) keep+// resolving `buildRuntimeServicesInfo` from this module. The implementation+// now lives in ./runtime-services-info.mjs (imported at the top of this file).+export { buildRuntimeServicesInfo };export function buildNpmScriptCommand(scriptName,diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjsindex 03655091bc..50661eb043 100644--- a/scripts/dev-with-automation.mjs+++ b/scripts/dev-with-automation.mjs@@ -1269,6 +1269,13 @@ function startStaticFrontend(config, staticDir) {logService("static", `Starting on port ${config.vitePort}...`, c.magenta);logService("static", `Serving from: ${staticDir}`, c.dim);+ // Build the runtime-services info JSON so the pre-built frontend can+ // populate the agent's <RUNTIME_SERVICES> system-prompt block without+ // VITE_RUNTIME_SERVICES_INFO baked in at build time.+ const runtimeServicesInfo = config.launchAgentServer+ ? JSON.stringify(buildAutomationRuntimeServicesInfo(config))+ : null;+const staticServerScript = join(projectRoot, "scripts", "static-server.mjs");spawnService("static",@@ -1288,6 +1295,10 @@ function startStaticFrontend(config, staticDir) {...(config.launchAgentServer && config.isPublic? ["--auth-required"]: []),+ // Inject runtime-services info so the agent knows what's reachable.+ ...(runtimeServicesInfo+ ? ["--runtime-services-info", runtimeServicesInfo]+ : []),// Proxy routes only to services that this launch mode started....buildRouteArgs(getLocalServiceRoutes(config)),// Reject known API prefixes that have no backend β returns 503diff --git a/scripts/runtime-services-info.mjs b/scripts/runtime-services-info.mjsnew file mode 100644index 0000000000..b3b80b62d2--- /dev/null+++ b/scripts/runtime-services-info.mjs@@ -0,0 +1,199 @@+/**+ * Single source of truth for the `<RUNTIME_SERVICES>` block.+ *+ * Builds a structured description of the services that are reachable from+ * inside the agent's sandbox. The frontend forwards it (verbatim, as a JSON+ * string) and renders it into the system prompt via+ * `AgentContext.system_message_suffix`, so the agent sees a+ * `<RUNTIME_SERVICES>` block listing what's available without having to probe.+ *+ * Two callers share this one definition:+ * - the dev launchers (scripts/dev-*.mjs), which know the stack as a set of+ * ports and bake the result into `VITE_RUNTIME_SERVICES_INFO` at build time;+ * - docker/entrypoint.sh, which runs this file as a CLI (see the bottom of+ * this module) because in a container the URLs are *runtime* config β the+ * ports and base URLs are overridable at `docker run` and therefore cannot+ * be baked into the image at build time. The JSON it prints is injected+ * into index.html at serve time by scripts/static-server.mjs.+ *+ * URLs are written from the *agent's* point of view (i.e. as the agent should+ * curl/fetch them from inside its sandbox), which is deliberately not the+ * browser's point of view.+ */++import process from "node:process";+import { pathToFileURL } from "node:url";++/**+ * @param {object} options+ * @param {string} [options.mode] - Human-readable mode label (e.g. "dev:safe").+ * @param {string} [options.agentHostAlias="localhost"] - Hostname the agent+ * uses to reach host-side services (ingress, frontend, port-derived+ * automation). Also surfaced as `agent_host_alias`.+ * @param {number} [options.agentServerPort] - Port the agent-server listens on.+ * Used to derive the agent_server URL when `agentServerUrl` is not given.+ * @param {string} [options.agentServerUrl] - Explicit agent_server URL, from+ * the agent's POV. Takes precedence over `agentServerPort`; used by the+ * Docker image, which serves over `127.0.0.1` to avoid IPv6 loopback issues+ * and honors an overridable `AGENT_SERVER_URL`. One of `agentServerUrl` /+ * `agentServerPort` is required (else the URL would be `:undefined`).+ * @param {number} [options.ingressPort] - Ingress port (omit if no ingress).+ * @param {number} [options.frontendPort] - Frontend port (Vite dev server+ * or static-file server). Omit if no frontend is exposed.+ * @param {number} [options.vitePort] - Deprecated alias for `frontendPort`,+ * accepted for backward compat with older launchers. Remove after one release.+ * @param {"vite"|"static"} [options.frontendKind="vite"] - Whether the+ * frontend port hosts Vite or a static build. Only affects the description.+ * @param {object} [options.automation] - Automation backend info. Skipped+ * entirely unless `.url` or `.port` is provided, so passing `{}` is safe.+ * @param {string} [options.automation.url] - Explicit automation base URL, from+ * the agent's POV. Takes precedence over `.port`; used by the Docker image to+ * honor an overridable `AUTOMATION_BASE_URL`.+ * @param {number} [options.automation.port] - Automation backend port (used to+ * derive the base URL when `.url` is not given).+ * @param {string} [options.automation.apiPrefix="/api/automation"] - Path+ * prefix all automation routes are mounted under.+ * @param {string} [options.automation.authEnvVar="OPENHANDS_AUTOMATION_API_KEY"]+ * - Env var holding the API key.+ * @returns {object} A JSON-serializable runtime services info object.+ */+export function buildRuntimeServicesInfo(options) {+ const {+ mode,+ agentHostAlias = "localhost",+ agentServerPort,+ agentServerUrl,+ ingressPort,+ // Accept legacy `vitePort` for one release so external callers keep working.+ vitePort,+ frontendPort = vitePort,+ frontendKind = "vite",+ automation,+ } = options;++ // Prefer an explicit URL (containers reach the agent-server over a specific+ // host/scheme), else derive it from the port. From the agent's POV the+ // agent-server it's *inside* is on the loopback host, regardless of where+ // the host machine is.+ const agentServerUrlResolved =+ agentServerUrl ??+ (agentServerPort != null ? `http://localhost:${agentServerPort}` : null);+ if (!agentServerUrlResolved) {+ // Without this the URL becomes `http://localhost:undefined` and ends up+ // verbatim in the agent's system prompt, which is worse than failing fast.+ throw new Error(+ "buildRuntimeServicesInfo: agentServerPort or agentServerUrl is required " ++ "(otherwise the agent_server URL would be `http://localhost:undefined`).",+ );+ }++ const services = {+ agent_server: {+ description:+ "The OpenHands Agent Server this agent is running inside. " ++ "Tool calls (terminal, file_editor, browser, etc.) execute here.",+ url_from_agent: agentServerUrlResolved,+ },+ };++ if (ingressPort !== undefined) {+ services.ingress = {+ description:+ "Unified entry point. Routes /api/automation/* to the automation " ++ "backend, /api/* and /sockets to the agent-server, and /* to the " ++ "frontend.",+ url_from_agent: `http://${agentHostAlias}:${ingressPort}`,+ };+ }++ if (frontendPort !== undefined) {+ services.frontend = {+ kind: frontendKind,+ description:+ frontendKind === "static"+ ? "Static-file server hosting the agent-canvas production build."+ : "Vite dev server hosting the agent-canvas frontend.",+ url_from_agent: `http://${agentHostAlias}:${frontendPort}`,+ };+ }++ // Prefer an explicit base URL, else derive from the port. Require one of the+ // two so we don't bake `:undefined` into the URL when the caller passes+ // `automation: {}`.+ const automationBaseUrl =+ automation?.url ??+ (automation?.port != null+ ? `http://${agentHostAlias}:${automation.port}`+ : null);+ if (automationBaseUrl) {+ const apiPrefix = automation.apiPrefix ?? "/api/automation";+ const authEnvVar = automation.authEnvVar ?? "OPENHANDS_AUTOMATION_API_KEY";+ services.automation = {+ description:+ "OpenHands Automations service. All routes are mounted under " ++ `'${apiPrefix}'. Authenticate with header ` ++ `'X-Session-API-Key: $${authEnvVar}'.`,+ url_from_agent: automationBaseUrl,+ api_prefix: apiPrefix,+ docs_url: `${automationBaseUrl}${apiPrefix}/docs`,+ openapi_url: `${automationBaseUrl}${apiPrefix}/openapi.json`,+ auth_env_var: authEnvVar,+ };+ }++ return {+ mode,+ agent_host_alias: agentHostAlias,+ services,+ };+}++// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+// CLI β used by docker/entrypoint.sh to emit the JSON at container startup.+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export function parseArgs(argv) {+ const options = { automation: {} };+ for (let i = 0; i < argv.length; i++) {+ const flag = argv[i];+ switch (flag) {+ case "--mode":+ options.mode = argv[++i];+ break;+ case "--agent-host-alias":+ options.agentHostAlias = argv[++i];+ break;+ case "--agent-server-url":+ options.agentServerUrl = argv[++i] || undefined;+ break;+ case "--automation-url":+ options.automation.url = argv[++i] || undefined;+ break;+ case "--automation-api-prefix":+ options.automation.apiPrefix = argv[++i];+ break;+ case "--automation-auth-env":+ options.automation.authEnvVar = argv[++i];+ break;+ default:+ throw new Error(`Unknown flag: ${flag}`);+ }+ }+ // Omit the automation entry entirely when no URL was supplied, rather than+ // advertising a backend the agent cannot reach.+ if (!options.automation.url) delete options.automation;+ return options;+}++const isMainModule =+ process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;++if (isMainModule) {+ try {+ const options = parseArgs(process.argv.slice(2));+ process.stdout.write(JSON.stringify(buildRuntimeServicesInfo(options)));+ } catch (err) {+ console.error(err instanceof Error ? err.message : err);+ process.exit(1);+ }+}diff --git a/scripts/static-server.mjs b/scripts/static-server.mjsindex f1d382a563..09ce9451da 100644--- a/scripts/static-server.mjs+++ b/scripts/static-server.mjs@@ -75,6 +75,7 @@ export function parseArgs(argv = process.argv.slice(2)) {rejectPrefixes: [],sessionApiKey: null,authRequired: false,+ runtimeServicesInfo: null,};for (let i = 0; i < argv.length; i++) {@@ -110,6 +111,9 @@ export function parseArgs(argv = process.argv.slice(2)) {case "--session-api-key":config.sessionApiKey = argv[++i] || null;break;+ case "--runtime-services-info":+ config.runtimeServicesInfo = argv[++i] || null;+ break;case "--auth-required":config.authRequired = true;break;@@ -167,6 +171,12 @@ OPTIONS:--auth-required Inject authRequired flag into index.html so thepre-built frontend shows the API key entry screen(public mode) without VITE_AUTH_REQUIRED baked in.+ --runtime-services-info <json>+ Inject a JSON description of the local runtime+ services into index.html so the pre-built+ frontend can populate the agent's+ <RUNTIME_SERVICES> system-prompt block without+ VITE_RUNTIME_SERVICES_INFO baked in.--reject-prefix <prefix> Return 503 for requests matching <prefix>instead of SPA-fallbacking to index.html;may be repeated. Useful in --frontend-only@@ -208,8 +218,19 @@ ROUTING:* - `authRequired`: sets `window.__AGENT_CANVAS_AUTH_REQUIRED__ = true` so the* pre-built frontend shows the API key entry screen (public mode) without* VITE_AUTH_REQUIRED baked in.+ *+ * - `runtimeServicesInfo`: a JSON string describing the local services+ * (agent-server, automation, β¦), exposed as+ * `window.__AGENT_CANVAS_RUNTIME_SERVICES_INFO__`. Read by+ * `parseRuntimeServicesInfo()` in `agent-server-adapter.ts` as a fallback+ * when `VITE_RUNTIME_SERVICES_INFO` is empty, so static builds (Docker /+ * published binary) still populate the agent's `<RUNTIME_SERVICES>` block.*/-function makeConfigInjectionScript(sessionApiKey, authRequired) {+function makeConfigInjectionScript(+ sessionApiKey,+ authRequired,+ runtimeServicesInfo,+) {const parts = [];if (sessionApiKey) {@@ -236,6 +257,16 @@ function makeConfigInjectionScript(sessionApiKey, authRequired) {parts.push(`window.__AGENT_CANVAS_AUTH_REQUIRED__=true;`);}+ if (runtimeServicesInfo) {+ // Stored as the raw JSON string so the browser-side parser+ // (parseRuntimeServicesInfo) can JSON.parse it exactly like the+ // VITE_RUNTIME_SERVICES_INFO env var. JSON.stringify produces a safe JS+ // string literal for the inline <script>.+ parts.push(+ `window.__AGENT_CANVAS_RUNTIME_SERVICES_INFO__=${JSON.stringify(runtimeServicesInfo)};`,+ );+ }+if (parts.length === 0) return "";return `<script>(function(){${parts.join("")}}());</script>`;@@ -249,7 +280,7 @@ async function serveInjectedIndexHtml(req,res,indexPath,- { sessionApiKey, authRequired } = {},+ { sessionApiKey, authRequired, runtimeServicesInfo } = {},) {let content;try {@@ -258,7 +289,11 @@ async function serveInjectedIndexHtml(return false;}- const script = makeConfigInjectionScript(sessionApiKey, authRequired);+ const script = makeConfigInjectionScript(+ sessionApiKey,+ authRequired,+ runtimeServicesInfo,+ );// Inject right before </head> so the key is available before any app code runs.// replace() targets the first (and only) </head> in well-formed HTML.const injected = content.includes("</head>")@@ -500,7 +535,9 @@ async function handleStatic(}const needsInjection =- injectionOpts.sessionApiKey || injectionOpts.authRequired;+ injectionOpts.sessionApiKey ||+ injectionOpts.authRequired ||+ injectionOpts.runtimeServicesInfo;// Serve index.html with runtime config injection when configured.if (needsInjection && filePath.endsWith("index.html")) {@@ -553,6 +590,7 @@ export function startStaticServer(config) {const injectionOpts = {sessionApiKey: config.sessionApiKey || null,authRequired: config.authRequired || false,+ runtimeServicesInfo: config.runtimeServicesInfo || null,};const rejectPrefixes = config.rejectPrefixes ?? [];diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.tsindex c500af5ed7..342459c9ab 100644--- a/src/api/agent-server-adapter.ts+++ b/src/api/agent-server-adapter.ts@@ -91,9 +91,11 @@ function browserToolsEnabled() {}/**- * Shape of `VITE_RUNTIME_SERVICES_INFO` (set by the dev launchers in- * scripts/dev-*.mjs). All URLs are written from the agent's point of view,- * not the browser's. The block is rendered into the agent's system prompt+ * Shape of the runtime services info (set by the dev launchers in+ * scripts/dev-*.mjs as `VITE_RUNTIME_SERVICES_INFO`, or injected at serve time+ * by `scripts/static-server.mjs` for static builds β see+ * `getRawRuntimeServicesInfo`). All URLs are written from the agent's point of+ * view, not the browser's. The block is rendered into the agent's system prompt* via `AgentContext.system_message_suffix` so the agent knows what's* reachable from inside its sandbox without having to probe.*/@@ -122,8 +124,35 @@ interface RuntimeServicesInfo {};}+/**+ * Return the raw runtime-services JSON string, consulting two sources in order+ * (mirrors `getBakedSessionApiKey` in agent-server-config.ts):+ * 1. `VITE_RUNTIME_SERVICES_INFO` β baked into the bundle at build time by+ * the dev launchers (`npm run dev`, dev:static).+ * 2. `window.__AGENT_CANVAS_RUNTIME_SERVICES_INFO__` β injected into+ * index.html at serve time by `scripts/static-server.mjs+ * --runtime-services-info <json>`. This is the path used by static builds+ * (the Docker image and the published binary), where the env var is empty+ * in the prebuilt bundle. Without it the `<RUNTIME_SERVICES>` block is+ * missing and the agent cannot reach the local automation backend.+ */+function getRawRuntimeServicesInfo(): string | null {+ const envRaw = import.meta.env.VITE_RUNTIME_SERVICES_INFO?.trim();+ if (envRaw) return envRaw;++ if (typeof window !== "undefined") {+ const injected = (window as unknown as Record<string, unknown>)+ .__AGENT_CANVAS_RUNTIME_SERVICES_INFO__;+ if (typeof injected === "string") {+ return injected.trim() || null;+ }+ }++ return null;+}+function parseRuntimeServicesInfo(): RuntimeServicesInfo | null {- const raw = import.meta.env.VITE_RUNTIME_SERVICES_INFO?.trim();+ const raw = getRawRuntimeServicesInfo();if (!raw) return null;try {const parsed = JSON.parse(raw) as RuntimeServicesInfo;@@ -131,7 +160,8 @@ function parseRuntimeServicesInfo(): RuntimeServicesInfo | null {return parsed;} catch {// Malformed JSON: ignore and fall back to no runtime info, rather than- // tearing down conversation creation over a misconfigured dev env var.+ // tearing down conversation creation over a misconfigured env var or+ // injected value.return null;}}diff --git a/tests/e2e/mock-llm/mock-llm-automation.spec.ts b/tests/e2e/mock-llm/mock-llm-automation.spec.tsindex 5025cbb648..2b06cbb793 100644--- a/tests/e2e/mock-llm/mock-llm-automation.spec.ts+++ b/tests/e2e/mock-llm/mock-llm-automation.spec.ts@@ -40,6 +40,7 @@ import {activateTrajectory,resetMockLLM,ensureMockLLMProfile,+ getMockLLMRequests,} from "./utils/mock-llm-helpers";// Token the test asserts on in the agent's text reply (step 2).@@ -415,6 +416,57 @@ test.describe("mock-LLM automation lifecycle", () => {const errorBanner = page.getByTestId("error-message-banner");await expect(errorBanner).not.toBeVisible({ timeout: 2_000 });});++ // ββ Verify: runtime services info is included in LLM requests ββ++ await test.step("verify runtime services info in LLM system prompt", async () => {+ const llmRequests = await getMockLLMRequests(request);+ expect(+ llmRequests.length,+ "mock LLM should have received at least one completion request",+ ).toBeGreaterThan(0);++ // The <RUNTIME_SERVICES> block should appear in a system message+ // sent to the LLM. Walk all captured requests looking for it.+ function findRuntimeServicesContent(+ reqs: Record<string, unknown>[],+ ): string | null {+ for (const req of reqs) {+ const messages = req.messages as+ | Array<{ role: string; content: unknown }>+ | undefined;+ if (!Array.isArray(messages)) continue;+ for (const msg of messages) {+ if (msg.role !== "system") continue;+ const text =+ typeof msg.content === "string"+ ? msg.content+ : Array.isArray(msg.content)+ ? (msg.content as Array<{ type?: string; text?: string }>)+ .filter((c) => c.type === "text" || typeof c === "string")+ .map((c) => (typeof c === "string" ? c : c.text ?? ""))+ .join("")+ : "";+ if (text.includes("<RUNTIME_SERVICES>")) return text;+ }+ }+ return null;+ }++ const runtimeBlock = findRuntimeServicesContent(llmRequests);+ expect(+ runtimeBlock,+ `Expected <RUNTIME_SERVICES> block in a system message.\n` ++ `Received ${llmRequests.length} LLM request(s) but none contained it.`,+ ).toBeTruthy();++ // Verify the block includes key services that should be present+ // in the full agent-canvas stack (agent-server + automation + ingress).+ expect(runtimeBlock).toContain("Agent Server");+ expect(runtimeBlock).toContain("Automation backend");+ expect(runtimeBlock).toContain("/api/automation");+ expect(runtimeBlock).toContain("</RUNTIME_SERVICES>");+ });});// ββ Step 3: Verify automation on list page, click through to detail, verify run link β