Theme / v2.1.15

Chat On Steroids

把 ChatGPT 對話變成會寫程式、會派工的本地開發環境

實戰範例

長指令與開發伺服器

用 exec_command 起長駐的開發伺服器、用 write_stdin 輪詢就緒並回答互動提問。認識 session_id、空白 chars 輪詢與輸出預算。

長指令與開發伺服器

開發伺服器(Dev Server)是典型的長駐程序:一旦啟動就不會「跑完」。CoS 的處理方式不是等它,而是讓它回傳一個 session 交給後續輪詢;需要回答互動提問時,也走同一個管道。


情境

receipt-cli 有一個預覽伺服器 npm run dev,會起在 http://localhost:3000,讓你在瀏覽器裡看收據版面。第一次啟動時它會問一句 Create default config .receiptrc? (y/N);此外專案還有一支跑好幾分鐘的 npm run test:e2e。

目標

讓 ChatGPT 自己把伺服器跑起來、回答那個互動提問、等到就緒訊號、驗證一個端點,並且知道後續還有更長的指令要處理。

步驟:給 ChatGPT 的 prompt

Start the preview server with npm run dev.

It may ask an interactive question on first run; answer yes.
Wait until it prints the local URL, then verify the server by requesting
the /health endpoint from a second command.

Report the session id you used, the readiness line you saw, and the
/health response. Leave the server running when you're done.

預期的工具呼叫序列

1. exec_command(cmd: "npm run dev")
   → 長指令:回傳不透明的 session_id,例如 "9f3c..." 

2. write_stdin(session_id: "9f3c...", chars: "")
   → 空白 chars=輪詢:看到互動提問 "Create default config .receiptrc? (y/N)"

3. write_stdin(session_id: "9f3c...", chars: "y\n")
   → 非空寫入:把這次互動回應的輸出完整收攏

4. write_stdin(session_id: "9f3c...", chars: "")
   → "listening on http://localhost:3000"

5. exec_command(cmd: "curl -s http://localhost:3000/health")
   → {"status":"ok"}

6. write_stdin(session_id: "9f3c...", chars: "")
   → 之後想再看日誌,就再輪詢一次

這裡發生了什麼

  • 長指令回傳 session_id:exec_command 跑得比等待視窗久時,會回傳一個不透明的 session_id,由 write_stdin 續接。一個指令、一個持久 session。
  • 空白 chars 是輪詢,不是另一個獨立的狀態查詢工具。空輪詢會在程序一有輸出時就回來,而不是硬等滿整個等待視窗;之後才到的輸出會留在緩衝區,等下一次輪詢。
  • 非空的寫入維持收集視窗行為,讓一次互動回應被完整收攏——第 3 步就是這個用法。
  • 兩步都可帶可選的等待時間與輸出預算,控制每次輪詢等多久、最多收多少。
  • 驗證另外開指令:同一台伺服器的健康檢查是新的 exec_command;新指令不會繼承舊 session 的變數與工作目錄。要在一段腳本內延續狀態,用同一次呼叫的 cmds(最多 20 條,共用一個 shell session)。
  • Windows 的 shell 是 PowerShell/cmd:curl 這類指令若行為不如預期,改用 curl.exe 或 Invoke-RestMethod。

驗收方式

  • ChatGPT 能報出它用的 session_id、看到的就緒行,以及 /health 的實際回應。
  • 伺服器在你收工前仍在跑,你可以在瀏覽器手動打開 http://localhost:3000 覆核。

注意事項

  • 收工要收尾:長駐程序會跟著那個 shell session 活著。你可以對同一個 session_id 寫入中斷(Ctrl+C 對應的字元)把它收掉,或先記著它、稍後自己處理;重點是不要忘記它還在跑。
  • 長指令若只是「很久但會結束」(例如 npm run test:e2e),一樣是 exec_command → write_stdin 輪詢;看到輸出再判斷結果,不要只憑「沒有回應」推測它失敗。
  • 持續輪詢也消耗對話與連接器呼叫;該等就等,但別把輪詢當心跳無腦打。
  • Provider 用量限制不可繞:拿長時間自動化去規避限制,會讓帳號承擔後果。

延伸閱讀:本地編碼迴圈、修一個失敗的測試。