Skip to content
Merged
21 changes: 21 additions & 0 deletions pkgs/mcpx/docs/exec.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,27 @@ frame it may have replaced (its frame carries the original when it changed
the value), and a `suffix` hook frame follows the outcome, before `end`. A
replaced error produces no `error` frame at all.

A hook entry declares exactly one action. `script` is the deterministic
action above. `prompt` is the model-backed one (#1929 Approach C, first
slice): the entry's `prompt` text is sent to the configured model provider
(`model.provider` and friends, resolved per request on the daemon, from
the same settings for a local CLI run), with `effect` defaulting to
`advise` — the only effect this slice implements; `ask`, `propose`,
`apply` and `run` are refused at validation rather than silently
downgraded. `@placeholders` in the prompt text — the built-ins `@result`,
`@error`, `@diagnostic`, `@calls`, `@artifacts`, `@source`, plus the
call's own placeholder values — are substituted JSON-encoded, as data,
never as raw text. The provider's answer rides the hook frame as
`advice`, with `model` and `provider` naming what answered; advice never
transforms the result or the error, in any phase. When no provider is
configured, or the provider errors, the frame instead carries
`error: "advice unavailable: …"` and the run continues deterministically
— a prompt hook can slow a run down by its timeout, but it cannot change
or fail it. A per-hook `model` names the model to ask, in the
provider/model namespace. Prompt hooks are declared in the same lists as
script hooks — the config `hooks` entries and a call's `options.hooks` —
and run in declaration order among them.

