-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.py
More file actions
1250 lines (1060 loc) · 52.7 KB
/
Copy pathplugin.py
File metadata and controls
1250 lines (1060 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Workbench plugin that installs, configures, and launches Codex CLI instances.
Codex is an agent *harness*: it supplies the tools, sandbox, and edit loop while
the reasoning comes from a backing model. Here the model is served by the local
EmuLLM relay (``router/gpt-5.6-sol`` over its keyless OpenAI-compatible ``/v1``
surface at ``http://127.0.0.1:8801/v1``). **Codex is only a client of EmuLLM**;
this plugin never starts, stops, or reconfigures EmuLLM.
The plugin manages any number of *instances*. Each instance is an isolated
``CODEX_HOME`` under ``homes/<name>/`` with its own ``config.toml``, auth, and
history, plus a target model, base URL, and workspace directory. Two surfaces
manage them:
* a dedicated manager page served at ``/codex_cli/manage`` (a table of instances
with per-row install / configure / launch / delete and a create form), and
* the native administration descriptor (an instance selector plus
create / launch / delete actions for one-at-a-time management).
Only routes are added to the workbench API process; there is no standalone
server. Secrets are never persisted: the launcher exports a placeholder key
because EmuLLM's ``/v1`` surface is keyless.
"""
from __future__ import annotations
import asyncio
import contextlib
import json
import os
import re
import shutil
import subprocess
import threading
import time
import uuid
from pathlib import Path
from typing import Any
import httpx
from fastapi import APIRouter, Body, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
import plugin_admin
try: # Cross-platform PTY for the in-browser codex terminal (Launch).
if os.name == "nt":
from winpty import PtyProcess # type: ignore # pywinpty (Windows ConPTY)
else:
from ptyprocess import PtyProcessUnicode as PtyProcess # type: ignore # POSIX pty
_PTY_IMPORT_ERROR = ""
except Exception as _err: # noqa: BLE001 - the terminal degrades with a clear message
PtyProcess = None # type: ignore
_PTY_IMPORT_ERROR = str(_err)
# Per-instance defaults. The model is served by the local EmuLLM relay; Codex is
# only a client of it, so nothing here starts, stops, or reconfigures EmuLLM.
INSTANCE_DEFAULTS: dict[str, str] = {
"model": "router/gpt-5.6-sol",
"providerId": "emullm",
"providerLabel": "EmuLLM Router",
"baseUrl": "http://127.0.0.1:8801/v1",
"wireApi": "responses",
"envKey": "EMULLM_API_KEY",
"workspaceDir": r"C:\snet\PeTTa\repos\symbolic_learner_workbench",
}
WIRE_API_CHOICES = ("responses", "chat")
DEFAULT_INSTANCE = "default"
# Codex 0.152.1 speaks only the Responses API, but most LAN models expose
# chat/completions. The plugin runs a local Responses<->chat adapter that Codex
# points at; it forwards to the instance's real upstream (any OpenAI-compatible
# LAN model, EmuLLM included -- no endpoint is special-cased). This is where the
# workbench API answers, used to build the adapter URL written into config.toml.
DEFAULT_API_BASE = "http://127.0.0.1:8000"
# EmuLLM's /v1 surface is keyless, but Codex still expects the provider's
# env_key variable to hold *some* value, so the launcher exports this placeholder.
EMULLM_PLACEHOLDER_KEY = "emullm-local"
_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
# Populated by _check_codex()/initialize() so the pages can show the version
# without spawning Codex on every render.
_VERSION_CACHE: dict[str, str] = {}
# --- filesystem / binary resolution ------------------------------------------
def _plugin_dir(manifest: dict[str, Any]) -> Path:
return plugin_admin.plugin_directory(manifest)
def _homes_dir(manifest: dict[str, Any]) -> Path:
return _plugin_dir(manifest) / "homes"
def _codex_entry(manifest: dict[str, Any]) -> Path:
"""Path to the CLI's Node entrypoint inside the local install."""
return _plugin_dir(manifest) / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"
def _node() -> str | None:
return shutil.which("node")
def _codex_installed(manifest: dict[str, Any]) -> bool:
return _codex_entry(manifest).is_file()
def _run_codex(manifest: dict[str, Any], args: list[str], *, timeout: float = 30.0) -> tuple[bool, str]:
"""Run ``codex <args>`` through the local Node install; return (ok, output)."""
node = _node()
if node is None:
return False, "Node.js was not found on PATH (Codex requires Node.js 22+)."
entry = _codex_entry(manifest)
if not entry.is_file():
return False, "Codex CLI is not installed. Use Launch or Install (npm install)."
try:
result = subprocess.run( # noqa: S603 - fixed node executable and local entrypoint
[node, str(entry), *args],
capture_output=True, text=True, timeout=timeout,
cwd=str(_plugin_dir(manifest)), check=False,
)
except (OSError, subprocess.SubprocessError) as error:
return False, f"Failed to launch Codex: {error}"
output = (result.stdout or "").strip() or (result.stderr or "").strip()
return result.returncode == 0, output
def _check_codex(manifest: dict[str, Any]) -> dict[str, Any]:
ok, output = _run_codex(manifest, ["--version"], timeout=30.0)
if ok and output:
_VERSION_CACHE[str(_plugin_dir(manifest))] = output
return {"ok": ok, "version": output if ok else "", "entrypoint": str(_codex_entry(manifest)), "detail": output}
def _ensure_installed(manifest: dict[str, Any]) -> dict[str, Any]:
"""Install the vendored Codex CLI (npm install) if it is not present yet.
All instances share the one vendored binary and differ only by CODEX_HOME.
"""
if _codex_installed(manifest):
return {"ok": True, "installed": True, "ranInstall": False}
npm = shutil.which("npm") or shutil.which("npm.cmd")
if npm is None:
return {"ok": False, "installed": False, "ranInstall": False,
"detail": "npm was not found on PATH (Node.js 22+ is required)."}
try:
result = subprocess.run( # noqa: S603 - fixed npm executable, no shell
[npm, "install", "--no-audit", "--no-fund"],
capture_output=True, text=True, timeout=600,
cwd=str(_plugin_dir(manifest)), check=False,
)
except (OSError, subprocess.SubprocessError) as error:
return {"ok": False, "installed": False, "ranInstall": True, "detail": str(error)}
ok = result.returncode == 0 and _codex_installed(manifest)
detail = "" if ok else (result.stderr or result.stdout or "npm install failed").strip()[-2000:]
return {"ok": ok, "installed": _codex_installed(manifest), "ranInstall": True, "detail": detail}
# --- in-browser codex terminal (Launch) --------------------------------------
async def _bridge_codex_terminal(ws: WebSocket, manifest: dict[str, Any], name: str) -> None:
"""Run ``node codex.js`` for one instance under a PTY, bridged to xterm.js.
The instance's CODEX_HOME, workspace cwd, and keyless placeholder key are
applied, so the browser terminal is the same Codex session the OS launcher
would start -- served in the workbench instead of a separate console.
"""
async def fail(text: str) -> None:
with contextlib.suppress(Exception):
await ws.send_text(f"\r\n[codex] {text}\r\n")
await ws.close()
if PtyProcess is None:
await fail(f"PTY backend unavailable: {_PTY_IMPORT_ERROR or 'winpty/ptyprocess not installed'}")
return
install = _ensure_installed(manifest)
if not install.get("ok"):
await fail(f"install failed: {install.get('detail')}")
return
cfg = _instance_config(manifest, name)
workspace = cfg.get("workspaceDir") or str(_plugin_dir(manifest))
if not Path(workspace).is_dir():
await fail(f"workspace directory does not exist: {workspace}")
return
node = shutil.which("node")
entry = _codex_entry(manifest)
if not node or not entry.is_file():
await fail("Node.js or the Codex CLI is not available")
return
_write_instance_config(manifest, name)
env = dict(os.environ)
env["CODEX_HOME"] = str(_home_dir(manifest, name))
env[cfg.get("envKey") or "EMULLM_API_KEY"] = EMULLM_PLACEHOLDER_KEY
try:
proc = PtyProcess.spawn([node, str(entry)], cwd=str(workspace), env=env, dimensions=(30, 100))
except Exception as error: # noqa: BLE001
await fail(f"failed to start codex: {error}")
return
loop = asyncio.get_running_loop()
outq: asyncio.Queue = asyncio.Queue()
def reader() -> None:
while True:
try:
data = proc.read(65536)
except EOFError:
break
except Exception: # noqa: BLE001
break
if data:
loop.call_soon_threadsafe(outq.put_nowait, data)
loop.call_soon_threadsafe(outq.put_nowait, None)
threading.Thread(target=reader, daemon=True).start()
async def sender() -> None:
while True:
data = await outq.get()
if data is None:
break
with contextlib.suppress(Exception):
await ws.send_text(data)
with contextlib.suppress(Exception):
await ws.send_text("\r\n[codex exited]\r\n")
with contextlib.suppress(Exception):
await ws.close()
send_task = loop.create_task(sender())
def _clamp(value: Any, fallback: int, hi: int) -> int:
try:
return max(1, min(hi, int(value)))
except (TypeError, ValueError):
return fallback
try:
while True:
message = await ws.receive_text()
control: Any = None
with contextlib.suppress(Exception):
control = json.loads(message)
if isinstance(control, dict) and control.get("t") == "i":
with contextlib.suppress(Exception):
proc.write(control.get("d", ""))
elif isinstance(control, dict) and control.get("t") == "r":
with contextlib.suppress(Exception):
proc.setwinsize(_clamp(control.get("r"), 30, 200), _clamp(control.get("c"), 100, 500))
else:
with contextlib.suppress(Exception):
proc.write(message)
except WebSocketDisconnect:
pass
finally:
with contextlib.suppress(Exception):
proc.terminate(force=True)
send_task.cancel()
def _codex_terminal_html(name: str) -> str:
return _CODEX_TERM_HTML.replace("__NAME__", name)
# --- Responses <-> chat/completions adapter ----------------------------------
# Codex 0.152.1 speaks only the Responses API. Most LAN models expose
# chat/completions (often with OpenAI tool-calling). This adapter presents a
# Responses surface to Codex and forwards to the instance's upstream via
# chat/completions -- so ANY OpenAI-chat LAN model works as an agentic Codex.
# It is model-agnostic: EmuLLM is treated exactly like any other upstream, gets
# no special path, and tool-calls only flow if the upstream actually emits them.
# Tools are NEVER executed here -- tool-calls are relayed to Codex, which runs
# them locally in its workspace.
def _rid(prefix: str) -> str:
return f"{prefix}-{uuid.uuid4().hex[:24]}"
def _flatten_text(content: Any) -> str:
"""Collapse a Responses/chat content value into plain text."""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
if isinstance(item.get("text"), str):
parts.append(item["text"])
elif isinstance(item.get("content"), (list, str)):
nested = _flatten_text(item["content"])
if nested:
parts.append(nested)
return "\n".join(p for p in parts if p)
if content is None:
return ""
return str(content)
def _stringify(value: Any) -> str:
if isinstance(value, str):
return value
if isinstance(value, list):
return _flatten_text(value)
try:
return json.dumps(value, ensure_ascii=False)
except (TypeError, ValueError):
return str(value)
def _responses_input_to_messages(body: dict[str, Any]) -> list[dict[str, Any]]:
"""Convert a Responses request (instructions + input items) to chat messages."""
messages: list[dict[str, Any]] = []
instructions = body.get("instructions")
instr_text = _flatten_text(instructions) if instructions else ""
if instr_text:
messages.append({"role": "system", "content": instr_text})
inp = body.get("input")
if isinstance(inp, str):
if inp:
messages.append({"role": "user", "content": inp})
return messages
if not isinstance(inp, list):
return messages
for item in inp:
if isinstance(item, str):
messages.append({"role": "user", "content": item})
continue
if not isinstance(item, dict):
continue
itype = item.get("type")
if itype in (None, "message"):
role = item.get("role") or "user"
if role == "developer":
role = "system"
messages.append({"role": role, "content": _flatten_text(item.get("content"))})
elif itype == "function_call":
messages.append({
"role": "assistant",
"content": None,
"tool_calls": [{
"id": item.get("call_id") or item.get("id") or _rid("call"),
"type": "function",
"function": {"name": item.get("name") or "", "arguments": item.get("arguments") or "{}"},
}],
})
elif itype == "function_call_output":
messages.append({
"role": "tool",
"tool_call_id": item.get("call_id") or item.get("id") or "",
"content": _stringify(item.get("output")),
})
# Other item types (reasoning, etc.) carry no chat-relevant text; skip.
return messages
def _responses_tools_to_chat(tools: Any) -> list[dict[str, Any]] | None:
"""Convert Responses function tools to chat/completions tool definitions."""
out: list[dict[str, Any]] = []
for tool in tools or []:
if not isinstance(tool, dict):
continue
if tool.get("type") != "function":
# Non-function built-in tool types are not expressible as chat
# functions; skip them (captured for later refinement if needed).
continue
fn = tool.get("function") if isinstance(tool.get("function"), dict) else {
key: tool.get(key) for key in ("name", "description", "parameters", "strict")
}
name = fn.get("name")
if not name:
continue
out.append({"type": "function", "function": {
"name": name,
"description": fn.get("description") or "",
"parameters": fn.get("parameters") or {"type": "object", "properties": {}},
}})
return out or None
def _chat_to_responses_result(chat: dict[str, Any], model: str) -> dict[str, Any]:
"""Convert a chat/completions response into a Responses result object."""
choice = (chat.get("choices") or [{}])[0]
message = choice.get("message") if isinstance(choice.get("message"), dict) else {}
output: list[dict[str, Any]] = []
for call in message.get("tool_calls") or []:
if not isinstance(call, dict):
continue
fn = call.get("function") if isinstance(call.get("function"), dict) else {}
output.append({
"id": _rid("fc"),
"type": "function_call",
"status": "completed",
"name": fn.get("name") or "",
"arguments": fn.get("arguments") or "{}",
"call_id": call.get("id") or _rid("call"),
})
text = message.get("content")
text = _flatten_text(text) if not isinstance(text, str) else text
if text:
output.append({
"id": _rid("msg"),
"type": "message",
"role": "assistant",
"status": "completed",
"content": [{"type": "output_text", "text": text, "annotations": []}],
})
usage_in = (chat.get("usage") or {}).get("prompt_tokens", 0)
usage_out = (chat.get("usage") or {}).get("completion_tokens", 0)
return {
"id": _rid("resp"),
"object": "response",
"created_at": int(time.time()),
"model": model,
"status": "completed",
"output_text": text or "",
"output": output,
"usage": {"input_tokens": usage_in, "output_tokens": usage_out,
"total_tokens": usage_in + usage_out},
}
def _responses_sse(result: dict[str, Any]) -> Any:
"""Yield a spec-compliant Responses SSE stream for message + function_call items."""
seq = 0
def frame(event_type: str, payload: dict[str, Any]) -> str:
nonlocal seq
data = {**payload, "type": event_type, "sequence_number": seq}
seq += 1
return f"event: {event_type}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
started = {**result, "status": "in_progress", "output": [], "output_text": ""}
yield frame("response.created", {"response": started})
yield frame("response.in_progress", {"response": started})
for index, item in enumerate(result["output"]):
if item["type"] == "message":
text = item["content"][0]["text"] if item.get("content") else ""
yield frame("response.output_item.added",
{"output_index": index, "item": {**item, "status": "in_progress", "content": []}})
yield frame("response.content_part.added", {
"item_id": item["id"], "output_index": index, "content_index": 0,
"part": {"type": "output_text", "text": "", "annotations": []}})
yield frame("response.output_text.delta", {
"item_id": item["id"], "output_index": index, "content_index": 0, "delta": text})
yield frame("response.output_text.done", {
"item_id": item["id"], "output_index": index, "content_index": 0, "text": text})
yield frame("response.content_part.done", {
"item_id": item["id"], "output_index": index, "content_index": 0,
"part": {"type": "output_text", "text": text, "annotations": []}})
yield frame("response.output_item.done", {"output_index": index, "item": item})
elif item["type"] == "function_call":
args = item.get("arguments") or "{}"
yield frame("response.output_item.added",
{"output_index": index, "item": {**item, "status": "in_progress", "arguments": ""}})
yield frame("response.function_call_arguments.delta",
{"item_id": item["id"], "output_index": index, "delta": args})
yield frame("response.function_call_arguments.done",
{"item_id": item["id"], "output_index": index, "arguments": args})
yield frame("response.output_item.done", {"output_index": index, "item": item})
yield frame("response.completed", {"response": result})
async def _adapter_complete(manifest: dict[str, Any], name: str, body: dict[str, Any]) -> dict[str, Any]:
"""Forward a Responses request to the instance's upstream via chat/completions."""
cfg = _instance_config(manifest, name)
upstream = (cfg.get("baseUrl") or "").rstrip("/")
if not upstream:
raise HTTPException(status_code=400, detail=f"Instance '{name}' has no upstream baseUrl configured")
payload: dict[str, Any] = {
"model": body.get("model") or cfg["model"],
"messages": _responses_input_to_messages(body),
"stream": False,
}
tools = _responses_tools_to_chat(body.get("tools"))
if tools:
payload["tools"] = tools
choice = body.get("tool_choice")
if choice is not None:
payload["tool_choice"] = choice
if body.get("temperature") is not None:
payload["temperature"] = body["temperature"]
headers = {"content-type": "application/json"}
key = os.environ.get(cfg.get("envKey") or "", "")
if key:
headers["authorization"] = f"Bearer {key}"
try:
async with httpx.AsyncClient(timeout=600) as client:
response = await client.post(f"{upstream}/chat/completions", json=payload, headers=headers)
except httpx.HTTPError as error:
raise HTTPException(status_code=502, detail=f"upstream request failed: {error}") from error
if response.status_code >= 400:
raise HTTPException(status_code=response.status_code,
detail=f"upstream {response.status_code}: {response.text[:800]}")
try:
chat = response.json()
except ValueError as error:
raise HTTPException(status_code=502, detail=f"upstream returned non-JSON: {error}") from error
return _chat_to_responses_result(chat, payload["model"])
# --- instance registry -------------------------------------------------------
def _safe_name(name: str) -> str:
name = (name or "").strip()
if not _NAME_RE.match(name):
raise HTTPException(
status_code=400,
detail="Instance name must be 1-64 chars: letters, digits, dot, dash, underscore, "
"and start alphanumeric.",
)
return name
def _registry(manifest: dict[str, Any]) -> dict[str, dict[str, Any]]:
stored = manifest.get("instances")
return dict(stored) if isinstance(stored, dict) else {}
def _home_dir(manifest: dict[str, Any], name: str) -> Path:
return _homes_dir(manifest) / name
def _instance_config(manifest: dict[str, Any], name: str) -> dict[str, str]:
"""Effective config for one instance: defaults overlaid with its registry entry."""
entry = _registry(manifest).get(name)
merged = dict(INSTANCE_DEFAULTS)
if isinstance(entry, dict):
for key in INSTANCE_DEFAULTS:
value = entry.get(key)
if isinstance(value, str) and value.strip():
merged[key] = value.strip()
if merged["wireApi"] not in WIRE_API_CHOICES:
merged["wireApi"] = "responses"
return merged
def _instance_names(manifest: dict[str, Any]) -> list[str]:
"""Union of registered instances and on-disk home directories, sorted.
Scanning ``homes/`` means a home created outside the workbench still shows up.
"""
names = set(_registry(manifest))
homes = _homes_dir(manifest)
if homes.is_dir():
for child in homes.iterdir():
if child.is_dir() and _NAME_RE.match(child.name):
names.add(child.name)
if not names:
names.add(DEFAULT_INSTANCE)
return sorted(names)
def _active_name(manifest: dict[str, Any]) -> str:
active = str(manifest.get("activeInstance") or "").strip()
names = _instance_names(manifest)
if active in names:
return active
return names[0] if names else DEFAULT_INSTANCE
# --- config.toml & launcher --------------------------------------------------
def _config_path(manifest: dict[str, Any], name: str) -> Path:
return _home_dir(manifest, name) / "config.toml"
def _launcher_path(manifest: dict[str, Any], name: str) -> Path:
return _home_dir(manifest, name) / "launch_codex.bat"
def _toml_str(value: str) -> str:
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
def _api_base(manifest: dict[str, Any]) -> str:
return str(manifest.get("apiBase") or DEFAULT_API_BASE).rstrip("/")
def _adapter_url(manifest: dict[str, Any], name: str) -> str:
"""The local Responses<->chat adapter URL Codex points at for this instance."""
return f"{_api_base(manifest)}/codex_cli/v1/{name}"
def _render_config_toml(cfg: dict[str, str], name: str, base_url: str) -> str:
lines = [
f"# Generated by the workbench codex_cli plugin for instance '{name}'.",
"# base_url is the plugin's local Responses<->chat adapter, which forwards",
f"# to the instance's upstream model ({cfg.get('baseUrl') or 'unset'}).",
"",
]
if cfg["model"]:
lines.append(f"model = {_toml_str(cfg['model'])}")
provider = cfg["providerId"] or "lan"
lines.append(f"model_provider = {_toml_str(provider)}")
lines.append("")
lines.append(f"[model_providers.{provider}]")
lines.append(f"name = {_toml_str(cfg['providerLabel'] or provider)}")
lines.append(f"base_url = {_toml_str(base_url)}")
lines.append(f"wire_api = {_toml_str(cfg['wireApi'])}")
if cfg["envKey"]:
lines.append(f"env_key = {_toml_str(cfg['envKey'])}")
return "\n".join(lines) + "\n"
def _write_instance_config(manifest: dict[str, Any], name: str) -> Path:
cfg = _instance_config(manifest, name)
home = _home_dir(manifest, name)
home.mkdir(parents=True, exist_ok=True)
target = _config_path(manifest, name)
target.write_text(_render_config_toml(cfg, name, _adapter_url(manifest, name)), encoding="utf-8")
return target
def _write_instance_launcher(manifest: dict[str, Any], name: str) -> Path:
cfg = _instance_config(manifest, name)
home = _home_dir(manifest, name)
home.mkdir(parents=True, exist_ok=True)
entry = _codex_entry(manifest)
workspace = cfg.get("workspaceDir") or str(_plugin_dir(manifest))
env_key = cfg.get("envKey") or "EMULLM_API_KEY"
lines = [
"@echo off",
f"REM Generated by the workbench codex_cli plugin for instance '{name}'.",
f'set "CODEX_HOME={home}"',
f'set "{env_key}={EMULLM_PLACEHOLDER_KEY}"',
f'cd /d "{workspace}"',
f'node "{entry}" %*',
]
target = _launcher_path(manifest, name)
target.write_text("\r\n".join(lines) + "\r\n", encoding="utf-8")
return target
# --- instance operations -----------------------------------------------------
def _persist_registry(manifest: dict[str, Any], registry: dict[str, dict[str, Any]],
*, active: str | None = None) -> None:
values: dict[str, Any] = {"instances": registry}
if active is not None:
values["activeInstance"] = active
plugin_admin.write_manifest_values(manifest, values)
manifest["instances"] = registry
if active is not None:
manifest["activeInstance"] = active
def _create_instance(manifest: dict[str, Any], name: str, overrides: dict[str, Any]) -> dict[str, Any]:
name = _safe_name(name)
registry = _registry(manifest)
if name in registry or _home_dir(manifest, name).exists():
raise HTTPException(status_code=409, detail=f"Instance already exists: {name}")
entry = {key: str(overrides[key]).strip() for key in INSTANCE_DEFAULTS
if key in overrides and isinstance(overrides[key], str) and str(overrides[key]).strip()}
registry[name] = entry
_persist_registry(manifest, registry, active=name)
_write_instance_config(manifest, name)
return {"ok": True, "name": name, "config": _instance_config(manifest, name)}
def _update_instance(manifest: dict[str, Any], name: str, overrides: dict[str, Any]) -> dict[str, Any]:
name = _safe_name(name)
registry = _registry(manifest)
entry = dict(registry.get(name) or {})
for key in INSTANCE_DEFAULTS:
if key in overrides and isinstance(overrides[key], str):
entry[key] = overrides[key].strip()
if entry.get("wireApi") and entry["wireApi"] not in WIRE_API_CHOICES:
entry["wireApi"] = "responses"
registry[name] = entry
_persist_registry(manifest, registry)
_write_instance_config(manifest, name)
return {"ok": True, "name": name, "config": _instance_config(manifest, name)}
def _delete_instance(manifest: dict[str, Any], name: str) -> dict[str, Any]:
name = _safe_name(name)
registry = _registry(manifest)
registry.pop(name, None)
home = _home_dir(manifest, name)
removed = False
if home.is_dir():
shutil.rmtree(home, ignore_errors=True)
removed = True
active = _active_name({**manifest, "instances": registry, "activeInstance": ""})
_persist_registry(manifest, registry, active=active)
return {"ok": True, "name": name, "homeRemoved": removed}
def _launch_instance(manifest: dict[str, Any], name: str) -> dict[str, Any]:
name = _safe_name(name)
cfg = _instance_config(manifest, name)
workspace = Path(cfg.get("workspaceDir") or "")
if not workspace.is_dir():
return {"ok": False, "detail": f"Workspace directory does not exist: {workspace}"}
install = _ensure_installed(manifest)
if not install.get("ok"):
return {"ok": False, "stage": "install", "detail": install.get("detail", "install failed")}
# Record the instance if it existed only as an on-disk home.
registry = _registry(manifest)
if name not in registry:
registry[name] = {}
_persist_registry(manifest, registry)
config_path = _write_instance_config(manifest, name)
launcher = _write_instance_launcher(manifest, name)
spawned, spawn_detail = False, ""
try:
subprocess.Popen( # noqa: S603 - fixed cmd, argument list, no user shell string
["cmd", "/c", "start", f"Codex - {name}", "cmd", "/k", str(launcher)],
cwd=str(workspace), close_fds=True,
)
spawned = True
except (OSError, subprocess.SubprocessError) as error:
spawn_detail = str(error)
return {
"ok": True, "name": name, "installed": install.get("installed"),
"ranInstall": install.get("ranInstall"), "configPath": str(config_path),
"launcher": str(launcher), "workspace": str(workspace),
"model": cfg["model"], "baseUrl": cfg["baseUrl"], "spawnedConsole": spawned,
"detail": "Codex launched in a new console."
if spawned else f"Config and launcher written; run {launcher} in a terminal."
+ (f" (console launch failed: {spawn_detail})" if spawn_detail else ""),
}
def _instance_status(manifest: dict[str, Any], name: str) -> dict[str, Any]:
cfg = _instance_config(manifest, name)
return {
"name": name,
"model": cfg["model"],
"baseUrl": cfg["baseUrl"],
"wireApi": cfg["wireApi"],
"providerId": cfg["providerId"],
"providerLabel": cfg["providerLabel"],
"envKey": cfg["envKey"],
"workspaceDir": cfg["workspaceDir"],
"homeExists": _home_dir(manifest, name).is_dir(),
"configWritten": _config_path(manifest, name).is_file(),
"launcherWritten": _launcher_path(manifest, name).is_file(),
"workspaceExists": bool(cfg["workspaceDir"]) and Path(cfg["workspaceDir"]).is_dir(),
}
def _list_instances(manifest: dict[str, Any]) -> dict[str, Any]:
names = _instance_names(manifest)
return {
"instances": [_instance_status(manifest, name) for name in names],
"active": _active_name(manifest),
"installed": _codex_installed(manifest),
"codexVersion": _VERSION_CACHE.get(str(_plugin_dir(manifest)), ""),
"node": _node() or "",
}
# --- administration descriptor (option B) ------------------------------------
def _describe(manifest: dict[str, Any]) -> dict[str, Any]:
node = _node()
installed = _codex_installed(manifest)
version = _VERSION_CACHE.get(str(_plugin_dir(manifest)), "")
names = _instance_names(manifest)
active = _active_name(manifest)
st = _instance_status(manifest, active)
status_items = [
plugin_admin.status("Route prefix", plugin_admin.admin_prefix(manifest), "neutral"),
plugin_admin.status("Node.js", node or "not found", "ok" if node else "error",
detail="" if node else "Codex requires Node.js 22+ on PATH."),
plugin_admin.status("Codex CLI", "installed" if installed else "not installed",
"ok" if installed else "warn",
detail="" if installed else "Use Launch or Install."),
plugin_admin.status("Codex version", version or "unknown", "ok" if version else "neutral"),
plugin_admin.status("Instances", len(names), "ok"),
plugin_admin.status("Active instance", active, "ok"),
plugin_admin.status("Model (served by EmuLLM)", st["model"] or "(unset)", "ok" if st["model"] else "warn"),
plugin_admin.status("EmuLLM base URL", st["baseUrl"] or "(unset)", "ok" if st["baseUrl"] else "warn",
detail="Codex is only a client of EmuLLM; EmuLLM is not modified."),
plugin_admin.status("Workspace", st["workspaceDir"] or "(unset)",
"ok" if st["workspaceExists"] else "warn"),
plugin_admin.status("config.toml", "written" if st["configWritten"] else "not written",
"ok" if st["configWritten"] else "warn", detail=str(_config_path(manifest, active))),
]
instance_section = plugin_admin.section(
"instance", "Active instance",
[
plugin_admin.field("activeInstance", "Instance", "select", active,
help_text="Which instance the fields and actions below apply to.",
options=names),
plugin_admin.field("model", "Model", "text", st["model"],
help_text="Model served by EmuLLM's router, e.g. router/gpt-5.6-sol.",
placeholder="router/gpt-5.6-sol"),
plugin_admin.field("baseUrl", "Base URL", "text", st["baseUrl"],
help_text="EmuLLM's keyless OpenAI-compatible base URL, including /v1.",
placeholder="http://127.0.0.1:8801/v1"),
plugin_admin.field("wireApi", "Wire API", "select", st["wireApi"], options=WIRE_API_CHOICES),
plugin_admin.field("workspaceDir", "Workspace directory", "text", st["workspaceDir"],
help_text="Directory Codex runs in for this instance.",
placeholder=r"C:\snet\PeTTa\repos\symbolic_learner_workbench"),
plugin_admin.field("providerId", "Provider id", "text", st["providerId"], placeholder="emullm"),
plugin_admin.field("providerLabel", "Provider label", "text", st["providerLabel"],
placeholder="EmuLLM Router"),
plugin_admin.field("envKey", "API key env var", "text", st["envKey"],
help_text="EmuLLM is keyless; the launcher sets a placeholder. Never stored here.",
placeholder="EMULLM_API_KEY"),
],
description="Select an instance and edit it. Save settings to persist and write its config.toml.",
)
create_section = plugin_admin.section(
"create", "Create instance",
[
plugin_admin.field("newInstanceName", "New instance name", "text",
str(manifest.get("newInstanceName") or ""),
help_text="Type a name, Save settings, then use the Create instance action.",
placeholder="scratch"),
],
description="New instances start from the EmuLLM defaults; edit them after creating.",
)
return plugin_admin.descriptor(
manifest,
title="Codex CLI",
summary="Install, configure, and launch Codex instances (served by EmuLLM router/gpt-5.6-sol).",
status_items=status_items,
sections=[instance_section, create_section],
actions=[
plugin_admin.action("launch", "Launch active", tone="primary",
description="Install if needed, write config, open Codex for the active instance."),
plugin_admin.action("createInstance", "Create instance",
description="Create the instance named above from EmuLLM defaults."),
plugin_admin.action("deleteInstance", "Delete active",
description="Remove the active instance's home directory and registry entry."),
plugin_admin.action("checkCodex", "Check Codex", description="Run codex --version."),
plugin_admin.action("writeConfig", "Write active config",
description="Regenerate the active instance's config.toml."),
],
)
def _apply_settings(manifest: dict[str, Any], values: dict[str, Any]) -> dict[str, Any]:
# Switch the active instance first, so field edits apply to the intended one.
requested = str(values.get("activeInstance") or "").strip()
active = requested if requested in _instance_names(manifest) else _active_name(manifest)
registry = _registry(manifest)
entry = dict(registry.get(active) or {})
for key in INSTANCE_DEFAULTS:
if key in values and isinstance(values[key], str):
entry[key] = values[key].strip()
if entry.get("wireApi") and entry["wireApi"] not in WIRE_API_CHOICES:
entry["wireApi"] = "responses"
registry[active] = entry
new_name = ""
if "newInstanceName" in values and isinstance(values["newInstanceName"], str):
new_name = values["newInstanceName"].strip()
plugin_admin.write_manifest_values(
manifest, {"instances": registry, "activeInstance": active, "newInstanceName": new_name}
)
manifest["instances"] = registry
manifest["activeInstance"] = active
manifest["newInstanceName"] = new_name
_write_instance_config(manifest, active)
return {"ok": True, "active": active, "config": _instance_config(manifest, active)}
# --- routers -----------------------------------------------------------------
def create_admin_router(manifest: dict[str, Any]) -> APIRouter:
"""Build the Codex CLI configure descriptor page (option B)."""
def describe() -> dict[str, Any]:
return _describe(manifest)
def apply_settings(values: dict[str, Any]) -> dict[str, Any]:
return _apply_settings(manifest, values)
def launch_action(_body: dict[str, Any]) -> dict[str, Any]:
return _launch_instance(manifest, _active_name(manifest))
def create_action(_body: dict[str, Any]) -> dict[str, Any]:
name = str(manifest.get("newInstanceName") or "").strip()
if not name:
raise HTTPException(status_code=400,
detail="Set 'New instance name' and Save settings before creating.")
result = _create_instance(manifest, name, {})
plugin_admin.write_manifest_values(manifest, {"newInstanceName": ""})
manifest["newInstanceName"] = ""
return result
def delete_action(_body: dict[str, Any]) -> dict[str, Any]:
return _delete_instance(manifest, _active_name(manifest))
def check_action(_body: dict[str, Any]) -> dict[str, Any]:
return _check_codex(manifest)
def write_action(_body: dict[str, Any]) -> dict[str, Any]:
return {"ok": True, "path": str(_write_instance_config(manifest, _active_name(manifest)))}
return plugin_admin.build_admin_router(
manifest,
describe=describe,
apply_settings=apply_settings,
actions={
"launch": launch_action,
"createInstance": create_action,
"deleteInstance": delete_action,
"checkCodex": check_action,
"writeConfig": write_action,
},
initialize=lambda _body: initialize(manifest),
)
def create_router(manifest: dict[str, Any]) -> APIRouter:
"""Serve the instances REST API and the dedicated manager page (option A)."""
router = APIRouter()
prefix = str(manifest.get("routePrefix") or "/codex_cli").rstrip("/")
@router.get(f"{prefix}/instances")
def list_instances() -> dict[str, Any]:
return _list_instances(manifest)
@router.post(f"{prefix}/instances")
def create_instance(body: dict[str, Any] = Body(default_factory=dict)) -> dict[str, Any]:
return _create_instance(manifest, str(body.get("name") or ""), body)
@router.put(f"{prefix}/instances/{{name}}")
def update_instance(name: str, body: dict[str, Any] = Body(default_factory=dict)) -> dict[str, Any]:
return _update_instance(manifest, name, body)
@router.delete(f"{prefix}/instances/{{name}}")
def delete_instance(name: str) -> dict[str, Any]:
return _delete_instance(manifest, name)
@router.post(f"{prefix}/instances/{{name}}/launch")
def launch_instance(name: str) -> dict[str, Any]:
return _launch_instance(manifest, name)
@router.post(f"{prefix}/instances/{{name}}/install")
def install_instance(name: str) -> dict[str, Any]:
_safe_name(name)
return _ensure_installed(manifest)
@router.get(f"{prefix}/manage", response_class=HTMLResponse)
def manage_page() -> HTMLResponse:
return HTMLResponse(_MANAGER_HTML)
@router.post(f"{prefix}/v1/{{name}}/responses")
async def adapter_responses(name: str, request: Request) -> Any:
safe = _safe_name(name)
try:
body = await request.json()
except Exception as error: # noqa: BLE001
raise HTTPException(status_code=400, detail=f"invalid JSON body: {error}") from error
result = await _adapter_complete(manifest, safe, body if isinstance(body, dict) else {})
if body.get("stream") if isinstance(body, dict) else False:
return StreamingResponse(_responses_sse(result), media_type="text/event-stream")
return JSONResponse(result)
@router.get(f"{prefix}/v1/{{name}}/models")
async def adapter_models(name: str) -> Any:
cfg = _instance_config(manifest, _safe_name(name))
upstream = (cfg.get("baseUrl") or "").rstrip("/")
if upstream: