蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在本机记录并恢复命令行会话

PYTHONWindows x64、OpenCode 1.19.5、CPython 3.12。cli_sessions.py
cli_sessions.py124 行
"""Local OpenCode V1 CLI sessions, attachments and export/import."""
from hashlib import file_digest
from http.server import ThreadingHTTPServer
from pathlib import Path
from tempfile import TemporaryDirectory
from threading import Thread
import json,os,subprocess,sys,socket
from contextlib import contextmanager
from first_use import Model, request
from time import monotonic,sleep


@contextmanager
def server(exe,root,env):
    with socket.socket() as reserve:
        reserve.bind(("127.0.0.1",0))
        port=reserve.getsockname()[1]
    origin=f"http://127.0.0.1:{port}"
    proc=subprocess.Popen([str(exe),"serve","--hostname","127.0.0.1","--port",str(port),"--pure"],
        cwd=root,env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    try:
        until=monotonic()+10
        while monotonic()<until and proc.poll() is None:
            try:
                request(origin,"/global/health")
                break
            except OSError:
                sleep(.08)
        else:
            raise RuntimeError("private OpenCode server failed to start")
        if proc.poll() is not None:
            raise RuntimeError("local server process exited")
        yield origin
    finally:
        if proc.poll() is None:
            proc.terminate()
        proc.communicate(timeout=10)


def profile(base):
    keys=("SystemRoot","WINDIR","PATH","TEMP","TMP","COMSPEC")
    env={k:os.environ[k] for k in keys if k in os.environ}
    env.update({f"XDG_{n}_HOME":str(base/n.lower()) for n in ("CONFIG","DATA","STATE","CACHE")})
    env.update(OPENCODE_DISABLE_AUTOUPDATE="1",OPENCODE_DISABLE_DEFAULT_PLUGINS="1",
      OPENCODE_DISABLE_MODELS_FETCH="1",NO_COLOR="1",HTTPS_PROXY="http://127.0.0.1:1",
      HTTP_PROXY="http://127.0.0.1:1",NO_PROXY="127.0.0.1,localhost")
    return env


def check(exe):
    with TemporaryDirectory(prefix="mbsky-cli-rehearsal-") as tmp, ThreadingHTTPServer(("127.0.0.1",0),Model) as mock:
        base=Path(tmp)
        root=base/"work"
        root.mkdir()
        local=root/"signal.txt"
        local.write_bytes(b"beacon-checkpoint-93\n")
        config={"model":"openai/stock-local","small_model":"openai/stock-local","share":"disabled",
          "enabled_providers":["openai"],"permission":{"*":"deny"},
          "provider":{"openai":{"npm":"@ai-sdk/openai-compatible","name":"Beacon replay",
            "options":{"baseURL":f"http://127.0.0.1:{mock.server_port}/v1","apiKey":"training-token"},
            "models":{"stock-local":{"name":"Beacon replay","tool_call":True,"limit":{"context":32768,"output":4096}}}}}}
        (root/"opencode.json").write_bytes(json.dumps(config).encode())
        mock.root=root
        mock.observations=[]
        worker=Thread(target=mock.serve_forever,daemon=True)
        worker.start()
        env=profile(base)
        def invoke(*args, opts=None):
            return subprocess.run([str(exe),*args],cwd=root,env=env if opts is None else opts,
                capture_output=True,encoding="utf-8",errors="replace",timeout=22,check=True).stdout
        def events(*args):
            result=subprocess.run([str(exe),"run","--format","json","--model","openai/stock-local",*args],
                cwd=root,env=env,capture_output=True,encoding="utf8",timeout=25,check=True)
            raw=result.stdout
            items=[json.loads(row) for row in raw.splitlines() if row.startswith("{")]
            assert not any(x["type"]=="error" for x in items),raw
            text=next((row for row in items if row["type"]=="text"),None)
            assert text is not None,(args,raw,result.stderr)
            assert text["part"]["text"]=="Inventory training session",text
            return text["sessionID"]
        try:
            first=events("--title","Beacon discovery","--file",str(local),"--","Locate the beacon.")
            same=events("--session",first,"Continue the checklist.")
            fork=events("--session",first,"--fork","Check a separate branch.")
            assert same==first and fork!=first,(first,same,fork)
            listing=json.loads(invoke("session","list","--format","json","-n","10"))
            ids={s["id"] for s in listing}
            assert first in ids and fork in ids,listing
            exported=json.loads(invoke("export",first))
            assert exported["info"]["id"]==first
            saved=base/"fixture-export.json"
            saved.write_text(json.dumps(exported),encoding="utf-8")
            independent=profile(base/"imported-profile")
            new_profile=invoke("import",str(saved),opts=independent)
            recovered=json.loads(invoke("session","list","--format","json",opts=independent))
            assert any(x["id"]==first for x in recovered),(recovered,new_profile)
            with server(exe,root,env) as origin:
                stored=request(origin,f"/session/{first}")
                assert stored["id"]==first,stored
                health=request(origin,"/global/health")
                assert health=={"healthy":True,"version":"1.19.5"},health
                result=subprocess.run([str(exe),"run","--format","json","--model","openai/stock-local",
                    "--attach",origin,"--dir",str(root),"--session",first,"Check via the existing server."],
                    cwd=root,env=env,capture_output=True,encoding="utf8",timeout=25,check=True)
                attached=bool(result.stdout.strip())
                messages=request(origin,f"/session/{first}/message")
                text=json.dumps(messages)
                assert "Locate the beacon." in text
                attached_persisted="Check via the existing server." in text
                assert local.as_uri() in text or "/signal.txt" in text,text[-1000:]
            records=dict(separate_fork=True,continuation=True,attached_stream_events=attached,attached_prompt_persisted=attached_persisted,session_listing=len(listing),
                exported_messages=len(exported["messages"]),imported_id_equal=True,
                attachment_in_session=True,health=health)
        finally:
            mock.shutdown()
            worker.join()
    with Path(exe).open("rb") as f:
        signature=file_digest(f,"sha256").hexdigest()
    return dict(version="1.19.5",binary_sha256=signature,observations=records,
                model_requests=len(mock.observations), cloud_requests=0)

if __name__=="__main__":
    print(json.dumps(check(Path(sys.argv[1]).resolve()),ensure_ascii=False,indent=2))
本例需在 Windows x64、OpenCode 1.19.5、CPython 3.12。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、OpenCode 1.19.5、CPython 3.12。

入口文件:projects/opencode-cli-sessions/cli_sessions.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 cli_sessions.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、OpenCode 1.19.5、CPython 3.12。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:OpenCode

课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a236.zip

下载课程关联工程包:OpenCode

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a237.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习