Artifact **metadata** comes before `end`; artifact **bodies** come strictly
after it. That is the whole point of the design, and it is step 5 of the
issue: a streaming consumer reads the emits and the return value, decides it
Expand Down
11 changes: 10 additions & 1 deletion pkgs/mcpx/internal/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -1166,7 +1166,7 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error {
if derr != nil {
return derr
}
svc := a.localService(store, c.Socket())
svc := a.localService(store, c.Socket(), cfg)
wire := execsvc.Options{
Session: sessionKey,
Output: eo.Output,
Expand Down Expand Up @@ -1242,6 +1242,7 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error {
}
} else if eo.Output != execsvc.OutputStream {
a.reportArtifacts(res)
a.reportHooks(res)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Render hook advice on the remote CLI text path too

For mcpx exec --remote or mcpx run --remote using default text output, configured prompt hooks invoke the model but their advice and warnings still disappear. This new reportHooks call only covers local execution: the remote branch returns earlier through execOnDaemon, then execRemote and renderExecResult, whose text branch prints stdout, emits and artifacts without inspecting res.Hooks. Call the helper from that shared remote renderer too, so remote text callers receive the prompt hook's output rather than paying for advice they cannot see.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9b39a59: renderExecResult's text branch now calls reportHooks next to reportArtifacts, so mcpx exec --remote / mcpx run --remote text callers receive prompt-hook advice and warnings from the retained frames. That renderer is the shared remote path (execRemote and the serve/call renderers go through it); its JSON/structured branch already marshals res with hooks included, and the stream path echoes hook frames as they arrive.

}
if res.ExitCode != 0 {
return &exitStatusError{code: res.ExitCode}
Expand Down Expand Up @@ -1272,6 +1273,14 @@ func runEnvelope(res *execsvc.Result, stdout string, logs []logging.Record, stre
// reading the structured Result (Codex review, PR #9205).
env["errorKind"] = res.ErrorKind
}
// Retained hook frames ride in the envelope: a prompt hook's
// advice and warnings live only in its frame, and this path
// runs with a nil sink, so without this a --json caller paid
// for a model call whose entire effect was discarded (Codex
// review, PR #9021).
if len(res.Hooks) > 0 {
env["hooks"] = res.Hooks
}
if res.StdoutTruncated {
env["stdoutTruncated"] = true
}
Expand Down
66 changes: 64 additions & 2 deletions pkgs/mcpx/internal/cli/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ import (
"time"

"github.com/developing-today/code/pkgs/mcpx/internal/artifacts"
"github.com/developing-today/code/pkgs/mcpx/internal/config"
"github.com/developing-today/code/pkgs/mcpx/internal/execsvc"
"github.com/developing-today/code/pkgs/mcpx/internal/model"
"github.com/developing-today/code/pkgs/mcpx/internal/settings"
)

// execOptions is what the exec and run commands resolved from their flags,
Expand Down Expand Up @@ -172,7 +175,7 @@ func (a *App) localStore() (*artifacts.Store, error) {
// has launchers, phases and a typecheck mode that the wire Options
// deliberately do not mirror. Everything after the process starts is the
// shared implementation.
func (a *App) localService(store *artifacts.Store, socket string) *execsvc.Service {
func (a *App) localService(store *artifacts.Store, socket string, cfg *config.Config) *execsvc.Service {
set := a.Settings()
lim := execsvc.DefaultLimits()
lim.Interpreter = set.String("script.interpreter")
Expand All @@ -182,7 +185,7 @@ func (a *App) localService(store *artifacts.Store, socket string) *execsvc.Servi
lim.ChunkBytes = set.Bytes("artifacts.chunkBytes")
lim.InterceptImages = set.Bool("artifacts.interceptImages")
lim.StdoutLimit = set.Bytes("exec.maxOutputBytes")
return &execsvc.Service{
svc := &execsvc.Service{
Store: store,
// The script runs in this process's machine, and the daemon whose
// store it is has to be the same one for a path to mean anything to
Expand All @@ -191,6 +194,44 @@ func (a *App) localService(store *artifacts.Store, socket string) *execsvc.Servi
Local: socket != "",
Limits: lim,
}
// Prompt hooks (#5276) on a local run resolve through the same
// configured model layer the daemon uses, minus the broker samplers
// only a daemon can offer. model.provider=none (the default)
// resolves to (nil, nil): no behaviour change for a user who
// configures nothing, and a prompt hook reports advice unavailable.
if prov, merr := model.Resolve(model.Config{
Provider: set.String("model.provider"),
BaseURL: set.String("model.baseURL"),
APIKeyEnv: set.String("model.apiKeyEnv"),
ProviderSettingsJSON: set.String("model.providers"),
ProfilesJSON: set.String("model.profiles"),
DefaultModel: set.String("model.default"),
Timeout: set.Duration("model.timeout"),
}); merr != nil {
svc.ModelProviderErr = merr
} else {
svc.ModelProvider = prov
}
// The same token cap the daemon resolves (prompt.maxTokens
// bounded by model.budget), so a local run's prompt hooks run
// under the operator's ceiling too (Codex review, PR #9021).
svc.ModelMaxTokens = execsvc.ModelTokenCap(set.Int("prompt.maxTokens"), set.Int("model.budget"))
// The configured default model, for a prompt hook that names
// none of its own (see execsvc.Service.ModelDefault).
svc.ModelDefault = set.String("model.default")
// Config-declared hooks apply to local runs exactly as they do
// to daemon runs: without this the service's Hooks stayed empty
// and a prompt (or script) entry in script.hooks was silently
// ignored on the default local path, provider or not (Codex
// review, PR #9021). Configured code is gated by hooks.autonomy
// exactly as the daemon gates it and as hookGate gates the
// legacy phases: below `run` it does not execute.
if cfg != nil && settings.AutonomyAtLeast(set.String("hooks.autonomy"), "run") {
for _, h := range cfg.ScriptHooks() {
svc.Hooks = append(svc.Hooks, execsvc.Hook{Phase: h.Phase, Script: h.Script, Prompt: h.Prompt, Effect: h.Effect, Model: h.Model, Name: h.Name})
Comment on lines +230 to +231

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Surface prompt-hook advice in local CLI output

For local mcpx exec or mcpx run with configured prompt hooks and hooks.autonomy=run, the hooks now invoke the provider, but default text output and --json still discard their advice and warnings. In commands.go, the text path leaves the sink nil and only reports artifacts afterward; the JSON path also uses a nil sink and builds its response through runEnvelope, which never copies res.Hooks. Consequently, these calls incur model latency and cost without delivering the prompt hook's sole effect. Include retained hook frames in the JSON envelope and render advice/warnings on the text path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in db22dac: runEnvelope now carries res.Hooks as the envelope's hooks key when a run produced frames (pinned by TestRunEnvelopeCarriesHooks, including the no-hooks/no-key case), so the --json path delivers advice and warnings. The default text path now calls reportHooks alongside reportArtifacts: retained frames render to stderr as "mcpx: hook advice (phase): ..." / "mcpx: hook warning (phase): ...", keeping stdout as the script's own answer. The stream path already encodes hook frames live, and the structured path marshals res itself, hooks included.

Comment on lines +229 to +231

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Collect local tool calls before enabling call-aware prompt hooks

For local mcpx exec or mcpx run with an outcome prompt referencing @calls, these hooks receive [] even when the script successfully called tools. localService never initializes svc.Calls, and RunWith populates its call snapshot only inside if s.Calls != nil; the actual calls execute through the separate daemon, with no forwarding into this local service. Consequently, the newly enabled local hooks can generate advice based on a false empty call history. Forward the run's daemon call records into the local hook context rather than presenting an uncollected history as no calls.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed in this PR -- deferred with reason, split to issue #9349. The local path has no collection surface to forward from: execsvc.CallRegistry is a live, in-process, per-run sink registry (no retention, no query API), and a local run's tool calls are reported to the DAEMON process's registry via X-Mcpx-Run -- a different process from the CLI's localService, which never sees them. Populating @Calls locally therefore needs a new cross-process surface (daemon retention plus a run-calls query the CLI fetches before outcome hooks, or client-side reporting back into the local process): a design addition beyond this advise-hooks slice, and rushing it here would risk the exec paths this PR just stabilised. Daemon runs are unaffected (routes_exec stamps the shared registry; their @Calls is populated). Issue #9349 records the root cause, the design options, and the acceptance bar, including that an uncollected history must not be presented as an empty one. -- queue task 9174, lane any-c

}
}
return svc
Comment on lines +218 to +234

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Forward configured prompt hooks to the local CLI service

For a local mcpx exec or mcpx run with a prompt entry in script.hooks, resolving the provider here never results in the hook running: localService leaves svc.Hooks empty, and the caller in commands.go constructs execsvc.Options without Hooks. The existing ScriptPhase plumbing reads the separate legacy phase fields, not script.hooks; a search across internal/cli found no ScriptHooks conversion or hook-list assignment. Consequently, the newly documented config-declared prompt hooks are silently ignored on the default local execution path, even with a configured provider and hooks.autonomy=run. Populate the local service's hook list from the resolved configuration under the autonomy gate.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e819507: localService (internal/cli/exec.go) now takes the run's config and populates svc.Hooks from cfg.ScriptHooks(), gated by hooks.autonomy at run exactly as the daemon gates config-declared hooks in routes_exec.go and as hookGate gates the legacy phases. The sole caller in commands.go passes its resolved cfg. Local mcpx exec / mcpx run runs now execute config-declared prompt (and script) hooks instead of silently ignoring script.hooks.

}

// ---- the remote path ----
Expand Down Expand Up @@ -376,6 +417,10 @@ func (a *App) renderExecResult(res *execsvc.Result, eo execOptions) error {
_, _ = fmt.Fprint(os.Stdout, res.Stdout)
}
a.reportArtifacts(res)
// The remote text path renders hooks too: this renderer is
// shared by every remote caller, and a prompt hook's advice
// lives only in its retained frame (Codex review, PR #9021).
a.reportHooks(res)
}
if res.Error != "" && res.ExitCode == 0 {
return errors.New(res.Error)
Expand Down Expand Up @@ -475,6 +520,23 @@ func (a *App) reportArtifacts(res *execsvc.Result) {
}
}

// reportHooks renders retained hook frames on the text path, to
// stderr like reportArtifacts: stdout is the script's own answer,
// and a prompt hook's advice (or its provider-unavailable warning)
// would otherwise be generated and silently discarded on a local
// run (Codex review, PR #9021). The stream path already encodes
// hook frames as they happen, and the structured/JSON paths carry
// res.Hooks in the document itself.
func (a *App) reportHooks(res *execsvc.Result) {
for _, f := range res.Hooks {
if f.Advice != "" {
fmt.Fprintf(os.Stderr, "mcpx: hook advice (%s): %s\n", f.Phase, f.Advice)
} else if f.Error != "" {
fmt.Fprintf(os.Stderr, "mcpx: hook warning (%s): %s\n", f.Phase, f.Error)
}
}
}

// stream issues a request and hands back the live response.
//
// do() reads the whole body, which is right for every other call and wrong
Expand Down
19 changes: 19 additions & 0 deletions pkgs/mcpx/internal/cli/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,3 +327,22 @@ func TestRunRestoresPlumbingSource(t *testing.T) {
t.Fatal("Run left its App installed as the plumbing source; later in-process clients would inherit its settings")
}
}

// Codex P2 (PR #9021): the --json envelope carries retained hook
// frames, so a prompt hook's advice reaches a JSON caller instead
// of being generated and discarded.
func TestRunEnvelopeCarriesHooks(t *testing.T) {
res := &execsvc.Result{Stdout: "hi", Hooks: []execsvc.HookFrame{
{On: "script", Phase: "onSuccess", Action: "prompt", Effect: "advise", Advice: "cache it"},
{On: "script", Phase: "onError", Action: "prompt", Effect: "advise", Error: "advice unavailable: no model provider is configured"},
}}
env := runEnvelope(res, res.Stdout, nil, nil)
hooks, ok := env["hooks"].([]execsvc.HookFrame)
if !ok || len(hooks) != 2 || hooks[0].Advice != "cache it" || hooks[1].Error == "" {
t.Fatalf("envelope hooks = %#v", env["hooks"])
}
bare := runEnvelope(&execsvc.Result{Stdout: "hi"}, "hi", nil, nil)
if _, present := bare["hooks"]; present {
t.Fatal("a run with no hooks must not gain a hooks key")
}
}
37 changes: 35 additions & 2 deletions pkgs/mcpx/internal/cli/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,23 @@ func (b mcpBackend) execOptions(ctx context.Context, timeoutSec int) execsvc.Opt
return opts
}

// hookAdviceText renders the retained hook frames a prompt hook left
// on the result — its advice, or the warning that no provider could
// answer — one line per frame, the same selection reportHooks makes
// for the CLI text path. Script hooks carry neither field and render
// nothing.
func hookAdviceText(res execsvc.Result) string {
var lines []string
for _, f := range res.Hooks {
if f.Advice != "" {
lines = append(lines, "hook advice ("+f.Phase+"): "+f.Advice)
} else if f.Error != "" {
lines = append(lines, "hook warning ("+f.Phase+"): "+f.Error)
}
}
return strings.Join(lines, "\n")
}

// renderExec turns a script's result into mcpx_exec's tool result. Shared by
// the direct path and the interruptible one (serve_ask.go), so a script
// answered inline renders exactly like one that was never asked anything.
Expand All @@ -305,11 +322,20 @@ func renderExec(res execsvc.Result) (string, error) {
}
sb.WriteString(res.Stdout)
text := strings.TrimRight(sb.String(), "\n")
// Prompt-hook advice is the hook's sole output, and an MCP caller
// has no stderr for it to ride on (reportHooks' channel): without
// this the model runs and its answer silently disappears on both
// the direct and the interruptible path (Codex review, PR #9021).
hooks := hookAdviceText(res)
if res.Error != "" {
parts := []string{res.Error}
if text != "" {
return "", fmt.Errorf("%s\n\n%s", res.Error, text)
parts = append(parts, text)
}
return "", errors.New(res.Error)
if hooks != "" {
parts = append(parts, hooks)
}
return "", errors.New(strings.Join(parts, "\n\n"))
}
// A hook may have replaced the result after the script ran -- an
// onSuccess transform, or an onError recovery for a script that
Expand All @@ -336,6 +362,13 @@ func renderExec(res execsvc.Result) (string, error) {
}
}
}
if hooks != "" {
if text != "" {
text += "\n\n" + hooks
} else {
text = hooks
}
}
if text == "" && len(res.Artifacts) == 0 {
return "(the script printed nothing; use console.log or emit to return a value)", nil
}
Expand Down
40 changes: 40 additions & 0 deletions pkgs/mcpx/internal/cli/serve_hooks_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package cli

