Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(agent): steer running Antigravity (agy) turns via PreInvocation hooks (MUL-9862) (#11200)
Multica Eve8038b648d768
diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.goindex af9a121347..9627609a55 100644--- a/server/cmd/multica/main.go+++ b/server/cmd/multica/main.go@@ -122,6 +122,10 @@ func main() {agent.RunCursorHookRelay(os.Stdin, os.Stdout, os.Getenv)return}+ if len(os.Args) == 2 && os.Args[1] == agent.AntigravityHookHelperArg {+ agent.RunAntigravityHookRelay(os.Stdin, os.Stdout, os.Getenv)+ return+ }cli.CleanupStaleUpdateArtifacts()if err := rootCmd.Execute(); err != nil {if err != errSilent {diff --git a/server/internal/daemon/antigravity_supplement_gate_test.go b/server/internal/daemon/antigravity_supplement_gate_test.gonew file mode 100644index 0000000000..afea52f691--- /dev/null+++ b/server/internal/daemon/antigravity_supplement_gate_test.go@@ -0,0 +1,55 @@+package daemon++import (+ "os"+ "path/filepath"+ "runtime"+ "slices"+ "testing"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+ "github.com/multica-ai/multica/server/pkg/agent"+)++func TestAntigravitySupplementHookCommandGate(t *testing.T) {+ originalResolveSelfExecutable := resolveSelfExecutable+ t.Cleanup(func() { resolveSelfExecutable = originalResolveSelfExecutable })+ resolveSelfExecutable = func() (string, error) { return "/usr/local/bin/multica", nil }++ workdir := t.TempDir()+ command, ok := antigravitySupplementHookCommand(&execenv.Environment{WorkDir: workdir})+ if runtime.GOOS == "windows" {+ if ok {+ t.Fatal("antigravity steering offered on Windows")+ }+ return+ }+ if want := []string{"/usr/local/bin/multica", agent.AntigravityHookHelperArg}; !ok || !slices.Equal(command, want) {+ t.Fatalf("managed workdir: command=%q ok=%v, want %q", command, ok, want)+ }++ for name, env := range map[string]*execenv.Environment{+ "nil env": nil,+ "local directory": {WorkDir: "/Users/me/project", LocalDirectory: true},+ "local worktree": {WorkDir: "/Users/me/project-wt", LocalWorktree: &execenv.LocalWorktree{}},+ } {+ if _, ok := antigravitySupplementHookCommand(env); ok {+ t.Fatalf("%s: antigravity steering offered", name)+ }+ }++ // Skills share .agents/ and must not block steering; a hooks.json Multica+ // did not write must.+ if err := os.MkdirAll(filepath.Join(workdir, ".agents", "skills"), 0o755); err != nil {+ t.Fatal(err)+ }+ if _, ok := antigravitySupplementHookCommand(&execenv.Environment{WorkDir: workdir}); !ok {+ t.Fatal("steering refused for a workdir holding only skills under .agents")+ }+ if err := os.WriteFile(filepath.Join(workdir, ".agents", "hooks.json"), []byte(`{"user":{}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ if _, ok := antigravitySupplementHookCommand(&execenv.Environment{WorkDir: workdir}); ok {+ t.Fatal("steering offered for a workdir whose own hooks.json blocks the managed hooks")+ }+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 48e0ff949c..588bd2f929 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -291,23 +291,37 @@ type terminalReportSendFunc func(context.Context, terminalTaskReport, []time.Durtype executionEnvironmentCommand func() ([]string, error)// cursorSupplementHookCommand returns the hook relay a steerable Cursor run-// installs in .cursor/hooks.json. That file lands in the workdir, so steering-// is offered only for daemon-managed workdirs, never inside a user's own-// directory or worktree, and only when the workdir has no hooks.json of its-// own. Windows is excluded because Cursor runs hooks there through PowerShell,-// whose quoting the relay command is not verified against.+// installs in .cursor/hooks.json. Windows is excluded because Cursor runs hooks+// there through PowerShell, whose quoting the relay command is not verified+// against.func cursorSupplementHookCommand(env *execenv.Environment) ([]string, bool) {+ return workdirSupplementHookCommand(env, agent.CursorHooksInstallable, agent.CursorHookHelperArg)+}++// antigravitySupplementHookCommand returns the hook relay a steerable+// Antigravity run installs in .agents/hooks.json. Windows is excluded because+// agy runs hooks there through cmd /c, whose quoting the relay command is not+// verified against.+func antigravitySupplementHookCommand(env *execenv.Environment) ([]string, bool) {+ return workdirSupplementHookCommand(env, agent.AntigravityHooksInstallable, agent.AntigravityHookHelperArg)+}++// workdirSupplementHookCommand gates hook-based steering. The provider's hooks+// file lands in the workdir, so steering is offered only for daemon-managed+// workdirs, never inside a user's own directory or worktree, and only when the+// workdir has no hooks file of its own.+func workdirSupplementHookCommand(env *execenv.Environment, installable func(string) error, helperArg string) ([]string, bool) {if runtime.GOOS == "windows" || env == nil || env.LocalDirectory || env.LocalWorktree != nil {return nil, false}- if agent.CursorHooksInstallable(env.WorkDir) != nil {+ if installable(env.WorkDir) != nil {return nil, false}executable, err := resolveSelfExecutable()if err != nil {return nil, false}- return []string{executable, agent.CursorHookHelperArg}, true+ return []string{executable, helperArg}, true}func defaultExecutionEnvironmentCommand() ([]string, error) {@@ -9012,10 +9026,15 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif provider == "museapp" {taskCapabilities = append(taskCapabilities, protocol.DaemonCapabilityMuseAppProcessCleanupV1)}- var cursorHookCommand []string+ var supplementHookCommand []stringsupplementSupported := agent.SupportsTaskSupplement(provider, resolvedVersion) && (task.IssueID != "" || task.ChatSessionID != "")- if supplementSupported && provider == "cursor" {- cursorHookCommand, supplementSupported = cursorSupplementHookCommand(env)+ if supplementSupported {+ switch provider {+ case "cursor":+ supplementHookCommand, supplementSupported = cursorSupplementHookCommand(env)+ case "antigravity":+ supplementHookCommand, supplementSupported = antigravitySupplementHookCommand(env)+ }}if supplementSupported {taskCapabilities = append(taskCapabilities, protocol.DaemonCapabilityTaskSupplementV1)@@ -9353,7 +9372,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iexecOpts := agent.ExecOptions{SkillInvocation: skillInvocation,EnableTaskSupplement: taskSupplementNegotiated,- CursorHookCommand: cursorHookCommand,+ SupplementHookCommand: supplementHookCommand,Cwd: env.WorkDir,PiSkillPaths: env.PiSkillPaths,Model: model,diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex ce3dedda49..c9dfe07287 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -158,11 +158,12 @@ type ExecOptions struct {// through Claude Code's --settings flag. It currently carries restrictive// runtime-skill overrides only; other providers ignore it.ClaudeSettingsPath string- // CursorHookCommand is the argv of the multica hook relay (the daemon's own- // binary followed by CursorHookHelperArg). The cursor backend needs it, with- // EnableTaskSupplement, to accept additional messages; other providers- // ignore it.- CursorHookCommand []string+ // SupplementHookCommand is the argv of the provider's multica hook relay+ // (the daemon's own binary followed by CursorHookHelperArg or+ // AntigravityHookHelperArg). The cursor and antigravity backends need it,+ // with EnableTaskSupplement, to accept additional messages; other+ // providers ignore it.+ SupplementHookCommand []string// OnUsage optionally receives the backend's cumulative usage snapshot while// the run is still live, keyed exactly like Result.Usage so a mid-run flush// and the terminal report upsert the same (task, provider, model) rowsdiff --git a/server/pkg/agent/antigravity.go b/server/pkg/agent/antigravity.goindex 010506ca77..cebf0f9a99 100644--- a/server/pkg/agent/antigravity.go+++ b/server/pkg/agent/antigravity.go@@ -1,9 +1,13 @@package agentimport (+ "bufio"+ "bytes""context""encoding/json"+ "errors""fmt"+ "io""log/slog""maps""os"@@ -36,6 +40,10 @@ import (// emitted on stdout; we capture it by routing `--log-file` to a temp file and// scanning its glog-formatted lines for the `conversation=<uuid>` token that// printmode.go logs at message-send time.+//+// Print mode reads no input after the prompt, so steering a running turn goes+// through a PreInvocation workspace hook instead (see+// antigravitySupplementSession).type antigravityBackend struct {cfg Config}@@ -191,9 +199,52 @@ type antigravityStepSummary struct {}type antigravityTurn struct {- start *int- steps map[int]antigravityStepSummary- invalid bool+ start *int+ // injected holds the user_input steps that appeared while steering+ // guidance was in flight; checkTranscript is set until the transcript+ // shows which guidance they carried, and rescanTranscript until the next+ // check has read it from the start.+ injected map[int]bool+ checkTranscript bool+ rescanTranscript bool+ steps map[int]antigravityStepSummary+ invalid bool+}++// observeUserInput classifies a user_input step. The first one opens the turn;+// a later one is valid only while injected steering guidance awaits its step.+func (t *antigravityTurn) observeUserInput(index int, supplements *antigravitySupplementSession) {+ switch {+ case t.start == nil:+ t.start = &index+ case *t.start == index || t.injected[index]:+ case supplements.awaitingReceipt():+ if t.injected == nil {+ t.injected = make(map[int]bool)+ }+ t.injected[index] = true+ t.checkTranscript, t.rescanTranscript = true, true+ default:+ t.invalid = true+ }+}++// confirmInjected settles guidance whose marker the transcript shows in a+// USER_INPUT record. A step another hook injected carries no marker and+// settles nothing, so the guidance it displaced fails at the end of the turn+// and falls back.+func (t *antigravityTurn) confirmInjected(supplements *antigravitySupplementSession, transcript *antigravityTranscript, conversationID string) {+ if !t.checkTranscript {+ return+ }+ // agy can rewrite the transcript in place when it compacts, leaving the+ // remembered offset inside an unrelated line. A new step is rare, so read+ // the whole file once for it; later checks only read what was added.+ if t.rescanTranscript {+ transcript.offset, t.rescanTranscript = 0, false+ }+ transcript.scan(conversationID, supplements.inflightMarkers(), supplements.receipt)+ t.checkTranscript = supplements.awaitingReceipt()}func (t *antigravityTurn) settledResponse() int {@@ -402,10 +453,23 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex_ = os.Remove(logPath)return nil, fmt.Errorf("agy stdout pipe: %w", err)}++ var supplements *antigravitySupplementSession+ var supplementErr error+ if opts.EnableTaskSupplement {+ supplements, supplementErr = startAntigravitySupplementSession(runCtx, opts.Cwd, opts.SupplementHookCommand, b.cfg.Logger)+ if supplementErr != nil {+ b.cfg.Logger.Warn("agy additional messages unavailable for this run", "error", supplementErr)+ supplements = nil+ } else {+ cmd.Env = append(cmd.Env, supplements.env()...)+ }+ }stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[agy:stderr] "), agentStderrTailBytes)cmd.Stderr = stderrBufif err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {+ supplements.close()cancel()_ = os.Remove(logPath)return nil, fmt.Errorf("start agy: %w", err)@@ -426,6 +490,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Exdefer close(msgCh)defer close(resCh)defer os.Remove(logPath)+ defer supplements.close()startTime := time.Now()var output strings.Builder@@ -438,6 +503,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts ExstreamStepUsage := make(map[int]TokenUsage)streamTools := make(map[int]antigravityToolState)turn := antigravityTurn{steps: make(map[int]antigravityStepSummary)}+ transcript := &antigravityTranscript{logPath: logPath}finalStatus := "completed"var finalError string@@ -454,6 +520,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Excase "init":streamSessionID = event.ConversationIDstreamModel = event.Init.Model+ supplements.activate(streamSessionID)case "step_update":if event.StepUpdate == nil {turn.invalid = true@@ -464,8 +531,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Exturn.invalid = true} else {if step.StepType == "user_input" {- turn.invalid = turn.invalid || turn.start != nil && *turn.start != *idx- turn.start = idx+ turn.observeUserInput(*idx, supplements)}turn.steps[*idx] = antigravityStepSummary{kind: step.StepType, state: strings.ToUpper(step.State),@@ -474,7 +540,9 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex}if event.StepUpdate.ConversationID != "" {streamSessionID = event.StepUpdate.ConversationID+ supplements.activate(streamSessionID)}+ turn.confirmInjected(supplements, transcript, streamSessionID)for _, message := range antigravityToolMessages(event.StepUpdate, streamTools) {// Tool lifecycle events also drive the daemon's in-flight// counter. Unlike best-effort text, neither half may be@@ -499,6 +567,8 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Exif event.Result == nil {continue}+ turn.confirmInjected(supplements, transcript, streamSessionID)+ supplements.end()if event.Result.ConversationID != "" {streamSessionID = event.Result.ConversationID}@@ -533,8 +603,13 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Exb.cfg.Logger.Warn("agy stdout scanner error", "err", err)}+ turn.confirmInjected(supplements, transcript, streamSessionID)+ supplements.end()waitErr := cmd.Wait()releaseProcessGroup(cmd)+ // Remove the managed hooks before the result is reported, so a+ // follow-up run never observes them.+ supplements.close()duration := time.Since(startTime)sessionID := streamSessionID@@ -642,7 +717,21 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex}}()- return &Session{Messages: msgCh, Result: resCh}, nil+ session := &Session{Messages: msgCh, Result: resCh}+ switch {+ case supplements != nil:+ session.Supplement = supplements.supplement+ session.SupplementReady = supplements.ready+ case supplementErr != nil:+ // The daemon already offered steering for this run and there is no way+ // to withdraw it, so settle each message as failed right away instead of+ // leaving it pending until the turn ends.+ session.Supplement = func(context.Context, string) error {+ return fmt.Errorf("agy hooks unavailable: %w", supplementErr)+ }+ session.SupplementReady = func() bool { return runCtx.Err() == nil }+ }+ return session, nil}// antigravityConversationIDRe matches the glog line printmode.go writes when@@ -815,6 +904,99 @@ func readAntigravityTranscriptOutput(logPath, conversationID string) string {return strings.Join(parts, "\n\n")}+// antigravityTranscriptLineLimit bounds the transcript line the receipt scan+// decodes. Longer lines are skipped: the record of the largest guidance, even+// with every byte JSON-escaped, stays well below it.+const antigravityTranscriptLineLimit = 1 << 20++// antigravityTranscript scans the conversation transcript agy writes during+// the turn for the USER_INPUT records injected guidance became. Each scan+// reads only what was added since the previous one, through one bounded+// buffer, and decodes only lines that carry an in-flight marker. agy rewrites+// the file when it compacts the conversation, so a replaced or shrunken file+// is read again from the start, and so is the file at each new injected step+// (see confirmInjected), which catches a rewrite in place.+type antigravityTranscript struct {+ logPath string+ path string+ file os.FileInfo+ offset int64+ reader *bufio.Reader+}++func (r *antigravityTranscript) scan(conversationID string, markers []string, found func(marker string)) {+ if len(markers) == 0 {+ return+ }+ if r.path == "" {+ if conversationID == "" {+ return+ }+ // agy logs its data dir at startup, before any step; without it there+ // is no transcript to follow, so do not rescan the log on every event.+ appDataDir := readAntigravityAppDataDir(r.logPath)+ r.logPath = ""+ if appDataDir == "" {+ return+ }+ r.path = filepath.Join(appDataDir, "brain", conversationID, ".system_generated", "logs", "transcript.jsonl")+ }+ f, err := os.Open(r.path)+ if err != nil {+ return+ }+ defer f.Close()+ info, err := f.Stat()+ if err != nil {+ return+ }+ if r.file == nil || !os.SameFile(r.file, info) || info.Size() < r.offset {+ r.offset = 0+ }+ r.file = info+ if _, err := f.Seek(r.offset, io.SeekStart); err != nil {+ return+ }+ if r.reader == nil {+ r.reader = bufio.NewReaderSize(f, antigravityTranscriptLineLimit)+ } else {+ r.reader.Reset(f)+ }+ pos, long := r.offset, false+ for {+ line, err := r.reader.ReadSlice('\n')+ pos += int64(len(line))+ if errors.Is(err, bufio.ErrBufferFull) {+ long = true+ continue+ }+ if err != nil {+ // A partial last line is read again once agy completes it.+ return+ }+ if !long {+ for _, marker := range markers {+ if antigravityTranscriptCarries(line, marker) {+ found(marker)+ }+ }+ }+ long = false+ r.offset = pos+ }+}++func antigravityTranscriptCarries(line []byte, marker string) bool {+ if !bytes.Contains(line, []byte(marker)) {+ return false+ }+ var rec struct {+ Type string `json:"type"`+ Content string `json:"content"`+ }+ return json.Unmarshal(line, &rec) == nil && rec.Type == "USER_INPUT" && strings.Contains(rec.Content, marker)+}+// readAntigravityAppDataDir extracts agy's CLI app data directory from the// per-run log. Best-effort: returns "" if the log is missing or the marker// format changes upstream.diff --git a/server/pkg/agent/antigravity_supplement.go b/server/pkg/agent/antigravity_supplement.gonew file mode 100644index 0000000000..255d0b5055--- /dev/null+++ b/server/pkg/agent/antigravity_supplement.go@@ -0,0 +1,454 @@+package agent++import (+ "bytes"+ "context"+ "crypto/subtle"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "log/slog"+ "net"+ "net/http"+ "os"+ "path/filepath"+ "slices"+ "strings"+ "sync"+)++// AntigravityHookHelperArg selects the Antigravity hook relay mode of the+// multica binary. agy runs it before every model call of the turn; it forwards+// the hook event to the run's loopback endpoint and prints the hook output agy+// expects.+const AntigravityHookHelperArg = "__multica_antigravity_hook"++const (+ antigravityHookURLEnv = "MULTICA_ANTIGRAVITY_HOOK_URL"+ antigravityHookTokenEnv = "MULTICA_ANTIGRAVITY_HOOK_TOKEN"+ // antigravityHookName keys Multica's entry in the workspace hooks.json.+ antigravityHookName = "multica-steering"+ antigravityHookTimeoutSeconds = 10+ antigravityHookRequestLimit = 64 << 10+ antigravityHookStdinLimit = 64 << 20+ // antigravityHookGuidanceLimit bounds one message. It admits the API's+ // 64 KiB comment plus the daemon's framing, and JSON escaping grows a byte+ // to at most six (\u003c), so the hook reply stays inside the relay's+ // response limit.+ antigravityHookGuidanceLimit = 72 << 10+ antigravityHookEmptyReply = "{}"+)++// The relay must be able to carry the largest reply the session can build.+const _ = uint(hookRelayResponseLimit - 6*antigravityHookGuidanceLimit - 1024)++// antigravityHookRequest is the subset of agy's PreInvocation payload that+// decides ownership. The relay forwards only this field.+type antigravityHookRequest struct {+ ConversationID string `json:"conversationId"`+}++// antigravitySupplementSession delivers additional guidance through an+// Antigravity workspace hook. agy print mode reads no input after the prompt,+// so a managed .agents/hooks.json runs the multica relay before each model+// call, and the relay asks this session, over a token-protected loopback+// endpoint, for guidance to return as PreInvocation injectSteps userMessage+// entries. agy appends each as a user_input step of the running turn, so the+// model reads it as a message from the user.+//+// A hook response is not delivery: the relay can fail after it, and other+// hooks (global, plugin) can inject user input of their own. Each message+// opens with its own random marker, and counts as delivered only when agy's+// conversation transcript shows a USER_INPUT record carrying that marker. The+// marker leads the text so it survives the transcript's truncated content. The+// daemon delivers one message at a time, so each hook reply carries at most+// one.+type antigravitySupplementSession struct {+ ctx context.Context+ logger *slog.Logger+ token string+ url string+ server *http.Server+ hooksPath string+ hooksData []byte++ mu sync.Mutex+ conversationID string+ active bool+ ended bool+ pending []*antigravitySupplementInput+ inflight []*antigravitySupplementInput+ closeOnce sync.Once+}++type antigravitySupplementInput struct {+ ctx context.Context+ marker string+ text string+ done chan error+ // claimed is set while a hook response carries the input; only the stream+ // receipt or the end of the turn settles it then.+ claimed bool+}++func startAntigravitySupplementSession(ctx context.Context, cwd string, hookCommand []string, logger *slog.Logger) (*antigravitySupplementSession, error) {+ if strings.TrimSpace(cwd) == "" {+ return nil, errors.New("antigravity hooks require a working directory")+ }+ if len(hookCommand) == 0 || strings.TrimSpace(hookCommand[0]) == "" {+ return nil, errors.New("antigravity hook relay command is not configured")+ }+ token, err := randomHex(32)+ if err != nil {+ return nil, err+ }+ hooksData, err := antigravityHooksFileData(hookShellCommand(hookCommand))+ if err != nil {+ return nil, err+ }+ s := &antigravitySupplementSession{+ ctx: ctx,+ logger: logger,+ token: token,+ hooksPath: filepath.Join(cwd, ".agents", "hooks.json"),+ hooksData: hooksData,+ }+ if err := s.writeHooksFile(); err != nil {+ return nil, err+ }+ listener, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ s.removeHooksFile()+ return nil, fmt.Errorf("listen for antigravity hooks: %w", err)+ }+ s.url = "http://" + listener.Addr().String() + "/hook"+ s.server = &http.Server{Handler: s, ReadHeaderTimeout: hookRelayTimeout}+ go func() { _ = s.server.Serve(listener) }()+ return s, nil+}++// AntigravityHooksInstallable reports whether a run in cwd can carry Multica's+// managed .agents/hooks.json. Multica never replaces hooks it did not write: a+// workdir with its own keeps them and goes without steering, so the daemon+// must check this before it offers steering for the run.+func AntigravityHooksInstallable(cwd string) error {+ if strings.TrimSpace(cwd) == "" {+ return errors.New("antigravity hooks require a working directory")+ }+ dir := filepath.Join(cwd, ".agents")+ if info, err := os.Stat(dir); err == nil && !info.IsDir() {+ return fmt.Errorf("%s is not a directory", dir)+ } else if err != nil && !errors.Is(err, fs.ErrNotExist) {+ return fmt.Errorf("inspect .agents dir: %w", err)+ }+ path := filepath.Join(dir, "hooks.json")+ existing, err := os.ReadFile(path)+ switch {+ case err == nil && !antigravityManagedHooks(existing):+ return fmt.Errorf("workdir already has an unmanaged %s", path)+ case err != nil && !errors.Is(err, fs.ErrNotExist):+ return fmt.Errorf("read antigravity hooks: %w", err)+ }+ return nil+}++// antigravityManagedHooks reports whether data is exactly a hooks file Multica+// generated, possibly by an earlier daemon binary. Anything a user added to it+// makes the file theirs.+func antigravityManagedHooks(data []byte) bool {+ var file map[string]antigravityHookConfig+ if json.Unmarshal(data, &file) != nil || len(file) != 1 {+ return false+ }+ hooks := file[antigravityHookName].PreInvocation+ if len(hooks) != 1 || !strings.Contains(hooks[0].Command, AntigravityHookHelperArg) {+ return false+ }+ generated, err := antigravityHooksFileData(hooks[0].Command)+ return err == nil && bytes.Equal(data, generated)+}++func (s *antigravitySupplementSession) writeHooksFile() error {+ if err := AntigravityHooksInstallable(filepath.Dir(filepath.Dir(s.hooksPath))); err != nil {+ return err+ }+ if err := os.MkdirAll(filepath.Dir(s.hooksPath), 0o755); err != nil {+ return fmt.Errorf("create .agents dir: %w", err)+ }+ if err := os.WriteFile(s.hooksPath, s.hooksData, 0o600); err != nil {+ return fmt.Errorf("write antigravity hooks: %w", err)+ }+ return nil+}++func (s *antigravitySupplementSession) removeHooksFile() {+ current, err := os.ReadFile(s.hooksPath)+ if err != nil || !bytes.Equal(current, s.hooksData) {+ return+ }+ if err := os.Remove(s.hooksPath); err != nil && s.logger != nil {+ s.logger.Warn("antigravity hooks cleanup failed", "path", s.hooksPath, "error", err)+ }+}++// env returns the variables agy passes on to the hook relay.+func (s *antigravitySupplementSession) env() []string {+ return []string{antigravityHookURLEnv + "=" + s.url, antigravityHookTokenEnv + "=" + s.token}+}++// activate opens delivery once the CLI reports the conversation it is running.+func (s *antigravitySupplementSession) activate(conversationID string) {+ if s == nil || conversationID == "" {+ return+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.ended || s.conversationID != "" {+ return+ }+ s.conversationID = conversationID+ s.active = true+}++func (s *antigravitySupplementSession) ready() bool {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.active && !s.ended && s.ctx.Err() == nil+}++func (s *antigravitySupplementSession) supplement(ctx context.Context, text string) error {+ nonce, err := randomHex(8)+ if err != nil {+ return err+ }+ marker := cursorGuidanceTagPrefix + nonce + "]"+ text = marker + "\n" + text+ if len(text) > antigravityHookGuidanceLimit {+ return fmt.Errorf("antigravity guidance is %d bytes, limit %d", len(text), antigravityHookGuidanceLimit)+ }+ input := &antigravitySupplementInput{ctx: ctx, marker: marker, text: text, done: make(chan error, 1)}+ s.mu.Lock()+ if err := ctx.Err(); err != nil {+ s.mu.Unlock()+ return err+ }+ if s.ended || s.ctx.Err() != nil {+ s.mu.Unlock()+ return context.Canceled+ }+ if !s.active {+ s.mu.Unlock()+ return errors.New("antigravity turn has not started")+ }+ s.pending = append(s.pending, input)+ s.mu.Unlock()+ select {+ case err := <-input.done:+ return err+ case <-ctx.Done():+ case <-s.ctx.Done():+ }+ // Serialize cancellation with hook delivery: once a hook carries the input+ // it may already be in agy's trajectory, so only the receipt or the end of+ // the turn decides the outcome; otherwise withdraw it so a later hook+ // cannot deliver it after this call has reported failure.+ s.mu.Lock()+ if input.claimed {+ s.mu.Unlock()+ return <-input.done+ }+ defer s.mu.Unlock()+ select {+ case err := <-input.done:+ return err+ default:+ }+ if i := slices.Index(s.pending, input); i >= 0 {+ s.pending = slices.Delete(s.pending, i, i+1)+ }+ if err := ctx.Err(); err != nil {+ return err+ }+ return s.ctx.Err()+}++// prepareHook claims the oldest pending guidance for one hook response. Only+// the run's own conversation may consume it: subagents run their own+// conversations and their model calls fire the same hook.+func (s *antigravitySupplementSession) prepareHook(req antigravityHookRequest) (*antigravitySupplementInput, map[string]any) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if !s.active || s.ended || s.ctx.Err() != nil || req.ConversationID != s.conversationID {+ return nil, map[string]any{}+ }+ for len(s.pending) > 0 {+ input := s.pending[0]+ s.pending[0] = nil+ s.pending = s.pending[1:]+ if err := input.ctx.Err(); err != nil {+ input.done <- err+ continue+ }+ input.claimed = true+ s.inflight = append(s.inflight, input)+ return input, map[string]any{"injectSteps": []map[string]string{{"userMessage": input.text}}}+ }+ return nil, map[string]any{}+}++// unclaim returns guidance whose hook response never left this process to the+// head of the queue for the next model call.+func (s *antigravitySupplementSession) unclaim(input *antigravitySupplementInput) {+ s.mu.Lock()+ defer s.mu.Unlock()+ i := slices.Index(s.inflight, input)+ if input == nil || i < 0 {+ return+ }+ s.inflight = slices.Delete(s.inflight, i, i+1)+ input.claimed = false+ switch {+ case input.ctx.Err() != nil:+ input.done <- input.ctx.Err()+ case s.ended:+ input.done <- context.Canceled+ default:+ s.pending = append([]*antigravitySupplementInput{input}, s.pending...)+ }+}++// awaitingReceipt reports whether injected guidance is waiting for the+// user_input step it should become.+func (s *antigravitySupplementSession) awaitingReceipt() bool {+ if s == nil {+ return false+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ return len(s.inflight) > 0+}++// inflightMarkers lists the markers of guidance a hook has injected.+func (s *antigravitySupplementSession) inflightMarkers() []string {+ if s == nil {+ return nil+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ markers := make([]string, len(s.inflight))+ for i, input := range s.inflight {+ markers[i] = input.marker+ }+ return markers+}++// receipt settles the injected guidance a transcript USER_INPUT record+// carries the marker of.+func (s *antigravitySupplementSession) receipt(marker string) {+ if s == nil {+ return+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ i := slices.IndexFunc(s.inflight, func(input *antigravitySupplementInput) bool { return input.marker == marker })+ if i < 0 {+ return+ }+ s.inflight[i].done <- nil+ s.inflight = slices.Delete(s.inflight, i, i+1)+}++func (s *antigravitySupplementSession) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost || r.URL.Path != "/hook" {+ http.NotFound(w, r)+ return+ }+ if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+s.token)) != 1 {+ http.Error(w, "unauthorized", http.StatusUnauthorized)+ return+ }+ var req antigravityHookRequest+ if err := json.NewDecoder(io.LimitReader(r.Body, antigravityHookRequestLimit)).Decode(&req); err != nil {+ http.Error(w, "invalid hook request", http.StatusBadRequest)+ return+ }+ claimed, reply := s.prepareHook(req)+ body, err := json.Marshal(reply)+ if err == nil {+ w.Header().Set("Content-Type", "application/json")+ _, err = w.Write(body)+ }+ if err != nil {+ s.unclaim(claimed)+ if s.logger != nil {+ s.logger.Warn("antigravity hook response failed", "error", err)+ }+ }+}++// end closes delivery when the turn reaches its terminal result. Guidance+// still in flight never became a user_input step of this turn.+func (s *antigravitySupplementSession) end() {+ if s == nil {+ return+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ s.ended, s.active = true, false+ for _, input := range slices.Concat(s.pending, s.inflight) {+ input.done <- context.Canceled+ }+ s.pending, s.inflight = nil, nil+}++func (s *antigravitySupplementSession) close() {+ if s == nil {+ return+ }+ s.closeOnce.Do(func() {+ s.end()+ _ = s.server.Close()+ s.removeHooksFile()+ })+}++type antigravityHookEntry struct {+ Type string `json:"type"`+ Command string `json:"command"`+ Timeout int `json:"timeout"`+}++type antigravityHookConfig struct {+ PreInvocation []antigravityHookEntry `json:"PreInvocation"`+}++func antigravityHooksFileData(command string) ([]byte, error) {+ file := map[string]antigravityHookConfig{+ antigravityHookName: {PreInvocation: []antigravityHookEntry{{+ Type: "command", Command: command, Timeout: antigravityHookTimeoutSeconds,+ }}},+ }+ data, err := json.MarshalIndent(file, "", " ")+ if err != nil {+ return nil, fmt.Errorf("marshal antigravity hooks: %w", err)+ }+ return append(data, '\n'), nil+}++// RunAntigravityHookRelay is the body of the Antigravity hook command. It+// always prints one JSON object and never fails the hook: a run without+// steering, a stale hooks.json or an unreachable endpoint all answer "{}" so+// the model call proceeds untouched.+func RunAntigravityHookRelay(stdin io.Reader, stdout io.Writer, getenv func(string) string) {+ _, _ = io.WriteString(stdout, antigravityHookRelay(stdin, getenv)+"\n")+}++func antigravityHookRelay(stdin io.Reader, getenv func(string) string) string {+ var req antigravityHookRequest+ if err := json.NewDecoder(io.LimitReader(stdin, antigravityHookStdinLimit)).Decode(&req); err != nil {+ return antigravityHookEmptyReply+ }+ return forwardHookRequest(getenv(antigravityHookURLEnv), getenv(antigravityHookTokenEnv), req, antigravityHookEmptyReply)+}diff --git a/server/pkg/agent/antigravity_supplement_integration_test.go b/server/pkg/agent/antigravity_supplement_integration_test.gonew file mode 100644index 0000000000..b57dce6450--- /dev/null+++ b/server/pkg/agent/antigravity_supplement_integration_test.go@@ -0,0 +1,89 @@+//go:build agentintegration++package agent++import (+ "context"+ "log/slog"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++// TestAntigravityRealSupplementReachesTheTurn steers a real agy print-mode run+// through the real multica hook relay and asserts the model acted on the+// guidance in the same turn. It is what catches agy changing PreInvocation+// injection, or no longer reporting the injected user_input step that settles+// delivery.+func TestAntigravityRealSupplementReachesTheTurn(t *testing.T) {+ requireRealAgentSmoke(t)+ if testing.Short() {+ t.Skip("skipping real-binary smoke test in -short mode")+ }+ path, err := exec.LookPath("agy")+ if err != nil {+ t.Skip("agy not on PATH; skipping real-binary smoke test")+ }+ version, err := exec.Command(path, "--version").Output()+ if err != nil || !SupportsTaskSupplement("antigravity", strings.TrimSpace(string(version))) {+ t.Skipf("agy %q predates PreInvocation steering", strings.TrimSpace(string(version)))+ }+ relay := filepath.Join(t.TempDir(), "multica")+ if out, err := exec.Command("go", "build", "-o", relay, "github.com/multica-ai/multica/server/cmd/multica").CombinedOutput(); err != nil {+ t.Fatalf("build multica relay: %v\n%s", err, out)+ }++ backend, err := New("antigravity", Config{ExecutablePath: path, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new antigravity backend: %v", err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 240*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx,+ "Run `sleep 10 && echo step-one` in the shell. After it finishes, run `echo step-two` in the shell. Then reply with a one-line summary.",+ ExecOptions{+ Cwd: t.TempDir(),+ Timeout: 230 * time.Second,+ EnableTaskSupplement: true,+ SupplementHookCommand: []string{relay, AntigravityHookHelperArg},+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ for !session.SupplementReady() {+ select {+ case <-ctx.Done():+ t.Fatal("agy turn never became ready for guidance")+ case <-time.After(50 * time.Millisecond):+ }+ }+ // The daemon's own framing (formatTaskSupplementInstruction).+ guidance := `[ADDITIONAL GUIDANCE] Human "Jiayuan" added guidance while you were working.++Treat this as additional guidance for the same active task, not as a replacement:+- Preserve and complete the original objective.+- Incorporate this guidance into the work and the turn's single final response.+- Do not send a separate acknowledgement.+- Replace or cancel the original objective only if the human explicitly asks for replacement or cancellation.++Human message:+Also include the codeword ORCHID-19 in your final reply.`+ if err := session.Supplement(ctx, guidance); err != nil {+ t.Fatalf("supplement was not delivered: %v", err)+ }++ result := <-session.Result+ if result.Status != "completed" {+ t.Fatalf("status = %q, error = %q", result.Status, result.Error)+ }+ if !strings.Contains(result.Output, "ORCHID-19") {+ t.Fatalf("final reply ignored the delivered guidance: %q", result.Output)+ }+}diff --git a/server/pkg/agent/antigravity_supplement_test.go b/server/pkg/agent/antigravity_supplement_test.gonew file mode 100644index 0000000000..906667b76b--- /dev/null+++ b/server/pkg/agent/antigravity_supplement_test.go@@ -0,0 +1,632 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "log/slog"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "testing"+ "time"+)++var testAntigravityHookCommand = []string{"/opt/multica tools/multica", AntigravityHookHelperArg}++func startTestAntigravitySupplements(t *testing.T, ctx context.Context) (*antigravitySupplementSession, string) {+ t.Helper()+ cwd := t.TempDir()+ s, err := startAntigravitySupplementSession(ctx, cwd, testAntigravityHookCommand, slog.Default())+ if err != nil {+ t.Fatalf("startAntigravitySupplementSession: %v", err)+ }+ t.Cleanup(s.close)+ return s, cwd+}++func (s *antigravitySupplementSession) testEnv(name string) string {+ for _, kv := range s.env() {+ if key, value, ok := strings.Cut(kv, "="); ok && key == name {+ return value+ }+ }+ return ""+}++func preInvocation(conversationID string) map[string]any {+ return map[string]any{+ "conversationId": conversationID,+ "transcriptPath": "/tmp/transcript.jsonl",+ "invocationNum": 2,+ "initialNumSteps": 1,+ "lastUserInput": strings.Repeat("x", 1<<20),+ }+}++func relayAntigravityHook(t *testing.T, getenv func(string) string, payload map[string]any) map[string]any {+ t.Helper()+ data, err := json.Marshal(payload)+ if err != nil {+ t.Fatal(err)+ }+ var out strings.Builder+ RunAntigravityHookRelay(strings.NewReader(string(data)), &out, getenv)+ var reply map[string]any+ if err := json.Unmarshal([]byte(out.String()), &reply); err != nil {+ t.Fatalf("relay printed %q, want one JSON object: %v", out.String(), err)+ }+ return reply+}++func injectedUserMessages(t *testing.T, reply map[string]any) []string {+ t.Helper()+ steps, _ := reply["injectSteps"].([]any)+ var messages []string+ for _, raw := range steps {+ step, _ := raw.(map[string]any)+ if len(step) != 1 {+ t.Fatalf("inject step %#v must carry exactly one field", raw)+ }+ message, ok := step["userMessage"].(string)+ if !ok {+ t.Fatalf("inject step %#v is not a userMessage", raw)+ }+ marker, body, ok := strings.Cut(message, "\n")+ if !ok || !strings.HasPrefix(marker, cursorGuidanceTagPrefix) {+ t.Fatalf("injected message %.80q does not open with a guidance marker", message)+ }+ messages = append(messages, body)+ }+ return messages+}++// onlyInflightMarker returns the marker of the single guidance a hook injected.+func onlyInflightMarker(t *testing.T, s *antigravitySupplementSession) string {+ t.Helper()+ markers := s.inflightMarkers()+ if len(markers) != 1 {+ t.Fatalf("in-flight markers = %q, want one", markers)+ }+ return markers[0]+}++// antigravitySupplementAsync starts Supplement and waits until the input is+// queued, so a following hook observes it deterministically.+func antigravitySupplementAsync(t *testing.T, s *antigravitySupplementSession, ctx context.Context, text string) <-chan error {+ t.Helper()+ before := func() int {+ s.mu.Lock()+ defer s.mu.Unlock()+ return len(s.pending)+ }()+ done := make(chan error, 1)+ go func() { done <- s.supplement(ctx, text) }()+ deadline := time.Now().Add(5 * time.Second)+ for {+ s.mu.Lock()+ queued := len(s.pending)+ s.mu.Unlock()+ if queued > before {+ return done+ }+ select {+ case err := <-done:+ t.Fatalf("supplement returned before a hook: %v", err)+ default:+ }+ if time.Now().After(deadline) {+ t.Fatal("supplement was never queued")+ }+ time.Sleep(5 * time.Millisecond)+ }+}++// assertAntigravityDelivered expects a receipt the caller has just processed+// to have settled the supplement.+func assertAntigravityDelivered(t *testing.T, done <-chan error) {+ t.Helper()+ select {+ case err := <-done:+ if err != nil {+ t.Fatalf("supplement = %v, want delivered", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("supplement was not delivered")+ }+}++func assertAntigravitySupplementWaiting(t *testing.T, done <-chan error) {+ t.Helper()+ select {+ case err := <-done:+ t.Fatalf("supplement settled (%v) before agy reported the user_input step", err)+ case <-time.After(50 * time.Millisecond):+ }+}++func TestAntigravitySupplementDeliversThroughHookRelay(t *testing.T) {+ s, cwd := startTestAntigravitySupplements(t, t.Context())++ data, err := os.ReadFile(filepath.Join(cwd, ".agents", "hooks.json"))+ if err != nil {+ t.Fatalf("hooks.json not written: %v", err)+ }+ var hooks map[string]antigravityHookConfig+ if err := json.Unmarshal(data, &hooks); err != nil {+ t.Fatal(err)+ }+ wantCommand := `'/opt/multica tools/multica' '` + AntigravityHookHelperArg + `'`+ if got := hooks[antigravityHookName].PreInvocation; len(got) != 1 || got[0].Command != wantCommand || got[0].Type != "command" {+ t.Fatalf("PreInvocation hooks = %#v, want command %q", got, wantCommand)+ }++ if s.ready() {+ t.Fatal("ready before the CLI reported its conversation")+ }+ if err := s.supplement(t.Context(), "early"); err == nil || !strings.Contains(err.Error(), "turn has not started") {+ t.Fatalf("supplement before start = %v, want turn-not-started", err)+ }+ s.activate("conv-main")+ if !s.ready() {+ t.Fatal("not ready after activation")+ }++ done := antigravitySupplementAsync(t, s, t.Context(), "Also update the changelog.")+ reply := relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))+ if got := injectedUserMessages(t, reply); len(got) != 1 || got[0] != "Also update the changelog." {+ t.Fatalf("injected = %q", got)+ }+ assertAntigravitySupplementWaiting(t, done)+ if reply := relayAntigravityHook(t, s.testEnv, preInvocation("conv-main")); len(reply) != 0 {+ t.Fatalf("second hook replayed claimed guidance: %#v", reply)+ }++ s.receipt(onlyInflightMarker(t, s))+ if err := <-done; err != nil {+ t.Fatalf("supplement = %v, want delivered", err)+ }+ if s.awaitingReceipt() {+ t.Fatal("delivered guidance still awaits a receipt")+ }+}++// Global and plugin hooks can inject user input into the same conversation.+// Their user_input step must not count as Multica's delivery.+func TestAntigravitySupplementIgnoresForeignUserInput(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ done := antigravitySupplementAsync(t, s, t.Context(), "Prefer the smaller fix.")+ relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))++ s.receipt(cursorGuidanceTagPrefix + "0000000000000000]")+ assertAntigravitySupplementWaiting(t, done)+ s.end()+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("supplement = %v, want canceled at turn end", err)+ }+}++func TestAntigravitySupplementIgnoresOtherConversations(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ done := antigravitySupplementAsync(t, s, t.Context(), "Use the smaller fix.")+ for _, conversationID := range []string{"", "conv-subagent"} {+ if reply := relayAntigravityHook(t, s.testEnv, preInvocation(conversationID)); len(reply) != 0 {+ t.Fatalf("conversation %q consumed guidance: %#v", conversationID, reply)+ }+ }+ if got := injectedUserMessages(t, relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))); len(got) != 1 {+ t.Fatalf("main conversation injected %q", got)+ }+ s.receipt(onlyInflightMarker(t, s))+ if err := <-done; err != nil {+ t.Fatalf("supplement = %v", err)+ }+}++func TestAntigravitySupplementInjectsOneMessagePerHookInOrder(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ first := antigravitySupplementAsync(t, s, t.Context(), "first")+ second := antigravitySupplementAsync(t, s, t.Context(), "second")+ for _, want := range []string{"first", "second"} {+ if got := injectedUserMessages(t, relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))); len(got) != 1 || got[0] != want {+ t.Fatalf("injected = %q, want %q", got, want)+ }+ }+ markers := s.inflightMarkers()+ if len(markers) != 2 || markers[0] == markers[1] {+ t.Fatalf("in-flight markers = %q, want one per message", markers)+ }+ s.receipt(markers[1])+ if err := <-second; err != nil {+ t.Fatalf("second = %v", err)+ }+ assertAntigravitySupplementWaiting(t, first)+ s.receipt(markers[0])+ if err := <-first; err != nil {+ t.Fatalf("first = %v", err)+ }+}++func TestAntigravitySupplementWithoutReceiptFailsAtTurnEnd(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ done := antigravitySupplementAsync(t, s, ctx, "Run the tests again.")+ relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))++ // The caller giving up does not withdraw guidance a hook already carried.+ cancel()+ assertAntigravitySupplementWaiting(t, done)++ s.end()+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("supplement = %v, want canceled at turn end", err)+ }+ if s.ready() {+ t.Fatal("ready after the turn ended")+ }+ if err := s.supplement(t.Context(), "late"); !errors.Is(err, context.Canceled) {+ t.Fatalf("late supplement = %v, want canceled", err)+ }+}++func TestAntigravitySupplementCancelWithdrawsUnclaimedGuidance(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ ctx, cancel := context.WithCancel(t.Context())+ done := antigravitySupplementAsync(t, s, ctx, "Never mind.")+ cancel()+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("supplement = %v, want canceled", err)+ }+ if reply := relayAntigravityHook(t, s.testEnv, preInvocation("conv-main")); len(reply) != 0 {+ t.Fatalf("withdrawn guidance was injected: %#v", reply)+ }+}++func TestAntigravitySupplementUnsentReplyReturnsGuidanceToQueue(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ first := antigravitySupplementAsync(t, s, t.Context(), "first")+ claimed, _ := s.prepareHook(antigravityHookRequest{ConversationID: "conv-main"})+ second := antigravitySupplementAsync(t, s, t.Context(), "second")+ s.unclaim(claimed)++ for _, want := range []string{"first", "second"} {+ if got := injectedUserMessages(t, relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))); len(got) != 1 || got[0] != want {+ t.Fatalf("injected = %q, want the unsent guidance first", got)+ }+ s.receipt(onlyInflightMarker(t, s))+ }+ for _, done := range []<-chan error{first, second} {+ if err := <-done; err != nil {+ t.Fatalf("supplement = %v", err)+ }+ }+}++// The API accepts 64 KiB comments and the daemon frames them before delivery.+// JSON escapes '<' as six bytes, so the hook reply is several times larger than+// the message; it must still reach agy intact.+func TestAntigravitySupplementCarriesLargestCommentThroughRelay(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ big := strings.Repeat("x", 1024) + "\n\nHuman message:\n" + strings.Repeat("<", 64<<10)+ done := antigravitySupplementAsync(t, s, t.Context(), big)+ if got := injectedUserMessages(t, relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))); len(got) != 1 || got[0] != big {+ t.Fatalf("relay injected %d messages, want the full comment", len(got))+ }+ s.receipt(onlyInflightMarker(t, s))+ if err := <-done; err != nil {+ t.Fatalf("supplement = %v", err)+ }++ if err := s.supplement(t.Context(), strings.Repeat("b", antigravityHookGuidanceLimit+1)); err == nil || !strings.Contains(err.Error(), "limit") {+ t.Fatalf("oversized supplement = %v, want limit error", err)+ }+}++func TestAntigravitySupplementCloseCleansUpOnlyItsHooks(t *testing.T) {+ s, cwd := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ done := antigravitySupplementAsync(t, s, t.Context(), "pending")+ s.close()+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("pending supplement = %v, want canceled", err)+ }+ if _, err := os.Stat(filepath.Join(cwd, ".agents", "hooks.json")); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("hooks.json after close: %v, want removed", err)+ }++ edited, cwd2 := startTestAntigravitySupplements(t, t.Context())+ path := filepath.Join(cwd2, ".agents", "hooks.json")+ if err := os.WriteFile(path, []byte(`{"user":{}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ edited.close()+ if _, err := os.Stat(path); err != nil {+ t.Fatalf("close removed a hooks.json it no longer owns: %v", err)+ }+}++func TestAntigravitySupplementKeepsUnmanagedHooksFile(t *testing.T) {+ cwd := t.TempDir()+ path := filepath.Join(cwd, ".agents", "hooks.json")+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ const userHooks = `{"lint":{"PreInvocation":[{"command":"./lint.sh"}]}}`+ if err := os.WriteFile(path, []byte(userHooks), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := AntigravityHooksInstallable(cwd); err == nil {+ t.Fatal("an unmanaged hooks.json was reported installable")+ }+ if _, err := startAntigravitySupplementSession(t.Context(), cwd, testAntigravityHookCommand, slog.Default()); err == nil {+ t.Fatal("started over an unmanaged hooks.json")+ }+ if data, _ := os.ReadFile(path); string(data) != userHooks {+ t.Fatalf("user hooks.json changed: %s", data)+ }++ stale, err := antigravityHooksFileData(hookShellCommand([]string{"/old/multica", AntigravityHookHelperArg}))+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, stale, 0o600); err != nil {+ t.Fatal(err)+ }+ s, err := startAntigravitySupplementSession(t.Context(), cwd, testAntigravityHookCommand, slog.Default())+ if err != nil {+ t.Fatalf("stale managed hooks.json blocked start: %v", err)+ }+ s.close()++ // A hook the user added to the generated file makes the file theirs, even+ // though it still names the relay: a later run must not overwrite it.+ var extended map[string]any+ if err := json.Unmarshal(stale, &extended); err != nil {+ t.Fatal(err)+ }+ extended["lint"] = map[string]any{"PreInvocation": []any{map[string]any{"type": "command", "command": "./lint.sh"}}}+ userEdited, err := json.MarshalIndent(extended, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, userEdited, 0o600); err != nil {+ t.Fatal(err)+ }+ if err := AntigravityHooksInstallable(cwd); err == nil {+ t.Fatal("a managed hooks.json with a user hook was reported installable")+ }+ if _, err := startAntigravitySupplementSession(t.Context(), cwd, testAntigravityHookCommand, slog.Default()); err == nil {+ t.Fatal("started over a user-extended hooks.json")+ }+ if data, _ := os.ReadFile(path); string(data) != string(userEdited) {+ t.Fatalf("user-extended hooks.json changed: %s", data)+ }++ agentsFile := t.TempDir()+ if err := os.WriteFile(filepath.Join(agentsFile, ".agents"), nil, 0o600); err != nil {+ t.Fatal(err)+ }+ if err := AntigravityHooksInstallable(agentsFile); err == nil {+ t.Fatal(".agents as a file was reported installable")+ }+}++func TestAntigravityHookRelayFailsOpen(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ env := func(url, token string) func(string) string {+ return func(name string) string {+ switch name {+ case antigravityHookURLEnv:+ return url+ case antigravityHookTokenEnv:+ return token+ }+ return ""+ }+ }+ for name, getenv := range map[string]func(string) string{+ "no env": env("", ""),+ "wrong token": env(s.url, "nope"),+ "non-loopback": env(strings.Replace(s.url, "127.0.0.1", "192.0.2.1", 1), s.token),+ "unreachable": env("http://127.0.0.1:1/hook", s.token),+ } {+ if reply := relayAntigravityHook(t, getenv, preInvocation("conv-main")); len(reply) != 0 {+ t.Fatalf("%s: relay replied %#v, want {}", name, reply)+ }+ }+ var out strings.Builder+ RunAntigravityHookRelay(strings.NewReader("not json"), &out, s.testEnv)+ if out.String() != "{}\n" {+ t.Fatalf("invalid payload: relay printed %q", out.String())+ }+}++func TestAntigravityTurnAcceptsOnlyInjectedUserInputs(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ done := antigravitySupplementAsync(t, s, t.Context(), "steer")+ relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))++ marker := onlyInflightMarker(t, s)+ transcript, appDataDir := newTestAntigravityTranscript(t)++ turn := antigravityTurn{steps: map[int]antigravityStepSummary{}}+ turn.observeUserInput(0, s)+ turn.observeUserInput(0, s) // a re-emitted snapshot of the opening step+ turn.observeUserInput(2, s) // another hook's input while guidance is in flight+ turn.observeUserInput(3, s) // the injected guidance+ turn.observeUserInput(3, s) // its re-emitted snapshot+ if turn.invalid || *turn.start != 0 || !turn.injected[2] || !turn.injected[3] {+ t.Fatalf("turn = %+v, want start 0 with steps 2 and 3 injected", turn)+ }++ // Until the transcript shows the marker, nothing is delivered; the foreign+ // input settles nothing.+ turn.confirmInjected(s, transcript, "conv-main")+ seedAntigravityTranscript(t, appDataDir, "conv-main", []string{+ `{"type":"USER_INPUT","step_index":0,"content":"goal"}`,+ `{"type":"USER_INPUT","step_index":2,"content":"lint: ok"}`,+ })+ turn.confirmInjected(s, transcript, "conv-main")+ assertAntigravitySupplementWaiting(t, done)+ if !turn.checkTranscript {+ t.Fatal("stopped checking the transcript with guidance still in flight")+ }+ appendAntigravityTranscript(t, appDataDir, "conv-main", antigravityUserInputRecord(t, 3, marker+"\nsteer"))+ turn.confirmInjected(s, transcript, "conv-main")+ if err := <-done; err != nil {+ t.Fatalf("supplement = %v", err)+ }+ if turn.checkTranscript {+ t.Fatal("still checking the transcript with nothing in flight")+ }+ turn.observeUserInput(5, s)+ if !turn.invalid {+ t.Fatal("a user_input step nothing injected was accepted")+ }++ var unsteered antigravityTurn+ unsteered.observeUserInput(0, nil)+ unsteered.observeUserInput(1, nil)+ if !unsteered.invalid {+ t.Fatal("a second boundary without steering was accepted")+ }+}++func appendAntigravityTranscript(t *testing.T, appDataDir, conversationID, record string) {+ t.Helper()+ path := filepath.Join(appDataDir, "brain", conversationID, ".system_generated", "logs", "transcript.jsonl")+ f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o644)+ if err != nil {+ t.Fatal(err)+ }+ defer f.Close()+ if _, err := f.WriteString(record + "\n"); err != nil {+ t.Fatal(err)+ }+}++func newTestAntigravityTranscript(t *testing.T) (*antigravityTranscript, string) {+ t.Helper()+ appDataDir := t.TempDir()+ logPath := filepath.Join(t.TempDir(), "agy.log")+ if err := os.WriteFile(logPath, []byte("I0630 1 common.go:156] CLI app data directory: "+appDataDir+"\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ return &antigravityTranscript{logPath: logPath}, appDataDir+}++func antigravityUserInputRecord(t *testing.T, step int, content string, extra ...string) string {+ t.Helper()+ data, err := json.Marshal(map[string]any{"type": "USER_INPUT", "source": "USER_EXPLICIT", "step_index": step, "content": content})+ if err != nil {+ t.Fatal(err)+ }+ if len(extra) > 0 {+ return strings.TrimSuffix(string(data), "}") + "," + strings.Join(extra, ",") + "}"+ }+ return string(data)+}++// agy rewrites the transcript when it compacts the conversation. A receipt+// written after that must still be found.+func TestAntigravityTranscriptFollowsCompactionRewrite(t *testing.T) {+ transcript, appDataDir := newTestAntigravityTranscript(t)+ const first, second = "[MULTICA-GUIDANCE nonce=1111111111111111]", "[MULTICA-GUIDANCE nonce=2222222222222222]"+ history := []string{antigravityUserInputRecord(t, 0, "goal")}+ for i := 1; i < 200; i++ {+ history = append(history, `{"type":"PLANNER_RESPONSE","source":"MODEL","status":"DONE","step_index":`+strconv.Itoa(i)+`,"content":"`+strings.Repeat("work ", 30)+`"}`)+ }+ history = append(history, antigravityUserInputRecord(t, 200, first+"\nfirst"))+ seedAntigravityTranscript(t, appDataDir, "conv-main", history)++ var found []string+ collect := func(marker string) { found = append(found, marker) }+ transcript.scan("conv-main", []string{first}, collect)+ if len(found) != 1 || found[0] != first {+ t.Fatalf("found = %q, want the first receipt", found)+ }++ seedAntigravityTranscript(t, appDataDir, "conv-main", []string{+ `{"type":"CONVERSATION_HISTORY","content":"summary"}`,+ antigravityUserInputRecord(t, 4, second+"\nsecond"),+ })+ found = nil+ transcript.scan("conv-main", []string{second}, collect)+ if len(found) != 1 || found[0] != second {+ t.Fatalf("found = %q, want the receipt in the rewritten transcript", found)+ }+}++// The compact transcript keeps only a prefix of long content. The marker+// leads the message, so the receipt survives the truncation.+func TestAntigravityTranscriptMatchesTruncatedContent(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ long := strings.Repeat("x", 64<<10)+ done := antigravitySupplementAsync(t, s, t.Context(), long)+ relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))+ marker := onlyInflightMarker(t, s)++ transcript, appDataDir := newTestAntigravityTranscript(t)+ seedAntigravityTranscript(t, appDataDir, "conv-main", []string{+ antigravityUserInputRecord(t, 0, "goal"),+ antigravityUserInputRecord(t, 3, (marker + "\n" + long)[:4096], `"truncated_fields":["content"]`),+ })+ turn := antigravityTurn{steps: map[int]antigravityStepSummary{}}+ turn.observeUserInput(0, s)+ turn.observeUserInput(3, s)+ turn.confirmInjected(s, transcript, "conv-main")+ assertAntigravityDelivered(t, done)+}++// A compaction can rewrite the transcript in place and grow it past the+// remembered offset before the next check, so the offset lands inside the+// receipt's line. A new injected step must read the file from the start.+func TestAntigravityTranscriptFindsReceiptAfterInPlaceRewrite(t *testing.T) {+ s, _ := startTestAntigravitySupplements(t, t.Context())+ s.activate("conv-main")+ transcript, appDataDir := newTestAntigravityTranscript(t)+ turn := antigravityTurn{steps: map[int]antigravityStepSummary{}}+ turn.observeUserInput(0, s)++ first := antigravitySupplementAsync(t, s, t.Context(), "first")+ relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))+ history := []string{antigravityUserInputRecord(t, 0, "goal")}+ for i := 1; i < 200; i++ {+ history = append(history, `{"type":"PLANNER_RESPONSE","source":"MODEL","status":"DONE","step_index":`+strconv.Itoa(i)+`,"content":"`+strings.Repeat("work ", 30)+`"}`)+ }+ history = append(history, antigravityUserInputRecord(t, 200, onlyInflightMarker(t, s)+"\nfirst"))+ seedAntigravityTranscript(t, appDataDir, "conv-main", history)+ turn.observeUserInput(200, s)+ turn.confirmInjected(s, transcript, "conv-main")+ if err := <-first; err != nil {+ t.Fatalf("first = %v", err)+ }+ oldOffset := int(transcript.offset)++ second := antigravitySupplementAsync(t, s, t.Context(), "second")+ relayAntigravityHook(t, s.testEnv, preInvocation("conv-main"))+ receipt := antigravityUserInputRecord(t, 4, onlyInflightMarker(t, s)+"\nsecond "+strings.Repeat("y", 2000))+ padding := `{"type":"CONVERSATION_HISTORY","content":"` + strings.Repeat("s", oldOffset-500) + `"}`+ if len(padding)+1 >= oldOffset || len(padding)+1+len(receipt)+1 <= oldOffset {+ t.Fatal("fixture: the receipt line must straddle the old offset")+ }+ path := filepath.Join(appDataDir, "brain", "conv-main", ".system_generated", "logs", "transcript.jsonl")+ if err := os.WriteFile(path, []byte(padding+"\n"+receipt+"\n"), 0o644); err != nil { // same inode+ t.Fatal(err)+ }+ turn.observeUserInput(4, s)+ turn.confirmInjected(s, transcript, "conv-main")+ assertAntigravityDelivered(t, second)+}diff --git a/server/pkg/agent/antigravity_supplement_unix_test.go b/server/pkg/agent/antigravity_supplement_unix_test.gonew file mode 100644index 0000000000..424f8822fe--- /dev/null+++ b/server/pkg/agent/antigravity_supplement_unix_test.go@@ -0,0 +1,248 @@+//go:build unix++package agent++import (+ "context"+ "errors"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestAntigravityExecuteSteersRunningTurnThroughHooks(t *testing.T) {+ t.Parallel()+ // "delivered": agy records the injected guidance as the step's user input.+ // "foreign hook input": Multica's reply was not applied; another hook+ // injected its own input, which carries no marker.+ for name, wantDelivered := range map[string]bool{"delivered": true, "foreign hook input": false} {+ t.Run(name, func(t *testing.T) {+ t.Parallel()+ testAntigravityExecuteSteering(t, wantDelivered)+ })+ }+}++func testAntigravityExecuteSteering(t *testing.T, wantDelivered bool) {+ cwd := t.TempDir()+ appDataDir := t.TempDir()+ transcript := filepath.Join(appDataDir, "brain", "conv-steer", ".system_generated", "logs", "transcript.jsonl")+ if err := os.MkdirAll(filepath.Dir(transcript), 0o755); err != nil {+ t.Fatal(err)+ }+ script := `#!/bin/sh+log=""+while [ $# -gt 0 ]; do+ case "$1" in+ --log-file) log="$2"; shift 2 ;;+ *) shift ;;+ esac+done+printf 'I0630 1 common.go:156] CLI app data directory: %s\n' '` + appDataDir + `' >> "$log"+printf '%s\n%s\n' "$MULTICA_ANTIGRAVITY_HOOK_URL" "$MULTICA_ANTIGRAVITY_HOOK_TOKEN" > hook-env.txt+printf '%s\n' '{"event":"init","conversation_id":"conv-steer","init":{}}'+printf '%s\n' '{"type":"USER_INPUT","step_index":0,"content":"original goal"}' >> '` + transcript + `'+printf '%s\n' '{"event":"step_update","step_update":{"conversation_id":"conv-steer","step_index":0,"state":"DONE","step_type":"user_input"}}'+while [ ! -f injected ]; do sleep 0.02; done+printf '%s\n' '{"event":"step_update","step_update":{"conversation_id":"conv-steer","step_index":3,"state":"DONE","step_type":"user_input"}}'+while [ ! -f answer ]; do sleep 0.02; done+printf '%s\n' '{"event":"step_update","step_update":{"conversation_id":"conv-steer","step_index":4,"state":"DONE","step_type":"agent_response","text_delta":"Done, with the smaller fix."}}'+printf '%s\n' '{"event":"result","result":{"conversation_id":"conv-steer","status":"ERROR","response":"Done, with the smaller fix.","error":"There was a network issue connecting to the server, please try again."}}'+`+ fakePath := filepath.Join(t.TempDir(), "agy")+ writeTestExecutable(t, fakePath, []byte(script))+ backend, err := New("antigravity", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("New(antigravity): %v", err)+ }+ session, err := backend.Execute(t.Context(), "original goal", ExecOptions{+ Cwd: cwd,+ Timeout: 30 * time.Second,+ EnableTaskSupplement: true,+ SupplementHookCommand: testAntigravityHookCommand,+ })+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ if session.Supplement == nil || session.SupplementReady == nil {+ t.Fatal("negotiated antigravity session exposes no supplement hooks")+ }++ deadline := time.Now().Add(10 * time.Second)+ for !session.SupplementReady() {+ if time.Now().After(deadline) {+ t.Fatal("session never became ready")+ }+ time.Sleep(10 * time.Millisecond)+ }+ var envLines []string+ for len(envLines) < 2 {+ data, _ := os.ReadFile(filepath.Join(cwd, "hook-env.txt"))+ envLines = strings.Fields(string(data))+ if time.Now().After(deadline) {+ t.Fatal("agy did not receive the hook environment")+ }+ time.Sleep(10 * time.Millisecond)+ }+ getenv := func(name string) string {+ switch name {+ case antigravityHookURLEnv:+ return envLines[0]+ case antigravityHookTokenEnv:+ return envLines[1]+ }+ return ""+ }+ if _, err := os.Stat(filepath.Join(cwd, ".agents", "hooks.json")); err != nil {+ t.Fatalf("hooks.json missing during the run: %v", err)+ }++ done := make(chan error, 1)+ go func() { done <- session.Supplement(t.Context(), "Prefer the smaller fix.") }()+ var injected []string+ var reply map[string]any+ for len(injected) == 0 && time.Now().Before(deadline) {+ reply = relayAntigravityHook(t, getenv, preInvocation("conv-steer"))+ injected = injectedUserMessages(t, reply)+ time.Sleep(10 * time.Millisecond)+ }+ if len(injected) != 1 || injected[0] != "Prefer the smaller fix." {+ t.Fatalf("injected = %q", injected)+ }+ assertAntigravitySupplementWaiting(t, done)+ // agy appends the step's transcript record before it streams the step.+ content := "lint: 3 warnings"+ if wantDelivered {+ content = reply["injectSteps"].([]any)[0].(map[string]any)["userMessage"].(string)+ }+ record := antigravityUserInputRecord(t, 3, content) + "\n"+ if f, err := os.OpenFile(transcript, os.O_APPEND|os.O_WRONLY, 0o644); err != nil {+ t.Fatal(err)+ } else if _, err := f.WriteString(record); err != nil {+ t.Fatal(err)+ } else {+ f.Close()+ }+ if err := os.WriteFile(filepath.Join(cwd, "injected"), nil, 0o600); err != nil {+ t.Fatal(err)+ }+ if wantDelivered {+ if err := <-done; err != nil {+ t.Fatalf("Supplement = %v, want delivered", err)+ }+ } else {+ assertAntigravitySupplementWaiting(t, done)+ }+ if err := os.WriteFile(filepath.Join(cwd, "answer"), nil, 0o600); err != nil {+ t.Fatal(err)+ }+ if !wantDelivered {+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("Supplement = %v, want canceled at turn end so the daemon falls back", err)+ }+ }++ // The injected user_input step belongs to the turn, so a trailing transport+ // error after the final answer still recovers as completed.+ if result := <-session.Result; result.Status != "completed" {+ t.Fatalf("status = %q, error = %q", result.Status, result.Error)+ }+ if session.SupplementReady() {+ t.Fatal("ready after the terminal result")+ }+ if _, err := os.Stat(filepath.Join(cwd, ".agents", "hooks.json")); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("hooks.json after the run: %v, want removed", err)+ }+}++func TestAntigravityExecuteWithoutNegotiationInstallsNothing(t *testing.T) {+ t.Parallel()+ cwd := t.TempDir()+ script := `#!/bin/sh+printf '%s\n' "${MULTICA_ANTIGRAVITY_HOOK_URL:-unset}" > hook-env.txt+ls -a .agents > agents-dir.txt 2>&1 || true+printf '%s\n' '{"event":"init","conversation_id":"conv-plain","init":{}}'+printf '%s\n' '{"event":"result","result":{"conversation_id":"conv-plain","status":"SUCCESS","response":"done"}}'+`+ fakePath := filepath.Join(t.TempDir(), "agy")+ writeTestExecutable(t, fakePath, []byte(script))+ backend, err := New("antigravity", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatal(err)+ }+ session, err := backend.Execute(t.Context(), "goal", ExecOptions{+ Cwd: cwd, Timeout: 30 * time.Second, SupplementHookCommand: testAntigravityHookCommand,+ })+ if err != nil {+ t.Fatal(err)+ }+ for range session.Messages {+ }+ if result := <-session.Result; result.Status != "completed" {+ t.Fatalf("status = %q, error = %q", result.Status, result.Error)+ }+ if session.Supplement != nil || session.SupplementReady != nil {+ t.Fatal("unnegotiated run exposes supplement hooks")+ }+ if data, _ := os.ReadFile(filepath.Join(cwd, "hook-env.txt")); strings.TrimSpace(string(data)) != "unset" {+ t.Fatalf("hook env leaked into an unnegotiated run: %q", data)+ }+ if _, err := os.Stat(filepath.Join(cwd, ".agents")); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf(".agents created for an unnegotiated run: %v", err)+ }+}++func TestAntigravityExecuteWithUnmanagedHooksFailsSupplementsFast(t *testing.T) {+ t.Parallel()+ cwd := t.TempDir()+ path := filepath.Join(cwd, ".agents", "hooks.json")+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(`{"user":{}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ script := `#!/bin/sh+printf '%s\n' '{"event":"init","conversation_id":"conv-own-hooks","init":{}}'+while [ ! -f release ]; do sleep 0.02; done+printf '%s\n' '{"event":"result","result":{"conversation_id":"conv-own-hooks","status":"SUCCESS","response":"done"}}'+`+ fakePath := filepath.Join(t.TempDir(), "agy")+ writeTestExecutable(t, fakePath, []byte(script))+ backend, err := New("antigravity", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatal(err)+ }+ session, err := backend.Execute(t.Context(), "goal", ExecOptions{+ Cwd: cwd, Timeout: 30 * time.Second, EnableTaskSupplement: true, SupplementHookCommand: testAntigravityHookCommand,+ })+ if err != nil {+ t.Fatal(err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ if session.Supplement == nil || !session.SupplementReady() {+ t.Fatal("negotiated run must settle supplements instead of leaving them pending")+ }+ if err := session.Supplement(t.Context(), "guidance"); err == nil || !strings.Contains(err.Error(), "hooks unavailable") {+ t.Fatalf("Supplement = %v, want hooks-unavailable failure", err)+ }+ if err := os.WriteFile(filepath.Join(cwd, "release"), nil, 0o600); err != nil {+ t.Fatal(err)+ }+ if result := <-session.Result; result.Status != "completed" {+ t.Fatalf("status = %q, error = %q", result.Status, result.Error)+ }+ if data, _ := os.ReadFile(path); string(data) != `{"user":{}}` {+ t.Fatalf("user hooks.json changed: %s", data)+ }+}diff --git a/server/pkg/agent/cursor.go b/server/pkg/agent/cursor.goindex 7d883b6aa7..0b99453933 100644--- a/server/pkg/agent/cursor.go+++ b/server/pkg/agent/cursor.go@@ -63,7 +63,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptvar supplements *cursorSupplementSessionvar supplementErr errorif opts.EnableTaskSupplement {- supplements, supplementErr = startCursorSupplementSession(runCtx, opts.Cwd, opts.CursorHookCommand, b.cfg.Logger)+ supplements, supplementErr = startCursorSupplementSession(runCtx, opts.Cwd, opts.SupplementHookCommand, b.cfg.Logger)if supplementErr != nil {b.cfg.Logger.Warn("cursor additional messages unavailable for this run", "error", supplementErr)supplements = nildiff --git a/server/pkg/agent/cursor_supplement.go b/server/pkg/agent/cursor_supplement.goindex 324c31c715..7bba1aec8d 100644--- a/server/pkg/agent/cursor_supplement.go+++ b/server/pkg/agent/cursor_supplement.go@@ -3,9 +3,7 @@ package agentimport ("bytes""context"- "crypto/rand""crypto/subtle"- "encoding/hex""encoding/json""errors""fmt"@@ -14,13 +12,11 @@ import ("log/slog""net""net/http"- "net/url""os""path/filepath""slices""strings""sync"- "time""unicode/utf16")@@ -36,9 +32,7 @@ const (// 10,000 JavaScript string units.cursorHookContextLimit = 10000cursorHookTimeoutSeconds = 10- cursorHookRelayTimeout = 5 * time.SecondcursorHookRequestLimit = 64 << 10- cursorHookResponseLimit = 256 << 10cursorHookStdinLimit = 64 << 20cursorGuidanceTagPrefix = "[MULTICA-GUIDANCE nonce="cursorHookRelayEmptyReply = "{}"@@ -113,7 +107,7 @@ func startCursorSupplementSession(ctx context.Context, cwd string, hookCommand [if err != nil {return nil, err}- hooksData, err := cursorHooksFileData(cursorHookShellCommand(hookCommand))+ hooksData, err := cursorHooksFileData(hookShellCommand(hookCommand))if err != nil {return nil, err}@@ -134,7 +128,7 @@ func startCursorSupplementSession(ctx context.Context, cwd string, hookCommand [return nil, fmt.Errorf("listen for cursor hooks: %w", err)}s.url = "http://" + listener.Addr().String() + "/hook"- s.server = &http.Server{Handler: s, ReadHeaderTimeout: cursorHookRelayTimeout}+ s.server = &http.Server{Handler: s, ReadHeaderTimeout: hookRelayTimeout}go func() { _ = s.server.Serve(listener) }()return s, nil}@@ -431,16 +425,6 @@ func cursorHooksFileData(command string) ([]byte, error) {return append(data, '\n'), nil}-// cursorHookShellCommand quotes argv for the POSIX shell Cursor runs command-// hooks through.-func cursorHookShellCommand(argv []string) string {- quoted := make([]string, len(argv))- for i, arg := range argv {- quoted[i] = "'" + strings.ReplaceAll(arg, "'", `'\''`) + "'"- }- return strings.Join(quoted, " ")-}-// RunCursorHookRelay is the body of the Cursor hook command. It always prints// one JSON object and never fails the hook: a run without steering, a stale// hooks.json or an unreachable endpoint all answer "{}" so the tool call@@ -451,61 +435,14 @@ func RunCursorHookRelay(stdin io.Reader, stdout io.Writer, getenv func(string) s}func cursorHookRelay(stdin io.Reader, getenv func(string) string) string {- endpoint, token := getenv(cursorHookURLEnv), getenv(cursorHookTokenEnv)- if endpoint == "" || token == "" || !loopbackHTTPURL(endpoint) {- return cursorHookRelayEmptyReply- }var req cursorHookRequestif err := json.NewDecoder(io.LimitReader(stdin, cursorHookStdinLimit)).Decode(&req); err != nil {return cursorHookRelayEmptyReply}- body, err := json.Marshal(req)- if err != nil {- return cursorHookRelayEmptyReply- }- ctx, cancel := context.WithTimeout(context.Background(), cursorHookRelayTimeout)- defer cancel()- httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))- if err != nil {- return cursorHookRelayEmptyReply- }- httpReq.Header.Set("Authorization", "Bearer "+token)- httpReq.Header.Set("Content-Type", "application/json")- client := &http.Client{Transport: &http.Transport{Proxy: nil}}- resp, err := client.Do(httpReq)- if err != nil {- return cursorHookRelayEmptyReply- }- defer resp.Body.Close()- data, err := io.ReadAll(io.LimitReader(resp.Body, cursorHookResponseLimit))- if err != nil || resp.StatusCode != http.StatusOK {- return cursorHookRelayEmptyReply- }- var output map[string]any- if json.Unmarshal(data, &output) != nil || output == nil {- return cursorHookRelayEmptyReply- }- return string(bytes.TrimSpace(data))-}--func loopbackHTTPURL(raw string) bool {- u, err := url.Parse(raw)- if err != nil || u.Scheme != "http" {- return false- }- ip := net.ParseIP(u.Hostname())- return ip != nil && ip.IsLoopback()+ return forwardHookRequest(getenv(cursorHookURLEnv), getenv(cursorHookTokenEnv), req, cursorHookRelayEmptyReply)}// jsStringLength counts UTF-16 code units, the unit of Cursor's length cap.func jsStringLength(s string) int {return len(utf16.Encode([]rune(s)))}--func randomHex(n int) (string, error) {- buf := make([]byte, n)- if _, err := rand.Read(buf); err != nil {- return "", fmt.Errorf("generate random token: %w", err)- }- return hex.EncodeToString(buf), nil-}diff --git a/server/pkg/agent/cursor_supplement_integration_test.go b/server/pkg/agent/cursor_supplement_integration_test.goindex 9c4a7f4920..10ca89b2f0 100644--- a/server/pkg/agent/cursor_supplement_integration_test.go+++ b/server/pkg/agent/cursor_supplement_integration_test.go@@ -43,10 +43,10 @@ func TestCursorRealSupplementReachesTheTurn(t *testing.T) {session, err := backend.Execute(ctx,"Run `sleep 5 && echo step-one` in the shell. After it finishes, run `echo step-two` in the shell. Then reply with a one-line summary.",ExecOptions{- Cwd: t.TempDir(),- Timeout: 230 * time.Second,- EnableTaskSupplement: true,- CursorHookCommand: []string{relay, CursorHookHelperArg},+ Cwd: t.TempDir(),+ Timeout: 230 * time.Second,+ EnableTaskSupplement: true,+ SupplementHookCommand: []string{relay, CursorHookHelperArg},})if err != nil {t.Fatalf("execute: %v", err)diff --git a/server/pkg/agent/cursor_supplement_unix_test.go b/server/pkg/agent/cursor_supplement_unix_test.goindex ede36663ed..286223bc5a 100644--- a/server/pkg/agent/cursor_supplement_unix_test.go+++ b/server/pkg/agent/cursor_supplement_unix_test.go@@ -32,10 +32,10 @@ printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"dt.Fatalf("New(cursor): %v", err)}session, err := backend.Execute(t.Context(), "original goal", ExecOptions{- Cwd: cwd,- Timeout: 30 * time.Second,- EnableTaskSupplement: true,- CursorHookCommand: testCursorHookCommand,+ Cwd: cwd,+ Timeout: 30 * time.Second,+ EnableTaskSupplement: true,+ SupplementHookCommand: testCursorHookCommand,})if err != nil {t.Fatalf("Execute: %v", err)@@ -146,7 +146,7 @@ printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"dt.Fatalf("New(cursor): %v", err)}session, err := backend.Execute(t.Context(), "original goal", ExecOptions{- Cwd: cwd, Timeout: 30 * time.Second, CursorHookCommand: testCursorHookCommand,+ Cwd: cwd, Timeout: 30 * time.Second, SupplementHookCommand: testCursorHookCommand,})if err != nil {t.Fatalf("Execute: %v", err)@@ -195,10 +195,10 @@ printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"dt.Fatalf("New(cursor): %v", err)}session, err := backend.Execute(t.Context(), "original goal", ExecOptions{- Cwd: cwd,- Timeout: 30 * time.Second,- EnableTaskSupplement: true,- CursorHookCommand: testCursorHookCommand,+ Cwd: cwd,+ Timeout: 30 * time.Second,+ EnableTaskSupplement: true,+ SupplementHookCommand: testCursorHookCommand,})if err != nil {t.Fatalf("Execute: %v", err)diff --git a/server/pkg/agent/hook_relay.go b/server/pkg/agent/hook_relay.gonew file mode 100644index 0000000000..4ae11a7dec--- /dev/null+++ b/server/pkg/agent/hook_relay.go@@ -0,0 +1,89 @@+package agent++import (+ "bytes"+ "context"+ "crypto/rand"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/url"+ "strings"+ "time"+)++// Hook-based steering (Cursor, Antigravity) shares one transport: the agent+// CLI runs the multica binary as a hook command, and that relay forwards the+// ownership fields of the hook payload to the run's token-protected loopback+// endpoint, then prints the endpoint's reply as the hook output.+const (+ hookRelayTimeout = 5 * time.Second+ hookRelayResponseLimit = 1 << 20+)++// forwardHookRequest posts req to the run's endpoint and returns the reply+// object it should print. Every failure — no steering for this run, a stale+// hooks file, an unreachable endpoint — returns empty, so the hook never+// changes what the agent does.+func forwardHookRequest(endpoint, token string, req any, empty string) string {+ if endpoint == "" || token == "" || !loopbackHTTPURL(endpoint) {+ return empty+ }+ body, err := json.Marshal(req)+ if err != nil {+ return empty+ }+ ctx, cancel := context.WithTimeout(context.Background(), hookRelayTimeout)+ defer cancel()+ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))+ if err != nil {+ return empty+ }+ httpReq.Header.Set("Authorization", "Bearer "+token)+ httpReq.Header.Set("Content-Type", "application/json")+ client := &http.Client{Transport: &http.Transport{Proxy: nil}}+ resp, err := client.Do(httpReq)+ if err != nil {+ return empty+ }+ defer resp.Body.Close()+ data, err := io.ReadAll(io.LimitReader(resp.Body, hookRelayResponseLimit))+ if err != nil || resp.StatusCode != http.StatusOK {+ return empty+ }+ var output map[string]any+ if json.Unmarshal(data, &output) != nil || output == nil {+ return empty+ }+ return string(bytes.TrimSpace(data))+}++// hookShellCommand quotes argv for the POSIX shell agent CLIs run command+// hooks through.+func hookShellCommand(argv []string) string {+ quoted := make([]string, len(argv))+ for i, arg := range argv {+ quoted[i] = "'" + strings.ReplaceAll(arg, "'", `'\''`) + "'"+ }+ return strings.Join(quoted, " ")+}++func loopbackHTTPURL(raw string) bool {+ u, err := url.Parse(raw)+ if err != nil || u.Scheme != "http" {+ return false+ }+ ip := net.ParseIP(u.Hostname())+ return ip != nil && ip.IsLoopback()+}++func randomHex(n int) (string, error) {+ buf := make([]byte, n)+ if _, err := rand.Read(buf); err != nil {+ return "", fmt.Errorf("generate random token: %w", err)+ }+ return hex.EncodeToString(buf), nil+}diff --git a/server/pkg/agent/version.go b/server/pkg/agent/version.goindex a14a00d02c..66c0d8b810 100644--- a/server/pkg/agent/version.go+++ b/server/pkg/agent/version.go@@ -153,6 +153,11 @@ func SupportsTaskSupplement(provider, version string) bool {// into the running ACP turn (queued, then injected at the next// tool/message boundary of the same session/prompt).minimum = "2.33.0"+ case "antigravity":+ // 1.4.8 is the oldest agy verified to append PreInvocation injectSteps+ // userMessage entries to the running turn and to report each as a+ // user_input step on the stream-json output.+ minimum = "1.4.8"case "cursor":// 2026.10.14 is the oldest build verified to forward postToolUse// additional_context into the model turn in --print mode.diff --git a/server/pkg/agent/version_test.go b/server/pkg/agent/version_test.goindex 2ffd397e3b..dbee1efc55 100644--- a/server/pkg/agent/version_test.go+++ b/server/pkg/agent/version_test.go@@ -15,6 +15,7 @@ func TestTaskSupplementVersionGate(t *testing.T) {{"claude", "2.1.110 (Claude Code)", true}, {"claude", "2.1.109", false},{"grok", "1.0.14", true}, {"grok", "1.0.13", false}, {"grok", "0.2.120", false},{"cursor", "2026.10.16-e3cb207", true}, {"cursor", "2026.10.14", true}, {"cursor", "2026.04.17-787b533", false},+ {"antigravity", "1.4.8", true}, {"antigravity", "agy 1.5.13", true}, {"antigravity", "1.4.7", false}, {"antigravity", "", false},{"kiro", "kiro-cli 2.33.0", true}, {"kiro", "2.34.1", true}, {"kiro", "kiro-cli 2.32.9", false},{"codex", "", false}, {"claude", "dev", false}, {"kimi", "9.0.0", false},} {