Documentation menu
Complete script examples and troubleshooting
Authenticated HTTP checks in JavaScript and Python, output validation and runtime failure diagnosis.
These examples describe source APIs. They have not contacted your endpoint or verified a deployed agent’s configuration. Start with a private test agent, review the destination and credentials, and inspect actual run results.
Built-in JavaScript: authenticated HTTP health
Select js. Set Args to {"url":"https://api.example.com/health"} and
credential references to {"api_token":"svc_readonly_token"}. The operator
must allow that local reference and enable the engine. Set a check timeout
long enough for the five-second call plus runtime cleanup.
const rs = require('routespear');
const settings = rs.args();
if (!settings.url || settings.url.indexOf('https://') !== 0) {
throw new Error('Set an HTTPS url in Args');
}
const token = rs.secret('api_token');
try {
const response = rs.http.get(settings.url, {
headers: { Authorization: 'Bearer ' + token },
timeoutMs: 5000,
followRedirects: false
});
rs.duration('http_ms', response.durationMs);
rs.gauge('http_status', response.status, { unit: 'code' });
rs.bool('http_ok', response.status >= 200 && response.status < 300);
} catch (error) {
rs.bool('http_ok', false);
rs.log('HTTP operation failed; no response duration was recorded');
}
A received non-2xx status emits an observed failure and duration. A thrown
network/policy/deadline error emits the failure without inventing response
latency. Invalid args or missing credentials fail before the operation. Disabling
redirects keeps authentication on the configured destination. If you later add
body assertions, check response.truncated before parsing response.body.
Python: authenticated HTTP with the standard library
Select python, with the same args and credential references. This uses the
existing Python SDK for inputs and metrics and urllib for HTTP. It does not
depend on requests or an SDK networking method that does not exist.
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import routespear as rs
settings = rs.args()
url = settings.get("url", "")
if urllib.parse.urlsplit(url).scheme != "https":
raise ValueError("Set an HTTPS url in Args")
token = rs.secret("api_token")
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
opener = urllib.request.build_opener(
urllib.request.ProxyHandler({}), NoRedirect()
)
request = urllib.request.Request(url, headers={"Authorization": "Bearer " + token})
started = time.perf_counter()
status = None
try:
with opener.open(request, timeout=5) as response:
status = response.status
except urllib.error.HTTPError as response:
status = response.code
response.close()
except (urllib.error.URLError, TimeoutError, OSError):
rs.boolean("http_ok", False)
print("HTTP operation failed; no response timing was recorded", file=sys.stderr)
if status is not None:
rs.duration("http_response_ms", (time.perf_counter() - started) * 1000)
rs.gauge("http_status", status, unit="code")
rs.boolean("http_ok", 200 <= status < 300)
This records time to receive response headers, not a downloaded body or a per-hop network measurement. HTTP errors such as 401/500 still provide a status; transport errors do not. The opener verifies HTTPS normally, disables environment proxies and redirects, and does not print a URL/error object that might contain sensitive request data. The five-second socket timeout is separate from the agent’s overall wall-clock deadline. Host networking has the host interpreter’s permissions, unlike the built-in engine’s target-policy host API.
Local SDK output checks
Each language reference contains a fixture example that emits known metrics without network access. Inside an agent run, SDK files and import paths are supplied automatically. No SDK installation or path setup is needed there.
The following instructions are only for developers running a script directly from a repository checkout, outside the agent. Such a standalone run needs the SDK import path, JSON on stdin and any relevant context environment. It does not verify the agent’s grants, target policy, scheduling or result ingestion.
For Python, with the repository checked out, one local invocation is:
printf '%s' '{"depth":12,"request_count":4,"samples_ms":[12,18,22]}' \
| PYTHONPATH=agent/plugins/script/internal/sdk/files python3 example.py
Expect only metric JSON lines on stdout. Capture stderr separately. Check metric names, kinds, values, units, labels and counter temporality. A zero exit code alone does not establish that every metric passed the runtime’s parser.
Diagnose a failed run
| Symptom | What to inspect |
|---|---|
| Execution refused before code runs | Plugin presence, local execution grant, interpreter allowlist or bundle trust/revision/expiry. |
| Import fails | Correct language/import, runtime-provided SDK path and installed host interpreter. No pip/npm installation should be needed for the bundled SDK itself. |
| Secret unavailable | Script-side name, credential_refs map, store key and operator -script-secrets allowlist. Scripts cannot use shared-secret delivery. |
| Args decoding error | Valid JSON, byte limit, and whether another operation consumed stdin first. |
rs.http missing in Python/Node |
Those host SDKs have no engine networking API. Use the language’s networking library or choose built-in js. |
| DNS family rejected | Built-in engine accepts any, ipv4, ipv6, not ip4 or ip6. |
| Metrics missing with successful process exit | Stdout formatting, rejected lines, reserved names, non-finite values, label/series/metric limits and truncation. |
| Timeout | Effective runtime deadline, call timeouts, CPU work, loops and cleanup margin; do not just raise an unrelated setting. |
| Unexpected malformed lines | Logs on stdout, uncaptured shell helper output, or PowerShell pipeline output. |
| Multiple measurements collapse into one series | Inspect the metric name and stable label set; do not compensate with unbounded timestamps or request-ID labels. |
Preserve the distinction between script/configuration failures, an observed service failure and missing measurements. SDK helpers do not automatically convert those into equivalent health results.