Skip to content

Commit 5f9151f

Browse files
committed
A task subagent keeps its tools when its parent was once on Deny
opencode seeds a task subagent with the parent session's deny rules only, not the allows after them, and hides a tool when the last rule naming it is a *-pattern deny. Rules are append-only, so a session that was on Deny once (even for a second) kept that block's '* * deny' for life, and every child it spawned sent its first request with no tools at all until galopin's own rules for the child landed: the model could only answer in text, and a background child ended there (anomalyco/opencode#45078). Every composed block now opens with a deny that can never apply ('*' / '<galopin:subagent-tools-visible>'): children inherit it after every older block, so their tools stay visible; it decides no call, changes nothing for the session that owns the block, and later denies (machine rules, the ceiling, the Deny word) still hide their tools. permission.rules leaves it out. Existing sessions pick it up on their next prompt. session.get also reports the model a subagent actually runs on (its newest assistant message's), so the panel stops naming the machine's default for it. The mock LLM records each request's tool list for the new IT.
1 parent ff832ca commit 5f9151f

13 files changed

Lines changed: 438 additions & 8 deletions

‎agent/PROTOCOL.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,8 @@ _How they are applied._ (1) At `session.create` the session is created **with**
178178

179179
_Growth of a session's rule list (measured on 1.18.34, decided to leave as is)._ `PATCH /session/:id {permission}` only appends: the handler (`packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts`, `update`) sets `Permission.merge(current.permission ?? [], payload)`, and `merge` is a plain concatenation with no de-duplication. No endpoint, flag or `null` replaces a session's rules; the one replacing path is the deprecated per-prompt `tools` map (`session/prompt.ts`: `session.permission = <allow/deny * per tool>`), which galopin never sends (above) and which only runs inside a turn, so it cannot be used to reset then re-send. Every word change, new or removed exception, coordination grant or ceiling change therefore adds one whole composed block (about 100-150 rules; a session whose rules never change gets one). The list is not unbounded in effect, only in size: every block starts with `* * <word>`, which matches every input, so opencode's last-match-wins (`Permission.evaluate` is `findLast`) stops inside the newest block and the older ones are dead weight for evaluation. Cost, measured against a scratch opencode 1.18.34 and the mock LLM: a write-tool turn took 0.69 s with 146 rules, 0.44 s with 1,646, 0.57 s with 5,146 and 1.35 s with 20,146 (noise dominates up to a few thousand; only the extreme shows); the session record grows with the list, 13.8 KB at 146 rules, 117 KB at 1,646, 357 KB at 5,146 and 1.38 MB at 20,146 (about 70 bytes a rule), and opencode publishes the whole record on every session update. Sending only a delta was considered and not built: the rules are wildcard patterns, so "the rules whose effective action changed" is not enumerable, and a suffix delta equals the full block only when nothing in the older block's changed part still matches an input the delta does not, which cannot be proved for arbitrary agent and machine rules. A wrong delta silently softens a deny; a large session record only costs bytes. A session that has grown too large can be replaced by a new one.
180180

