|
1 | 1 | #!/usr/bin/env python3 |
2 | | -"""Native OpenCode CLI connectivity smoke test (smoke v1.0). |
| 2 | +"""Native OpenCode CLI connectivity smoke test (smoke v1.1). |
3 | 3 |
|
4 | 4 | Diagnostic experiment, not production activation. It complements the direct |
5 | 5 | synthetic diagnostic (model_health_diagnostic.py): that script builds direct |
|
22 | 22 | HOME/XDG_* reserved under a dedicated directory, disconnected from the |
23 | 23 | repository checkout (repo source is used only to install the runtime, never |
24 | 24 | loaded into model context). Every tool the pinned runtime exposes is denied |
25 | | -at the config level — read, edit, bash, webfetch, external_directory, task |
26 | | -and todowrite — so a malfunctioning model cannot read or write anything |
27 | | -regardless of what the transcript later shows. |
| 25 | +at the config level except `read`, which is set to `ask` (headless-safe) to |
| 26 | +maintain free-tier compatibility with the live opencode.ai gateway: `read: |
| 27 | +ask` is not auto-approved in headless mode (validated against the real pinned |
| 28 | +CLI, exits 0 with `tool_use(read,error)` and no file-content leakage) and |
| 29 | +does not change the request envelope to trigger a pre-auth 403. The |
| 30 | +transcript-level guard rejects any tool-use event (completed or error), and |
| 31 | +all other tools remain denied. The workflow maps `OPENCODE_API_KEY` only in |
| 32 | +the secret-bearing step, after a credential-free compatibility preflight has |
| 33 | +passed the same envelope with a synthetic key. |
28 | 34 |
|
29 | 35 | Recording: sanitized evidence only — CLI version, model, ok/failed status, |
30 | 36 | reason class, provider HTTP status class, elapsed time and event counts. |
31 | 37 | Never the API key, prompt, URLs, response bodies, headers or stderr text. |
32 | 38 |
|
33 | | -Usage: opencode_native_smoke.py RESULT_JSON BINARY AGENT_HOME WORKDIR TIMEOUT_MIN |
| 39 | +Usage: opencode_native_smoke.py [--preflight] RESULT_JSON BINARY AGENT_HOME WORKDIR TIMEOUT_MIN |
34 | 40 | All three paths are canonicalized to absolute before any subprocess runs (the |
35 | 41 | inference run changes cwd to the workdir; a relative binary path with a slash |
36 | 42 | would otherwise resolve from the wrong directory). The binary must be the |
37 | 43 | checked-out, lockfile-pinned runtime; it is not user-configurable. |
38 | 44 |
|
39 | | -Environment: OPENCODE_API_KEY (read once, never printed, never written). |
40 | | -
|
41 | | -Exit code: 0 only when the CLI version matches the pin, exited 0, produced a |
42 | | -coherent pure-text life cycle ending in step_finish(reason="stop"), and the |
43 | | -run was marked ok. Any other outcome writes a sanitized record and exits 1. |
| 45 | +Preflight mode (--preflight): credential-free synthetic compatibility probe. |
| 46 | +It sends the exact same fixed request envelope with a non-credential synthetic |
| 47 | +key and passes only when the gateway reaches authentication (HTTP 401) instead |
| 48 | +of rejecting the envelope at the policy layer (HTTP 403). It never reads |
| 49 | +OPENCODE_API_KEY. This is the regression guard for the free-tier envelope |
| 50 | +incompatibility that made the merged diagnostic a false negative, and it must |
| 51 | +pass before the workflow maps the real secret. |
| 52 | +
|
| 53 | +Environment: OPENCODE_API_KEY (live mode only; read once, never printed, never |
| 54 | +written; ignored entirely in preflight mode). |
| 55 | +
|
| 56 | +Exit code: 0 only when the CLI version matches the pin and the run met its |
| 57 | +mode's objective (live: coherent pure-text life cycle ending in |
| 58 | +step_finish(reason="stop"); preflight: auth reached with 401). Any other |
| 59 | +outcome writes a sanitized record and exits 1. |
44 | 60 | """ |
45 | 61 | from __future__ import annotations |
46 | 62 |
|
|
51 | 67 | import sys |
52 | 68 | import time |
53 | 69 |
|
54 | | -SMOKE_VERSION = '1.0' |
| 70 | +SMOKE_VERSION = '1.1' |
55 | 71 |
|
56 | 72 | # One fixed model, in the CLI selector (provider/model) form. The selector is |
57 | 73 | # consumed by the CLI; the bare provider ID is never sent anywhere by us. |
|
60 | 76 | # The exact fixed synthetic prompt from the diagnostic mandate. |
61 | 77 | PROMPT = 'Respond with exactly OK' |
62 | 78 |
|
| 79 | +# Preflight mode uses this fixed non-credential placeholder. It is not a secret, |
| 80 | +# cannot authenticate, and proves only that the request envelope is accepted |
| 81 | +# (auth layer reached) rather than policy-rejected before auth. |
| 82 | +SYNTHETIC_KEY = 'synthetic-compatibility-probe-not-a-credential' |
| 83 | + |
63 | 84 | # Pinned runtime version; must match .github/opencode/runtime/package.json. |
64 | 85 | EXPECTED_OPENCODE_VERSION = '1.19.3' |
65 | 86 |
|
|
71 | 92 | ENABLED_PROVIDERS = ('opencode',) |
72 | 93 |
|
73 | 94 | # The fixed prompt needs no tools, so every tool the pinned runtime exposes is |
74 | | -# denied before the transcript can ever show one. All seven keys below are |
75 | | -# recognized permission kinds in opencode-ai 1.19.3 (validated against the |
76 | | -# pinned binary's embedded code: read/edit/bash/webfetch plus the delegation |
77 | | -# kinds external_directory, task and todowrite). read is denied too (B3): the |
78 | | -# CLI inherits OPENCODE_API_KEY, so a filesystem-read tool running at all would |
79 | | -# be an unnecessary exposure surface. |
| 95 | +# denied before the transcript can ever show one — except `read`, which is |
| 96 | +# `ask` (see the compatibility note below). All seven keys are recognized |
| 97 | +# permission kinds in opencode-ai 1.19.3 (validated against the pinned binary's |
| 98 | +# embedded code: read/edit/bash/webfetch plus the delegation kinds |
| 99 | +# external_directory, task and todowrite). |
80 | 100 | # |
81 | | -# Validated envelope note (pinned binary, 2026-10-23): read:'deny' changes the |
82 | | -# outbound tool envelope; on the live opencode.ai gateway a synthetic invalid |
83 | | -# key then receives HTTP 403 (policy layer) where read:'allow' produces HTTP 401 |
84 | | -# (upstream Invalid credential). The success path step_start -> text -> |
85 | | -# step_finish(reason="stop"), exit 0 was verified with this exact hardened |
86 | | -# config against a scripted provider stub, so status 'ok' remains meaningful; |
87 | | -# under this config a 'forbidden' class therefore reflects credential/policy |
88 | | -# state — it must never be read as model unavailability. |
| 101 | +# IMPORTANT (diagnostic compatibility, 2026-10-23): on OpenCode 1.19.3 the |
| 102 | +# free-tier gateway treats `read: 'deny'` as changing the outbound tool envelope |
| 103 | +# and returns HTTP 403 (policy rejection) before auth; the run fails with |
| 104 | +# `provider_error`/`forbidden` even though the network/key path is valid. |
| 105 | +# Headless validation with the real pinned binary + scripted stub (no TTY) |
| 106 | +# shows `read: 'ask'` does NOT auto-approve filesystem reads and does NOT hang: |
| 107 | +# it produces `tool_use(read,error)` and stops (`step_finish(reason=tool-calls)`) |
| 108 | +# without leaking file contents, and exits 0. On the live gateway with a |
| 109 | +# synthetic key, `read: 'ask'` yields HTTP 401 (auth envelope reached), same as |
| 110 | +# `read: 'allow'`. The runner's transcript-level `unexpected_tool_use` check |
| 111 | +# and `evaluate()` still reject every tool-use event, completed or error; |
| 112 | +# `read` remains not 'allow'. This is a diagnostic-only change: it reconciles |
| 113 | +# the native-CLI smoke with free-tier compatibility without granting |
| 114 | +# uncontrolled filesystem access or expanding the credential surface. |
89 | 115 | PERMISSIONS = { |
90 | 116 | 'edit': 'deny', |
91 | | - 'read': 'deny', |
| 117 | + 'read': 'ask', |
92 | 118 | 'bash': 'deny', |
93 | 119 | 'webfetch': 'deny', |
94 | 120 | 'external_directory': 'deny', |
|
106 | 132 | }) |
107 | 133 |
|
108 | 134 | RESULT_KEYS = frozenset({ |
109 | | - 'smoke_version', 'opencode_expected_version', 'opencode_version', |
| 135 | + 'smoke_version', 'mode', 'opencode_expected_version', 'opencode_version', |
110 | 136 | 'model', 'status', 'reason', 'error_class', 'error_status_code', |
111 | 137 | 'exit_code', 'timed_out', 'event_count', 'stderr_lines', 'elapsed_ms', |
112 | 138 | }) |
@@ -299,7 +325,38 @@ def evaluate(lines: list[str], exit_code: int | None, timed_out: bool |
299 | 325 | return 'ok', '', error_class, error_status_code |
300 | 326 |
|
301 | 327 |
|
302 | | -def _write_result(path: str, *, opencode_version: str | None, status: str, reason: str, |
| 328 | +def resolve_key(mode: str, environ: dict) -> str: |
| 329 | + """Return the credential for this mode. |
| 330 | +
|
| 331 | + Preflight never reads OPENCODE_API_KEY: it always uses the fixed synthetic |
| 332 | + placeholder, so a real secret cannot be exposed by the credential-free |
| 333 | + compatibility step even if the workflow environment leaked it. |
| 334 | + """ |
| 335 | + if mode == 'preflight': |
| 336 | + return SYNTHETIC_KEY |
| 337 | + return environ.get('OPENCODE_API_KEY', '') |
| 338 | + |
| 339 | + |
| 340 | +def probe_verdict(status: str, reason: str, error_class: str | None, |
| 341 | + error_status_code: int | None) -> tuple[str, str]: |
| 342 | + """Map one synthetic-key run to the preflight objective. |
| 343 | +
|
| 344 | + Compatible: the gateway answered 401 — the request envelope (config, tools, |
| 345 | + fixed model/prompt) reached authentication and only the fake credential was |
| 346 | + rejected. Anything else fails closed: 403 means the envelope was rejected |
| 347 | + at the policy layer (the exact free-tier regression this guards against), |
| 348 | + and any other outcome is unexpected for a synthetic key. |
| 349 | + """ |
| 350 | + if (status == 'failed' and reason == 'provider_error' |
| 351 | + and error_class == 'auth_error' and error_status_code == 401): |
| 352 | + return 'ok', 'credential_rejected_as_expected' |
| 353 | + if status == 'failed' and error_class == 'forbidden': |
| 354 | + return 'failed', 'config_envelope_rejected' |
| 355 | + return 'failed', 'unexpected_probe_outcome' |
| 356 | + |
| 357 | + |
| 358 | +def _write_result(path: str, *, mode: str = 'live', opencode_version: str | None, |
| 359 | + status: str, reason: str, |
303 | 360 | error_class: str | None, error_status_code: int | None, |
304 | 361 | exit_code: int | None, timed_out: bool, event_count: int, |
305 | 362 | stderr_lines: int, elapsed_ms: int | None) -> dict: |
@@ -312,6 +369,7 @@ def _write_result(path: str, *, opencode_version: str | None, status: str, reaso |
312 | 369 | """ |
313 | 370 | record = { |
314 | 371 | 'smoke_version': SMOKE_VERSION, |
| 372 | + 'mode': mode, |
315 | 373 | 'opencode_expected_version': EXPECTED_OPENCODE_VERSION, |
316 | 374 | 'opencode_version': opencode_version, |
317 | 375 | 'model': MODEL, |
@@ -334,7 +392,7 @@ def _write_result(path: str, *, opencode_version: str | None, status: str, reaso |
334 | 392 | def _summary(record: dict) -> str: |
335 | 393 | """One sanitized status line for the run log (also artifact-consistent).""" |
336 | 394 | return (' '.join([ |
337 | | - f'native smoke: model={record["model"]}', |
| 395 | + f"native smoke: mode={record.get('mode', 'live')} model={record['model']}", |
338 | 396 | 'status ok' if record['status'] == 'ok' else 'status failed', |
339 | 397 | f"reason={record['reason'] or '-'}", |
340 | 398 | f"error_class={record['error_class'] or '-'}", |
@@ -344,11 +402,21 @@ def _summary(record: dict) -> str: |
344 | 402 |
|
345 | 403 |
|
346 | 404 | def main(argv: list[str]) -> int: |
347 | | - if len(argv) != 6: |
348 | | - print('usage: opencode_native_smoke.py RESULT_JSON BINARY AGENT_HOME WORKDIR TIMEOUT_MIN', |
349 | | - file=sys.stderr) |
| 405 | + args = list(argv[1:]) |
| 406 | + preflight = bool(args) and args[0] == '--preflight' |
| 407 | + if preflight: |
| 408 | + args = args[1:] |
| 409 | + if len(args) != 5: |
| 410 | + print('usage: opencode_native_smoke.py [--preflight] RESULT_JSON BINARY ' |
| 411 | + 'AGENT_HOME WORKDIR TIMEOUT_MIN', file=sys.stderr) |
| 412 | + return 2 |
| 413 | + mode = 'preflight' if preflight else 'live' |
| 414 | + result_path, binary, agent_home, workdir = args[0], args[1], args[2], args[3] |
| 415 | + try: |
| 416 | + timeout_min = int(args[4]) |
| 417 | + except ValueError: |
| 418 | + print('timeout must be an integer number of minutes', file=sys.stderr) |
350 | 419 | return 2 |
351 | | - result_path, binary, agent_home, workdir, timeout_min = argv[1], argv[2], argv[3], argv[4], int(argv[5]) |
352 | 420 |
|
353 | 421 | # Canonicalize before any subprocess runs. The inference run later changes |
354 | 422 | # cwd to the smoke workdir; a relative binary containing '/' would then be |
@@ -357,16 +425,17 @@ def main(argv: list[str]) -> int: |
357 | 425 | binary = os.path.abspath(binary) |
358 | 426 | agent_home = os.path.abspath(agent_home) |
359 | 427 | workdir = os.path.abspath(workdir) |
360 | | - key = os.environ.get('OPENCODE_API_KEY', '') |
| 428 | + key = resolve_key(mode, os.environ) |
361 | 429 |
|
362 | 430 | start = time.monotonic() |
363 | 431 |
|
364 | 432 | if not key: |
365 | | - _write_result(result_path, opencode_version=None, status='failed', |
366 | | - reason='missing_api_key', error_class=None, |
367 | | - error_status_code=None, exit_code=None, timed_out=False, |
368 | | - event_count=0, stderr_lines=0, elapsed_ms=None) |
369 | | - print('native smoke: status failed reason=missing_api_key') |
| 433 | + _write_result(result_path, mode=mode, opencode_version=None, |
| 434 | + status='failed', reason='missing_api_key', |
| 435 | + error_class=None, error_status_code=None, exit_code=None, |
| 436 | + timed_out=False, event_count=0, stderr_lines=0, |
| 437 | + elapsed_ms=None) |
| 438 | + print(f'native smoke: mode={mode} status failed reason=missing_api_key') |
370 | 439 | return 1 |
371 | 440 |
|
372 | 441 | # No credential below this line until the inference env is built: the |
@@ -381,19 +450,20 @@ def main(argv: list[str]) -> int: |
381 | 450 | version = read_version(binary, home_env) |
382 | 451 | except (VersionProbeError, OSError, ValueError) as error: |
383 | 452 | reason = _esc_reason(error) or 'opencode_version_unverified' |
384 | | - _write_result(result_path, opencode_version=None, status='failed', |
385 | | - reason=reason, error_class=None, error_status_code=None, |
386 | | - exit_code=None, timed_out=False, event_count=0, |
387 | | - stderr_lines=0, elapsed_ms=None) |
388 | | - print(f'native smoke: status failed reason={reason}') |
| 453 | + _write_result(result_path, mode=mode, opencode_version=None, |
| 454 | + status='failed', reason=reason, error_class=None, |
| 455 | + error_status_code=None, exit_code=None, timed_out=False, |
| 456 | + event_count=0, stderr_lines=0, elapsed_ms=None) |
| 457 | + print(f'native smoke: mode={mode} status failed reason={reason}') |
389 | 458 | return 1 |
390 | 459 |
|
391 | 460 | if version != EXPECTED_OPENCODE_VERSION: |
392 | | - _write_result(result_path, opencode_version=version, status='failed', |
393 | | - reason='opencode_version_mismatch', error_class=None, |
394 | | - error_status_code=None, exit_code=None, timed_out=False, |
395 | | - event_count=0, stderr_lines=0, elapsed_ms=None) |
396 | | - print('native smoke: status failed reason=opencode_version_mismatch') |
| 461 | + _write_result(result_path, mode=mode, opencode_version=version, |
| 462 | + status='failed', reason='opencode_version_mismatch', |
| 463 | + error_class=None, error_status_code=None, exit_code=None, |
| 464 | + timed_out=False, event_count=0, stderr_lines=0, |
| 465 | + elapsed_ms=None) |
| 466 | + print(f'native smoke: mode={mode} status failed reason=opencode_version_mismatch') |
397 | 467 | return 1 |
398 | 468 |
|
399 | 469 | env = build_child_env(agent_home, key) |
@@ -404,7 +474,7 @@ def main(argv: list[str]) -> int: |
404 | 474 | exit_code: int | None = None |
405 | 475 | try: |
406 | 476 | completed = subprocess.run(command, capture_output=True, text=True, |
407 | | - env=env, cwd=workdir, |
| 477 | + env=env, cwd=workdir, stdin=subprocess.DEVNULL, |
408 | 478 | timeout=timeout_min * 60 + 90) |
409 | 479 | lines = completed.stdout.splitlines() |
410 | 480 | exit_code = completed.returncode |
@@ -415,17 +485,23 @@ def main(argv: list[str]) -> int: |
415 | 485 | timed_out = True |
416 | 486 | except OSError: |
417 | 487 | elapsed_ms = int((time.monotonic() - start) * 1000) |
418 | | - _write_result(result_path, opencode_version=version, status='failed', |
419 | | - reason='cli_launch_error', error_class=None, |
420 | | - error_status_code=None, exit_code=None, timed_out=False, |
421 | | - event_count=0, stderr_lines=0, elapsed_ms=elapsed_ms) |
422 | | - print('native smoke: status failed reason=cli_launch_error') |
| 488 | + _write_result(result_path, mode=mode, opencode_version=version, |
| 489 | + status='failed', reason='cli_launch_error', |
| 490 | + error_class=None, error_status_code=None, exit_code=None, |
| 491 | + timed_out=False, event_count=0, stderr_lines=0, |
| 492 | + elapsed_ms=elapsed_ms) |
| 493 | + print(f'native smoke: mode={mode} status failed reason=cli_launch_error') |
423 | 494 | return 1 |
424 | 495 | elapsed_ms = int((time.monotonic() - start) * 1000) |
425 | 496 |
|
426 | 497 | status, reason, error_class, error_status_code = evaluate( |
427 | 498 | lines, exit_code, timed_out) |
428 | | - record = _write_result(result_path, opencode_version=version, |
| 499 | + if mode == 'preflight': |
| 500 | + # The objective is envelope compatibility, not inference: a synthetic |
| 501 | + # key must reach auth (401) rather than be policy-rejected (403). |
| 502 | + status, reason = probe_verdict(status, reason, error_class, |
| 503 | + error_status_code) |
| 504 | + record = _write_result(result_path, mode=mode, opencode_version=version, |
429 | 505 | status=status, reason=reason, error_class=error_class, |
430 | 506 | error_status_code=error_status_code, |
431 | 507 | exit_code=exit_code, timed_out=timed_out, |
|