import (
"strings"
"testing"

"github.com/developing-today/code/pkgs/mcpx/internal/execsvc"
)

// Oracle: a prompt hook's advice is its sole output, and mcpx_exec's
// tool result is the only channel an MCP caller has — renderExec
// must carry retained advice and provider warnings in the rendered
// result (and in the error text on a failed run) without displacing
// the script's own outcome (Codex review, PR #9021).
func TestRenderExecCarriesHookAdvice(t *testing.T) {
hooks := []execsvc.HookFrame{
{Phase: "onSuccess", Action: "prompt", Advice: "cache the lookup"},
{Phase: "onError", Action: "prompt", Error: "no model provider configured"},
}

out, err := renderExec(execsvc.Result{Stdout: "answer\n", Hooks: hooks})
if err != nil {
t.Fatalf("renderExec: %v", err)
}
for _, want := range []string{"answer", "hook advice (onSuccess): cache the lookup", "hook warning (onError): no model provider configured"} {
if !strings.Contains(out, want) {
t.Fatalf("rendered result missing %q:\n%s", want, out)
}
}

_, err = renderExec(execsvc.Result{Error: "boom", Hooks: hooks})
if err == nil || !strings.Contains(err.Error(), "boom") || !strings.Contains(err.Error(), "cache the lookup") {
t.Fatalf("error path dropped hook advice: %v", err)
}

out, err = renderExec(execsvc.Result{Hooks: hooks})
if err != nil || !strings.Contains(out, "cache the lookup") {
t.Fatalf("advice-only result = %q, %v", out, err)
}
}
29 changes: 23 additions & 6 deletions pkgs/mcpx/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -414,10 +414,14 @@ type ScriptConfig struct {
Hooks []any `json:"hooks,omitempty"`
}