181+
_A task subagent keeps its tools (the tool-visibility sentinel)._ opencode seeds a task subagent's session with the parent session's **deny** rules only (`deriveSubagentSessionPermission`), not the allows that came after them, and hides a tool from a request when the last rule naming it, pattern ignored, is a `*`-pattern deny (`Permission.disabled`). With append-only rules, a parent that was once on Deny keeps that block's `* * deny` for life, so every child it spawned started with **every tool hidden** until galopin's own rules for the child landed; a first step can beat them by a few hundred milliseconds, and a background child has no second step, so it answered in text and ended (upstream: anomalyco/opencode#45078). galopin therefore opens every composed block with one deny that can never apply, `{"*", "<galopin:subagent-tools-visible>", "deny"}`: the child inherits it after every older block, so it is the last rule the visibility check sees for each tool, and its pattern is not `*`, so the tool stays visible. It decides no call (no wildcard, one token, no real command or path equals it), changes nothing for the session that owns the block (the block's own `* * <word>` follows it), and a deny later in the block — a machine rule, the ceiling's tail, the Deny word — still hides its tool in the child. `permission.rules` leaves it out. A session picks it up on its next prompt (its composed rules' fingerprint changes), so sessions poisoned before this release recover without a reset.
182+
181183
_`session_read` / `session_spawn` / `session_send`._ They have no opencode permission, so galopin looks the tool's name up in the asking session's rules (the agent's, then the session's; the machine's own rule for the name survives the selector under Ask and Allow, and Deny refuses): `allow` → no card unless the spawn is an escalation (the result carries `autoApproved:true`, the badge reads **allowed by the permission rules**), `deny` → refused with no card and none of the rate budget spent, `ask` or no rule → a `gp_` card. A **wildcard allow never grants a read** — opencode's default `"*": allow` would otherwise let any session read any transcript — **but under the Allow word it grants a spawn or a send**, like any other tool (the reads stay grant-gated because a transcript can hold secrets) — while a wildcard deny refuses them. An allow does not lift the hard limits: a send or a read into another workspace, or a send at hop 4 or more, is still carried by a card; the per-pair rate limits still refuse. "Always" on a `gp_` card is "once" and the card offers none; the Allow word never answers one.
182184

183185
_Coordination grant (`session.grantCoordination`, capability `coordinationGrant`)._ A scheduled run has nobody to answer a card, and no op can write a rule (`session.setRules` is retired), so the grant is the one narrow thing a client may write: `{sessionId, keys}` with `keys` drawn from `session_list`, `session_read`, `session_send`, `session_spawn` and nothing else (`invalid` otherwise, nothing recorded). galopin keeps it on the ROOT session inside the same record as the selector (the session overlay, `coordination`), so it **survives a restart** like an exception does, and composes it as one `allow` per key **after the mode block and before the machine's own rules for the tools** — and so beneath the ceiling's tail, which is last. What that makes of it:
@@ -273,6 +275,9 @@ Directory = {path, name, isGitRepo: bool}
273275
Session = {id, workspaceId, backend, title, status: "idle"|"busy"|"retry"|"error", pendingPermissions: number,
274276
modeId|null, modelId|null, effort?, permissionMode?: "deny"|"ask"|"allow", parentId|null, rootId?, childSummary?, spawnedBy?,
275277
createdAt, updatedAt, usage: Usage|null}
278+
// modelId: the model a person chose for the session ("<provider>/<model>"), null when
279+
// none was; on session.get a subagent (parentId set), which has no choice of its own,
280+
// reports the model its newest assistant message ran on (null before its first).
276281
// rootId: the top-level ancestor of a subagent (the session itself when it has none).
277282
// childSummary: {children, running, waiting} for a session that spawned subagents —
278283
// direct children, those mid-turn, and descendants at any depth awaiting a permission.

‎agent/internal/backend/opencode/events.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,7 @@ func (b *Backend) translateEvent(directory, typ string, props map[string]any) []
267267
b.resolveClientMessageID(sid, &msg)
268268
events := []backend.BackendEvent{wrap(sid, backend.Event{Kind: backend.EventMessage, Message: &msg})}
269269
if msg.Role == "assistant" {
270+
b.noteSessionModel(sid, info)
270271
if u := usageFromMessageMap(info); u != nil {
271272
b.fillContextMax(info, u)
272273
b.setSessionUsage(sid, u)

‎agent/internal/backend/opencode/http.go‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,9 +162,40 @@ func (b *Backend) GetSession(ctx context.Context, _ string, sessionID string) (b
162162
b.noteSession(s)
163163
ov := b.getOverlay(sessionID)
164164
s.ModeID, s.ModelID, s.Effort = ov.ModeID, ov.ModelID, ov.Effort
165+
if s.ModelID == "" && s.ParentID != "" {
166+
// A subagent runs on its parent's model and has no choice of its own
167+
// to report: say what it actually ran on, so the panel does not fall
168+
// back to naming the machine's default model for it.
169+
s.ModelID = b.subagentModel(ctx, sessionID)
170+
}
165171
return b.withUsage(s), nil
166172
}
167173

174+
// subagentModel is the model a subagent's newest assistant message ran on:
175+
// from the event stream when this process saw one, else from its newest
176+
// messages (a short page, not the whole transcript), else "".
177+
func (b *Backend) subagentModel(ctx context.Context, sessionID string) string {
178+
if m := b.sessionModelOf(sessionID); m != "" {
179+
return m
180+
}
181+
var raw []any
182+
if err := b.doJSON(ctx, http.MethodGet, "/session/"+url.PathEscape(sessionID)+"/message?limit=10", nil, &raw); err != nil {
183+
return ""
184+
}
185+
entries := asMaps(raw)
186+
for i := len(entries) - 1; i >= 0; i-- {
187+
info := getMap(entries[i], "info")
188+
if info == nil || getStr(info, "role") != "assistant" {
189+
continue
190+
}
191+
b.noteSessionModel(sessionID, info)
192+
if m := b.sessionModelOf(sessionID); m != "" {
193+
return m
194+
}
195+
}
196+
return ""
197+
}
198+
168199
func (b *Backend) CreateSession(ctx context.Context, workspaceDir string, opts backend.CreateSessionOptions) (backend.Session, error) {
169200
body := map[string]any{}
170201
if opts.Title != "" {

‎agent/internal/backend/opencode/mapping.go‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,27 @@ func usageFromMessageMap(m map[string]any) *backend.Usage {
389389

390390
// setSessionUsage records sessionID's latest known Usage, observed off the
391391
// event stream (opencode's own session object carries no usage field).
392+
// noteSessionModel remembers the model an assistant message ran on
393+
// (opencode's message info carries providerID and modelID; the session
394+
// object does not).
395+
func (b *Backend) noteSessionModel(sessionID string, info map[string]any) {
396+
provider, model := getStr(info, "providerID"), getStr(info, "modelID")
397+
if sessionID == "" || provider == "" || model == "" {
398+
return
399+
}
400+
b.usageMu.Lock()
401+
b.sessionModel[sessionID] = provider + "/" + model
402+
b.usageMu.Unlock()
403+
}
404+
405+
// sessionModelOf is noteSessionModel's answer for a session, "" when no
406+
// assistant message of it has been seen since this process started.
407+
func (b *Backend) sessionModelOf(sessionID string) string {
408+
b.usageMu.Lock()
409+
defer b.usageMu.Unlock()
410+
return b.sessionModel[sessionID]
411+
}
412+
392413
func (b *Backend) setSessionUsage(sessionID string, u *backend.Usage) {
393414
b.usageMu.Lock()
394415
b.sessionUsage[sessionID] = u

‎agent/internal/backend/opencode/opencode.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,12 @@ type Backend struct {
206206
// Transcript.
207207
usageMu sync.Mutex
208208
sessionUsage map[string]*backend.Usage
209+
// sessionModel (under usageMu) is the "provider/model" each session's
210+
// latest assistant message ran on, as the event stream shows it. A
211+
// subagent has no model of its own in opencode's session object or in
212+
// galopin's overlay (it runs on its parent's), so this is the only place
213+
// session.get can learn what it actually runs on.
214+
sessionModel map[string]string
209215
}
210216

211217
type sessionOverlay struct {
@@ -248,6 +254,7 @@ func New(cfg Config) *Backend {
248254
pendingClientMsg: map[string]pendingClaim{},
249255
modelLimit: map[string]int{},
250256
sessionUsage: map[string]*backend.Usage{},
257+
sessionModel: map[string]string{},
251258
commandMarkers: map[string]backend.MessageCommand{},
252259
}
253260
}

‎agent/internal/backend/opencode/permissions.go‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,14 +559,27 @@ func (b *Backend) RuleLayers(ctx context.Context, workspaceDir, sessionID string
559559
// cerea, so that many trailing rules are the machine's policy, not the
560560
// session's selector.
561561
nSafe := len(permrules.SafeDirRules(ownLayers.SafeDirs))
562+
// The tool-visibility sentinel opens cerea and is machinery, not a rule a
563+
// person set or reads: it is left out of the listing (and so are the
564+
// ceiling's restatements of it), and the machine's own rules follow it.
565+
nSentinel := 0
566+
if len(cerea) > 0 && permrules.IsToolVisibilitySentinel(cerea[0]) {
567+
nSentinel = 1
568+
}
562569
for i, r := range cerea {
570+
if i < nSentinel {
571+
continue
572+
}
563573
src := backend.SourceCerea
564-
if i < nOwn || i >= len(cerea)-nSafe {
574+
if i < nSentinel+nOwn || i >= len(cerea)-nSafe {
565575
src = backend.SourceMachine
566576
}
567577
out.Rules = append(out.Rules, backend.SourcedRule{Rule: r, Source: src})
568578
}
569579
for _, r := range tail {
580+
if r.Pattern == permrules.ToolVisibilitySentinel.Pattern {
581+
continue
582+
}
570583
out.Rules = append(out.Rules, backend.SourcedRule{Rule: r, Source: backend.SourceCeiling})
571584
}
572585
return out, nil

‎agent/internal/backend/opencode/permissions_test.go‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,11 @@ func TestCreateSessionCarriesTheRules(t *testing.T) {
123123
t.Fatalf("creates=%d patches=%d, want the rules in the one create", len(creates), len(patches))
124124
}
125125
rules := rulesOf(t, creates[0])
126-
if rules[0] != (permrules.Rule{Permission: "edit", Pattern: "*", Action: permrules.Allow}) {
127-
t.Errorf("first rule = %+v, want the machine's own", rules[0])
126+
if rules[0] != permrules.ToolVisibilitySentinel {
127+
t.Errorf("first rule = %+v, want the tool-visibility sentinel", rules[0])
128+
}
129+
if rules[1] != (permrules.Rule{Permission: "edit", Pattern: "*", Action: permrules.Allow}) {
130+
t.Errorf("second rule = %+v, want the machine's own", rules[1])
128131
}
129132
agent := []permrules.Rule{{Permission: "*", Pattern: "*", Action: permrules.Allow}}
130133
if got := permrules.Evaluate(append(agent, rules...), "edit", "a.go"); got != permrules.Ask {
@@ -412,6 +415,16 @@ func TestRuleLayersAttributesSources(t *testing.T) {
412415
if last := l.Rules[len(l.Rules)-1]; last.Source != backend.SourceCeiling {
413416
t.Errorf("last rule = %+v, want the ceiling's", last)
414417
}
418+
// The tool-visibility sentinel is machinery: never listed, and the
419+
// machine's own rule keeps its label right after where it sits.
420+
for _, r := range l.Rules {
421+
if r.Pattern == permrules.ToolVisibilitySentinel.Pattern {
422+
t.Errorf("the sentinel is listed: %+v", r)
423+
}
424+
if r.Source == backend.SourceMachine && r.Permission != "webfetch" {
425+
t.Errorf("a non-machine rule is labelled machine: %+v", r)
426+
}
427+
}
415428
}
416429

417430
// stackOf is what opencode holds for a session after the creates and PATCHes it
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package opencode
2+
3+
import (
4+
"context"
5+
"net/http"
6+
"net/http/httptest"
7+
"strings"
8+
"testing"
9+
)
10+
11+
// A subagent runs on its parent's model and has no model of its own in
12+
// opencode's session object or galopin's overlay: session.get must say what
13+
// it actually ran on (its newest assistant message's), not leave it empty —
14+
// an empty modelId made the panel name the machine's default model for it.
15+
// A top-level session with no explicit choice still reports none.
16+
func TestGetSessionReportsTheModelASubagentRunsOn(t *testing.T) {
17+
messages := `[{"info":{"id":"msg_1","role":"user"},"parts":[]},
18+
{"info":{"id":"msg_2","role":"assistant","providerID":"older","modelID":"older-model"},"parts":[]},
19+
{"info":{"id":"msg_3","role":"assistant","providerID":"cortecs","modelID":"glm-5.3-flash"},"parts":[]}]`
20+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
21+
w.Header().Set("Content-Type", "application/json")
22+
switch {
23+
case r.URL.Path == "/session/ses_child":
24+
_, _ = w.Write([]byte(`{"id":"ses_child","parentID":"ses_root","title":"t (@general subagent)","directory":"/ws"}`))
25+
case r.URL.Path == "/session/ses_root":
26+
_, _ = w.Write([]byte(`{"id":"ses_root","title":"root","directory":"/ws"}`))
27+
case strings.HasSuffix(r.URL.Path, "/message"):
28+
_, _ = w.Write([]byte(messages))
29+
default:
30+
http.NotFound(w, r)
31+
}
32+
}))
33+
defer srv.Close()
34+
b := fakeServerBackend(t, srv)
35+
ctx := context.Background()
36+
37+
child, err := b.GetSession(ctx, "/ws", "ses_child")
38+
if err != nil {
39+
t.Fatal(err)
40+
}
41+
if child.ModelID != "cortecs/glm-5.3-flash" {
42+
t.Errorf("subagent modelId = %q, want its newest assistant message's model", child.ModelID)
43+
}
44+
45+
// The event stream's answer wins once one is seen.
46+
b.noteSessionModel("ses_child", map[string]any{"providerID": "pystino", "modelID": "glm-5.3"})
47+
if child, _ = b.GetSession(ctx, "/ws", "ses_child"); child.ModelID != "pystino/glm-5.3" {
48+
t.Errorf("subagent modelId after a message event = %q, want pystino/glm-5.3", child.ModelID)
49+
}
50+
51+
root, err := b.GetSession(ctx, "/ws", "ses_root")
52+
if err != nil {
53+
t.Fatal(err)
54+
}
55+
if root.ModelID != "" {
56+
t.Errorf("a top-level session nobody chose a model for reports %q, want none", root.ModelID)
57+
}
58+
}

‎agent/internal/mockllm/mockllm.go‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ type Server struct {
6363
// expanded text reached the mock" is exactly the fact only the mock can
6464
// see. Capped so a long IT run cannot grow it without bound.
6565
requests [][]string
66+
// requestTools is, per entry of requests, the tool names that request
67+
// offered the model ([] for none): whether a request carried tools at all
68+
// is a fact only the mock sees (a subagent whose every tool is hidden still
69+
// reaches the provider, just with no tools on it).
70+
requestTools [][]string
6671
// tools is the tool descriptions (name -> description) of the most recent
6772
// chat-completion request: what the model was told it can call, which only
6873
// the mock can see (the task tool's list of agent types is in its description).
@@ -81,6 +86,21 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
8186
out = [][]string{}
8287
}
8388
writeJSON(w, map[string]any{"requests": out})
89+
case r.URL.Path == "/__control/request-log":
90+
s.mu.Lock()
91+
type entry struct {
92+
Prompts []string `json:"prompts"`
93+
Tools []string `json:"tools"`
94+
}
95+
out := make([]entry, len(s.requests))
96+
for i := range s.requests {
97+
out[i] = entry{Prompts: s.requests[i], Tools: []string{}}
98+
if i < len(s.requestTools) && s.requestTools[i] != nil {
99+
out[i].Tools = s.requestTools[i]
100+
}
101+
}
102+
s.mu.Unlock()
103+
writeJSON(w, map[string]any{"requests": out})
84104
case r.URL.Path == "/__control/tools":
85105
s.mu.Lock()
86106
out := s.tools
@@ -92,6 +112,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
92112
case r.URL.Path == "/__control/reset-requests" && r.Method == http.MethodPost:
93113
s.mu.Lock()
94114
s.requests = nil
115+
s.requestTools = nil
95116
s.mu.Unlock()
96117
writeJSON(w, map[string]bool{"ok": true})
97118
case r.URL.Path == "/__control/health":
@@ -189,6 +210,11 @@ func (s *Server) complete(w http.ResponseWriter, r *http.Request) {
189210
}
190211
s.mu.Lock()
191212
s.requests = append(s.requests, prompts)
213+
names := []string{}
214+
for _, t := range req.Tools {
215+
names = append(names, t.Function.Name)
216+
}
217+
s.requestTools = append(s.requestTools, names)
192218
if len(req.Tools) > 0 {
193219
s.tools = map[string]string{}
194220
for _, t := range req.Tools {

0 commit comments

Comments
 (0)