mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
* feat(hooks): record Codex hook trust on sync with --trust Codex runs a user-level hook only after its trusted_hash is stored in that home's config.toml, keyed by the hook's position in hooks.json. Only the TUI's /hooks review writes it, so every hook Skillshare adds or moves starts untrusted and codex exec skips it without a word. `hooks sync --trust` (global mode, opt-in) asks each Codex home's `codex app-server` for the current hash of the hooks Skillshare owns and writes trusted_hash through config/batchWrite, the same calls /hooks makes, so the hash is always the one Codex computes. It changes nothing else in config.toml: disabled hooks stay disabled and are reported. Trust it wrote is remembered in the hooks state directory, so when a hook moves or is removed the next --trust sync clears the old position, unless that trust has changed since. Without codex on PATH the hook files are still written and the command fails saying trust was not recorded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(hooks): scope Codex trust to config owner Scope trust selection and saved hashes to the active config owner so a global config cannot trust or reconcile another config’s hooks. Recheck hooks.json after hooks/list to avoid trusting a handler from a stale position, and only report trusted or cleared actions after config/batchWrite succeeds. Keep v1 ownerless hashes cleanup-only so upgraded installs clear stale trust after hook removal without trusting foreign hooks. * fix(hooks): retain parked Codex trust receipts Locate hooks using all records for their canonical file before selecting the active config owner, so identical hooks remain identifiable across shared and symlinked homes. Keep cleanup receipts for parked registrations whose native group still matches, including when duplicate counts make locate ambiguous, while clearing receipts for removed hooks. Add regressions for identical hooks across config owners, symlink aliases, parked-home restoration, ambiguous duplicates, and stale receipt cleanup. * fix(hooks): coalesce symlinked Codex trust homes Canonicalize current-owner and legacy trust receipts so symlink spellings of one hooks.json are processed once. Remove the redundant parked-position branch because the hash-matching fallback below covers it. Add regression coverage for current and legacy receipts. * fix(hooks): coalesce removed Codex hook homes Resolve existing home directories when hook files have been removed so trust receipts for symlink aliases reconcile once. Correct canonical key expectations and exercise coalescing without unsupported ledger migration. * fix(hooks): read reconciled trust fixture into fresh state JSON decoding retains existing map entries, so reusing the seeded receipt map makes the alias appear to survive reconciliation. Decode the persisted state into a new value to verify its actual contents. * feat(hooks): confirm Codex trust before recording it and drop the receipts file `hooks sync --trust` recorded trust for every owned hook without showing what it was trusting, and tracked its own writes in codex-trust.json so it could clear them later. Codex's review exists so that a person sees a command before it runs, and the receipts file was the source of most of the edge cases found in review. Trust is now two steps. A preview asks Codex which owned hooks are new or changed and returns them with their commands and a revision; the write takes that revision and is refused when the hooks changed since. The CLI lists the hooks and asks once, `--yes` skips the question, and without a terminal nothing is trusted unless `--yes` is given. The dashboard gets the same two steps as API routes. Nothing is cleared any more: a leftover entry only matches a hook with the same event, matcher and handler at that position, which is the hook the user already approved. That removes codex-trust.json. The app-server is started without CODEX_HOME for the default home. Codex resolves the symlinks of CODEX_HOME but not of ~/.codex, so a symlinked default home got a trust key the user's own Codex never looks up. A home whose write fails no longer stops the other homes, and the error names which were recorded. A preview releases the hooks operation lock before it waits on Codex, so a slow Codex does not fail other hooks operations. Refs #828 * feat(ui): trust Codex hooks from the Hooks page The dashboard could sync Codex hooks but left them untrusted, so Codex skipped them until the user ran the CLI or approved each one in Codex. The Sync box now offers "Trust Codex hooks" in the global scope when a hook is bound to a Codex target. The dialog shows each hook that needs trust with its full command and records trust for exactly that list; a change since the list was shown is refused. The button is hidden while changes are pending, because trust covers the hooks on disk and the next sync would invalidate it. Refs #828 * test(ui): cover the Codex trust dialog's refused, empty and disabled states Only the happy path was tested, so a regression in the states where the dialog must not offer a write would have passed. The docs sentence on several Codex homes now says what is isolated: a failed write, not a home that cannot be listed. Refs #828 * refactor(hooks): split the trust prompt and output rendering out of the handlers hooks_handlers.go had grown past 500 lines and mixed orchestration with the confirmation prompt and every print function, which the CLI layering rule asks to keep apart. The code is moved unchanged: the prompt goes to hooks_prompt.go and the printing to hooks_render.go. * fix(hooks): leave out a Codex home that cannot be listed instead of stopping With several Codex homes, one home Codex could not list aborted the whole trust run, so a broken account home kept every other home untrusted. A home that fails to list is now reported and left out, and the other homes are previewed and trusted as usual. The CLI warns before the question and exits with an error that names the home; the dashboard dialog shows the same note. When no home can be listed the preview still fails. Codex answers a home it cannot load, such as one with an invalid config.toml, with a successful reply that has no hooks and the reason in `errors`. That was read as a home without hooks and passed silently. It is now a failed listing that carries Codex's own message. Refs #828 * fix(hooks): check the reviewed Codex hooks per home when recording trust The revision was one digest over every home's hooks. When a home was listed in the preview but failed to list again at the write, its hooks dropped out of the digest, so the write was refused as stale: the homes the user had just reviewed stayed untrusted and the real listing error was hidden behind "changed since they were listed". The revision now has one part per home. A home is refused only when its own hooks changed; a home that cannot be listed any more is reported and the reviewed homes are still trusted. Refs #828 * chore: release as 0.30.10 Keep the next release on the patch version the maintainer asked for, instead of the 0.31.0 that Release Please derives from the feat commit. Release-As: 0.30.10 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Willie <egg358358@gmail.com>
527 lines
16 KiB
Go
527 lines
16 KiB
Go
package hooks
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unicode"
|
|
)
|
|
|
|
// CodexTrust is one Codex hook Skillshare owns, as sync --trust sees it.
|
|
type CodexTrust struct {
|
|
Target string `json:"target"`
|
|
Entry string `json:"entry,omitempty"`
|
|
Key string `json:"key"`
|
|
// Command is what the hook runs, shown for review before trust is recorded.
|
|
Command string `json:"command,omitempty"`
|
|
// Action is needed (not trusted yet, or changed since it was), trusted (recorded
|
|
// now) or unchanged (already trusted).
|
|
Action string `json:"action"`
|
|
// Disabled reports a hook switched off in Codex, which sync --trust leaves off.
|
|
Disabled bool `json:"disabled,omitempty"`
|
|
}
|
|
|
|
// CodexTrustPlan is what sync --trust looked at. Revision names the hooks that need
|
|
// trust and their hashes, one part per home, so trust is recorded only for what was
|
|
// shown and a home that fails later does not hold back the homes that were reviewed.
|
|
type CodexTrustPlan struct {
|
|
Hooks []CodexTrust `json:"hooks"`
|
|
Revision string `json:"revision"`
|
|
// Failed are the homes Codex could not list. Their hooks are not in Hooks, so
|
|
// they are never trusted; the other homes go on without them.
|
|
Failed []CodexTrustFailure `json:"failed,omitempty"`
|
|
}
|
|
|
|
// CodexTrustFailure is one Codex home that could not be listed, and why.
|
|
type CodexTrustFailure struct {
|
|
Target string `json:"target"`
|
|
Error string `json:"error"`
|
|
}
|
|
|
|
// Err reports the homes Codex could not list, or nil.
|
|
func (p *CodexTrustPlan) Err() error {
|
|
var errs []error
|
|
for _, f := range p.Failed {
|
|
errs = append(errs, fmt.Errorf("%s: %s", f.Target, f.Error))
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
// Needed are the hooks that would be newly trusted.
|
|
func (p *CodexTrustPlan) Needed() []CodexTrust {
|
|
var out []CodexTrust
|
|
for _, h := range p.Hooks {
|
|
if h.Action == "needed" {
|
|
out = append(out, h)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// CodexHook is the part of a Codex app-server hooks/list entry trust needs.
|
|
type CodexHook struct {
|
|
Key string `json:"key"`
|
|
SourcePath string `json:"sourcePath"`
|
|
Enabled bool `json:"enabled"`
|
|
CurrentHash string `json:"currentHash"`
|
|
TrustStatus string `json:"trustStatus"`
|
|
}
|
|
|
|
// CodexAppServer is a running `codex app-server` for one Codex home. Codex computes
|
|
// each hook's hash and writes config.toml itself, exactly as its /hooks review does.
|
|
type CodexAppServer interface {
|
|
ListHooks() ([]CodexHook, error)
|
|
// SetTrust writes hooks.state.<key>.trusted_hash for each key.
|
|
SetTrust(hashes map[string]string) error
|
|
Close() error
|
|
}
|
|
|
|
// codexHome is one physical hooks.json: every record written to it, and the active
|
|
// config's own among them.
|
|
type codexHome struct {
|
|
target, path string
|
|
records, owned map[string]record
|
|
}
|
|
|
|
// PreviewCodexTrust lists the Codex hooks Skillshare owns in each global Codex home
|
|
// and which of them need trust. It writes nothing and never runs a hook.
|
|
func (s *Service) PreviewCodexTrust() (*CodexTrustPlan, error) { return s.codexTrust("", false) }
|
|
|
|
// TrustCodex records Codex trust for the hooks a preview with this revision listed
|
|
// as needed. Only trusted_hash changes; enabled and the rest of config.toml stay as
|
|
// they are, and trust recorded earlier for a hook that moved or left stays too: it
|
|
// matches only a hook with the same event, matcher and handler at that position.
|
|
func (s *Service) TrustCodex(revision string) (*CodexTrustPlan, error) {
|
|
return s.codexTrust(revision, true)
|
|
}
|
|
|
|
func (s *Service) codexTrust(revision string, apply bool) (*CodexTrustPlan, error) {
|
|
if s.ProjectRoot != "" {
|
|
return nil, fmt.Errorf("--trust records trust in global Codex homes only; run it with -g")
|
|
}
|
|
lock, err := s.lock()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// A preview lets go before it asks Codex, which can take a while: a hooks.json that
|
|
// changes meanwhile fails the listing or the revision, so nothing is trusted unseen.
|
|
state, _, err := s.loadLedger()
|
|
if !apply || err != nil {
|
|
lock.Unlock()
|
|
} else {
|
|
defer lock.Unlock()
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
owner, err := filepath.Abs(s.ConfigPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("resolve hooks config owner: %w", err)
|
|
}
|
|
// Two targets that name one hooks.json, by a symlink or not, share one Codex run.
|
|
homes := map[string]*codexHome{}
|
|
for key, r := range state.Records {
|
|
if r.Root != "" || s.agentOf(r.Target) != "codex" {
|
|
continue
|
|
}
|
|
file := canonicalCodexHooksPath(r.Path)
|
|
h := homes[file]
|
|
if h == nil {
|
|
h = &codexHome{records: map[string]record{}, owned: map[string]record{}}
|
|
homes[file] = h
|
|
}
|
|
h.records[key] = r
|
|
if r.Owner != owner {
|
|
continue
|
|
}
|
|
sc, _ := s.forTarget(r.Target)
|
|
path, err := sc.nativePath("codex")
|
|
if err != nil || canonicalCodexHooksPath(path) != file {
|
|
continue // The record's home moved or is missing; there is nothing to trust there.
|
|
}
|
|
if h.target == "" || r.Target < h.target {
|
|
h.target, h.path = r.Target, path
|
|
}
|
|
h.owned[key] = r
|
|
}
|
|
plan := &CodexTrustPlan{Hooks: []CodexTrust{}}
|
|
type write struct {
|
|
target string
|
|
server CodexAppServer
|
|
edits map[string]string
|
|
review string // names this home's needed hooks and hashes; empty when none
|
|
}
|
|
var writes []write
|
|
var servers []CodexAppServer
|
|
defer func() {
|
|
for _, server := range servers {
|
|
server.Close()
|
|
}
|
|
}()
|
|
var reviews []string
|
|
listed := 0
|
|
for _, file := range sortedKeys(homes) {
|
|
h := homes[file]
|
|
if info, err := os.Stat(filepath.Dir(h.path)); len(h.owned) == 0 || err != nil || !info.IsDir() {
|
|
continue // A missing account home is skipped, as sync skips it.
|
|
}
|
|
server, hooks, edits, err := s.listCodexHome(h)
|
|
if server != nil {
|
|
servers = append(servers, server)
|
|
}
|
|
if err != nil {
|
|
// One home Codex cannot list does not stop the others.
|
|
plan.Failed = append(plan.Failed, CodexTrustFailure{Target: h.target, Error: err.Error()})
|
|
continue
|
|
}
|
|
listed++
|
|
review := ""
|
|
if len(edits) > 0 {
|
|
var needed []string
|
|
for key, hash := range edits {
|
|
needed = append(needed, key+"\x00"+hash)
|
|
}
|
|
slices.Sort(needed)
|
|
review = digest([]byte(strings.Join(needed, "\n")))
|
|
reviews = append(reviews, review)
|
|
}
|
|
writes = append(writes, write{h.target, server, edits, review})
|
|
plan.Hooks = append(plan.Hooks, hooks...)
|
|
}
|
|
if listed == 0 && len(plan.Failed) > 0 {
|
|
return plan, plan.Err()
|
|
}
|
|
slices.Sort(reviews)
|
|
plan.Revision = strings.Join(reviews, ".")
|
|
if !apply {
|
|
return plan, nil
|
|
}
|
|
// Each home is checked on its own: a home that cannot be listed now is reported
|
|
// below, and it does not make the homes that were reviewed look changed.
|
|
reviewed := strings.Split(revision, ".")
|
|
for _, w := range writes {
|
|
if w.review != "" && !slices.Contains(reviewed, w.review) {
|
|
return plan, fmt.Errorf("Codex hooks changed since they were listed: %w", ErrStaleRevision)
|
|
}
|
|
}
|
|
// One home that fails does not stop the others, and the error says which is which.
|
|
var done []string
|
|
var failed []error
|
|
if err := plan.Err(); err != nil {
|
|
failed = append(failed, err)
|
|
}
|
|
for _, w := range writes {
|
|
if len(w.edits) == 0 {
|
|
continue
|
|
}
|
|
if err := w.server.SetTrust(w.edits); err != nil {
|
|
failed = append(failed, fmt.Errorf("%s: %w", w.target, err))
|
|
continue
|
|
}
|
|
done = append(done, w.target)
|
|
for i, h := range plan.Hooks {
|
|
if _, ok := w.edits[h.Key]; ok {
|
|
plan.Hooks[i].Action = "trusted"
|
|
}
|
|
}
|
|
}
|
|
if len(failed) > 0 && len(done) > 0 {
|
|
return plan, fmt.Errorf("Codex trust was recorded for %s, but not for every home: %w", strings.Join(done, ", "), errors.Join(failed...))
|
|
}
|
|
return plan, errors.Join(failed...)
|
|
}
|
|
|
|
// canonicalCodexHooksPath resolves the home's symlinks even when hooks.json is absent.
|
|
func canonicalCodexHooksPath(path string) string {
|
|
if resolved, err := filepath.EvalSymlinks(path); err == nil {
|
|
return resolved
|
|
}
|
|
return filepath.Join(canonicalPath(filepath.Dir(path)), filepath.Base(path))
|
|
}
|
|
|
|
// listCodexHome asks Codex about one hooks.json. It locates groups against every
|
|
// record for the file, then reports only the active owner's; edits are the hashes
|
|
// that would make the needed ones trusted. The server is returned open for the write.
|
|
func (s *Service) listCodexHome(h *codexHome) (CodexAppServer, []CodexTrust, map[string]string, error) {
|
|
data, exists, _, err := safeRead(h.path)
|
|
if err != nil || !exists {
|
|
return nil, nil, nil, err
|
|
}
|
|
doc, err := parseNative("codex", data)
|
|
if err != nil {
|
|
return nil, nil, nil, err
|
|
}
|
|
type group struct {
|
|
entry string
|
|
item any
|
|
}
|
|
groups := map[string]group{}
|
|
for key, index := range locate(doc, h.records) {
|
|
if r, ok := h.owned[key]; ok {
|
|
groups[codexEventKey(r.Event)+":"+strconv.Itoa(index)] = group{r.Entry, doc.events[r.Event][index]}
|
|
}
|
|
}
|
|
if len(groups) == 0 {
|
|
return nil, nil, nil, nil
|
|
}
|
|
start := s.CodexAppServer
|
|
if start == nil {
|
|
start = startCodexAppServer
|
|
}
|
|
dir := filepath.Dir(h.path)
|
|
server, err := start(dir, s.codexDefaultHome(dir))
|
|
if err != nil {
|
|
return nil, nil, nil, err
|
|
}
|
|
listed, err := server.ListHooks()
|
|
if err != nil {
|
|
return server, nil, nil, err
|
|
}
|
|
current, currentExists, _, err := safeRead(h.path)
|
|
if err != nil {
|
|
return server, nil, nil, err
|
|
}
|
|
if !currentExists || !bytes.Equal(data, current) {
|
|
return server, nil, nil, fmt.Errorf("%s changed while Codex hooks were being listed; run hooks sync --trust again", h.path)
|
|
}
|
|
var results []CodexTrust
|
|
edits := map[string]string{}
|
|
for _, hook := range listed {
|
|
if !samePath(hook.SourcePath, h.path) {
|
|
continue
|
|
}
|
|
position, handler := codexPosition(hook.Key)
|
|
g, ok := groups[position]
|
|
if !ok {
|
|
continue
|
|
}
|
|
result := CodexTrust{Target: h.target, Entry: g.entry, Key: hook.Key, Command: codexHandlerCommand(g.item, handler), Action: "unchanged", Disabled: !hook.Enabled}
|
|
switch hook.TrustStatus {
|
|
case "untrusted", "modified":
|
|
result.Action, edits[hook.Key] = "needed", hook.CurrentHash
|
|
case "trusted":
|
|
default:
|
|
continue // Managed hooks are trusted by policy, not config.toml.
|
|
}
|
|
results = append(results, result)
|
|
}
|
|
return server, results, edits, nil
|
|
}
|
|
|
|
// codexDefaultHome reports whether the user's Codex finds dir as ~/.codex rather than
|
|
// through CODEX_HOME. Codex resolves CODEX_HOME's symlinks but not ~/.codex's, and the
|
|
// trust key holds that path, so the app-server must find the home the same way.
|
|
func (s *Service) codexDefaultHome(dir string) bool {
|
|
if env := s.ConfigDirs["codex"]; env != "" && samePath(env, dir) {
|
|
return false
|
|
}
|
|
home, err := os.UserHomeDir()
|
|
return err == nil && filepath.Clean(dir) == filepath.Join(home, ".codex")
|
|
}
|
|
|
|
// codexHandlerCommand is the command of one handler of a hooks.json group.
|
|
func codexHandlerCommand(item any, handler int) string {
|
|
group, _ := item.(map[string]any)
|
|
handlers, _ := group["hooks"].([]any)
|
|
if handler < 0 || handler >= len(handlers) {
|
|
return ""
|
|
}
|
|
h, _ := handlers[handler].(map[string]any)
|
|
command, _ := h["command"].(string)
|
|
return command
|
|
}
|
|
|
|
// codexEventKey is Codex's snake_case event label for a hooks.json event name.
|
|
func codexEventKey(event string) string {
|
|
var b strings.Builder
|
|
for i, r := range event {
|
|
if unicode.IsUpper(r) {
|
|
if i > 0 {
|
|
b.WriteByte('_')
|
|
}
|
|
r = unicode.ToLower(r)
|
|
}
|
|
b.WriteRune(r)
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// codexPosition splits a hook key "<source>:<event>:<group>:<handler>" into
|
|
// "<event>:<group>" and the handler index; every handler of a group Skillshare owns
|
|
// is its own.
|
|
func codexPosition(key string) (string, int) {
|
|
parts := strings.Split(key, ":")
|
|
if len(parts) < 4 {
|
|
return "", -1
|
|
}
|
|
handler, err := strconv.Atoi(parts[len(parts)-1])
|
|
if err != nil {
|
|
return "", -1
|
|
}
|
|
return parts[len(parts)-3] + ":" + parts[len(parts)-2], handler
|
|
}
|
|
|
|
// codexRPCTimeout bounds each app-server request.
|
|
const codexRPCTimeout = 30 * time.Second
|
|
|
|
type codexProcess struct {
|
|
cmd *exec.Cmd
|
|
stdin io.WriteCloser
|
|
lines chan []byte
|
|
next int
|
|
}
|
|
|
|
// startCodexAppServer runs `codex app-server` for one Codex home: with CODEX_HOME set
|
|
// to it, or for the default home with CODEX_HOME unset so Codex finds ~/.codex itself.
|
|
func startCodexAppServer(home string, defaultHome bool) (CodexAppServer, error) {
|
|
bin, err := exec.LookPath("codex")
|
|
if err != nil {
|
|
return nil, errors.New("codex is not on PATH")
|
|
}
|
|
cmd := exec.Command(bin, "app-server")
|
|
cmd.Dir = home
|
|
cmd.Env = slices.DeleteFunc(os.Environ(), func(v string) bool { return strings.HasPrefix(v, "CODEX_HOME=") })
|
|
if !defaultHome {
|
|
cmd.Env = append(cmd.Env, "CODEX_HOME="+home)
|
|
}
|
|
stdin, err := cmd.StdinPipe()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
stdout, err := cmd.StdoutPipe()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := cmd.Start(); err != nil {
|
|
return nil, err
|
|
}
|
|
p := &codexProcess{cmd: cmd, stdin: stdin, lines: make(chan []byte, 16)}
|
|
go func() {
|
|
scanner := bufio.NewScanner(stdout)
|
|
scanner.Buffer(make([]byte, 0, 64*1024), 64*1024*1024)
|
|
for scanner.Scan() {
|
|
p.lines <- append([]byte(nil), scanner.Bytes()...)
|
|
}
|
|
close(p.lines)
|
|
}()
|
|
if _, err := p.call("initialize", map[string]any{"clientInfo": map[string]string{"name": "skillshare", "version": "0"}}); err != nil {
|
|
p.Close()
|
|
return nil, err
|
|
}
|
|
if err := p.send(map[string]any{"jsonrpc": "2.0", "method": "initialized"}); err != nil {
|
|
p.Close()
|
|
return nil, err
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
func (p *codexProcess) send(msg any) error {
|
|
data, err := json.Marshal(msg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = p.stdin.Write(append(data, '\n'))
|
|
return err
|
|
}
|
|
|
|
func (p *codexProcess) call(method string, params any) (json.RawMessage, error) {
|
|
p.next++
|
|
if err := p.send(map[string]any{"jsonrpc": "2.0", "id": p.next, "method": method, "params": params}); err != nil {
|
|
return nil, fmt.Errorf("codex app-server %s: %w", method, err)
|
|
}
|
|
timeout := time.After(codexRPCTimeout)
|
|
for {
|
|
select {
|
|
case line, ok := <-p.lines:
|
|
if !ok {
|
|
return nil, fmt.Errorf("codex app-server exited during %s", method)
|
|
}
|
|
var msg struct {
|
|
ID *int `json:"id"`
|
|
Method string `json:"method"`
|
|
Result json.RawMessage `json:"result"`
|
|
Error *struct {
|
|
Message string `json:"message"`
|
|
} `json:"error"`
|
|
}
|
|
if json.Unmarshal(line, &msg) != nil || msg.Method != "" || msg.ID == nil || *msg.ID != p.next {
|
|
continue // Notifications and server requests carry a method; responses never do.
|
|
}
|
|
if msg.Error != nil {
|
|
return nil, fmt.Errorf("codex app-server %s: %s", method, msg.Error.Message)
|
|
}
|
|
return msg.Result, nil
|
|
case <-timeout:
|
|
return nil, fmt.Errorf("codex app-server did not answer %s within %s", method, codexRPCTimeout)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (p *codexProcess) ListHooks() ([]CodexHook, error) {
|
|
raw, err := p.call("hooks/list", map[string]any{"cwds": []string{p.cmd.Dir}})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return parseCodexHooksList(raw)
|
|
}
|
|
|
|
// parseCodexHooksList reads a hooks/list result. Codex answers a home it cannot load,
|
|
// such as one with an invalid config.toml, with no hooks and the reason in errors;
|
|
// that is a failed listing, not a home without hooks.
|
|
func parseCodexHooksList(raw json.RawMessage) ([]CodexHook, error) {
|
|
var res struct {
|
|
Data []struct {
|
|
Hooks []CodexHook `json:"hooks"`
|
|
Errors []struct {
|
|
Message string `json:"message"`
|
|
} `json:"errors"`
|
|
} `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(raw, &res); err != nil {
|
|
return nil, fmt.Errorf("codex app-server hooks/list: %w", err)
|
|
}
|
|
var out []CodexHook
|
|
var problems []string
|
|
for _, entry := range res.Data {
|
|
out = append(out, entry.Hooks...)
|
|
for _, e := range entry.Errors {
|
|
problems = append(problems, e.Message)
|
|
}
|
|
}
|
|
if len(out) == 0 && len(problems) > 0 {
|
|
return nil, fmt.Errorf("Codex could not load its hooks: %s", strings.Join(problems, "; "))
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (p *codexProcess) SetTrust(hashes map[string]string) error {
|
|
edits := []map[string]any{}
|
|
for _, key := range sortedKeys(hashes) {
|
|
escaped := strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(key)
|
|
edits = append(edits, map[string]any{"keyPath": `hooks.state."` + escaped + `".trusted_hash`, "value": hashes[key], "mergeStrategy": "replace"})
|
|
}
|
|
_, err := p.call("config/batchWrite", map[string]any{"edits": edits})
|
|
return err
|
|
}
|
|
|
|
func (p *codexProcess) Close() error {
|
|
p.stdin.Close()
|
|
_ = p.cmd.Process.Kill()
|
|
go func() {
|
|
for range p.lines { // Unblock the reader so it sees EOF and exits.
|
|
}
|
|
}()
|
|
_ = p.cmd.Wait()
|
|
return nil
|
|
}
|