|
| 1 | +package python.multiplatform.env |
| 2 | + |
| 3 | +import python.multiplatform.ffi.Python3 |
| 4 | +import python.native.ffi.PyImport_ExecCodeModule |
| 5 | +import python.native.ffi.Py_CompileString |
| 6 | +import python.native.ffi.Py_DecRef |
| 7 | +import python.multiplatform.ffi.pyErrorOrGeneric |
| 8 | + |
| 9 | +/** |
| 10 | + * The dev agent (SPEC L-12, #233): a debug-only channel from a notebook or a hot reload into this |
| 11 | + * interpreter, designed in toolchain's `docs/design/live-connection.md` (option B). |
| 12 | + * |
| 13 | + * [Python3.initialize] calls [startIfRequested]. It does nothing unless the launcher set |
| 14 | + * [ENVIRONMENT_VARIABLE] (`port=<n>;token=<t>[;overlay=<dir>]`), which a debug launch does and a release |
| 15 | + * build never does; then the agent's Python ([DEV_AGENT_SOURCE], embedded from |
| 16 | + * `src/commonMain/python/python_multiplatform_devagent.py`) is loaded as the module [MODULE] and listens on |
| 17 | + * 127.0.0.1 with that token. A malformed request is reported on stderr and does not stop the app. |
| 18 | + */ |
| 19 | +internal object PythonDevAgent { |
| 20 | + const val ENVIRONMENT_VARIABLE = "PYTHON_MULTIPLATFORM_DEV_AGENT" |
| 21 | + const val MODULE = "python_multiplatform_devagent" |
| 22 | + |
| 23 | + private const val PY_FILE_INPUT: Int = 257 |
| 24 | + private var loaded = false |
| 25 | + private var requested = false |
| 26 | + |
| 27 | + fun startIfRequested() { |
| 28 | + if (requested || readEnvVar(ENVIRONMENT_VARIABLE).isNullOrBlank()) return |
| 29 | + requested = true |
| 30 | + try { |
| 31 | + load() |
| 32 | + Python3.exec("__import__(\"$MODULE\").start_from_env()") |
| 33 | + } catch (e: Exception) { |
| 34 | + println("WARNING: python-multiplatform dev agent not started: ${e.message}") |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + /** Loads [DEV_AGENT_SOURCE] as the module [MODULE] (once). */ |
| 39 | + fun load() { |
| 40 | + if (loaded) return |
| 41 | + Python3.withPython { |
| 42 | + val code = Py_CompileString(DEV_AGENT_SOURCE, "<python-multiplatform:devagent>", PY_FILE_INPUT) |
| 43 | + ?: throw pyErrorOrGeneric("Failed to compile the dev agent") |
| 44 | + try { |
| 45 | + val module = PyImport_ExecCodeModule(MODULE, code) |
| 46 | + ?: throw pyErrorOrGeneric("Failed to load the dev agent") |
| 47 | + Py_DecRef(module) |
| 48 | + } finally { |
| 49 | + Py_DecRef(code) |
| 50 | + } |
| 51 | + } |
| 52 | + loaded = true |
| 53 | + } |
| 54 | +} |
0 commit comments