// HookConfig is one resolved hook: a phase and the script that runs in it.
// HookConfig is one resolved hook: a phase and the one action that runs
// in it — a script, or a prompt with its declared effect and model.
type HookConfig struct {
Phase string `json:"phase"`
Script string `json:"script"`
Prompt string `json:"prompt,omitempty"`
Effect string `json:"effect,omitempty"`
Model string `json:"model,omitempty"`
Name string `json:"name,omitempty"`
}

Expand Down Expand Up @@ -458,13 +462,17 @@ func ResolveHooks(layers [][]any) []HookConfig {
}

// hookEntry decodes one element of a hooks list. An entry that names no phase
// or no script is dropped here rather than failing every run of the config: it
// is the one defect a config can carry that would otherwise break unrelated
// work.
// or no action (script or prompt) is dropped here rather than failing every
// run of the config: it is the one defect a config can carry that would
// otherwise break unrelated work.
func hookEntry(el any) (HookConfig, bool) {
usable := func(h HookConfig) bool {
return h.Phase != "" &&
(strings.TrimSpace(h.Script) != "" || strings.TrimSpace(h.Prompt) != "")
}
switch v := el.(type) {
case HookConfig:
if v.Phase == "" || strings.TrimSpace(v.Script) == "" {
if !usable(v) {
return HookConfig{}, false
}
return v, true
Expand All @@ -476,10 +484,19 @@ func hookEntry(el any) (HookConfig, bool) {
if s, ok := v["script"].(string); ok {
h.Script = s
}
if s, ok := v["prompt"].(string); ok {
h.Prompt = s
}
if s, ok := v["effect"].(string); ok {
h.Effect = s
}
if s, ok := v["model"].(string); ok {
h.Model = s
}
if s, ok := v["name"].(string); ok {
h.Name = s
}
if h.Phase == "" || strings.TrimSpace(h.Script) == "" {
if !usable(h) {
return HookConfig{}, false
}
return h, true
Expand Down
27 changes: 27 additions & 0 deletions pkgs/mcpx/internal/config/hooks_prompt_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package config

import "testing"

// A config-declared hook may carry a prompt action (#5276): the entry is
// usable with a prompt and no script, and its effect/model survive
// resolution. An entry with no action at all is still dropped.
func TestResolveHooksPromptEntry(t *testing.T) {
got := ResolveHooks([][]any{{
map[string]any{
"phase": "onSuccess", "prompt": "advise on @result",
"effect": "advise", "model": "openai/gpt-5", "name": "reviewer",
},
map[string]any{"phase": "before", "script": "prep.ts"},
map[string]any{"phase": "suffix"},
}})
if len(got) != 2 {
t.Fatalf("resolved %d hooks, want 2 (the actionless entry dropped): %+v", len(got), got)
}
p := got[0]
if p.Prompt != "advise on @result" || p.Effect != "advise" || p.Model != "openai/gpt-5" || p.Name != "reviewer" {
t.Fatalf("prompt hook mangled in resolution: %+v", p)
}
if got[1].Script != "prep.ts" {
t.Fatalf("script hook mangled in resolution: %+v", got[1])
}
}
8 changes: 8 additions & 0 deletions pkgs/mcpx/internal/daemon/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,14 @@ func (s *Server) brokerSamplerFor(session string, provider string) model.SampleF
if err != nil {
return model.Response{}, err
}
// When this request runs inside an interruptible ask call (a
// prompt hook during /v1/ask kind: exec), record the question
// on that call too: the host driving the call answers through
// its ask poll, which only exposes questions the call carries,
// so unattached the hook waited out its timeout unanswered
// (Codex review, PR #9021). Outside an ask call this is a
// no-op; the broker's own answerers remain the route, as before.
s.reg.attachSample(ctx, question, params)
// Publish the lifecycle before waiting, as the upstream
// sampling path does (hooks.go): a sample.opened hook is how
// an event-driven answerer learns there is a question to
Expand Down
Loading
Loading