Skip to content

Commit 34062ea

Browse files
authored
fix(gateway): allow write-scoped session model changes (#120875)
1 parent 7f3cc69 commit 34062ea

14 files changed

Lines changed: 179 additions & 100 deletions

‎docs/gateway/operator-scopes.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ dispatch so authorization failures have one canonical structured response:
5858
`operator.talk.secrets`.
5959
- `talk.client.*`, `talk.session.*`, `talk.speak`, and `talk.mode` need
6060
`operator.talk` (or the compatible broader `operator.write`).
61+
- `sessions.patch` needs `operator.write` for session organization fields and
62+
the per-session `model` override. Other runtime overrides, including
63+
thinking, fast, verbose, trace, and reasoning levels, need `operator.admin`.
64+
Persisting a selected model as the configured agent default is also
65+
admin-only.
6166

6267
Some handlers then apply stricter checks based on the concrete thing being
6368
approved or mutated:

‎docs/gateway/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -626,7 +626,7 @@ methods. Treat this as feature discovery, not a full enumeration of
626626
- `sessions.send` sends a message into an existing session.
627627
- `sessions.steer` is the interrupt-and-steer variant for an active session.
628628
- `sessions.abort` aborts active work for a session. Pass `key` plus optional `runId`, or `runId` alone for active runs the gateway can resolve to a session. Supplying `runId` keeps cancellation scoped to that run. Set `clearQueued: true` on a key-only non-global request to also discard followup and lane queues owned by that session. Existing callers that omit `clearQueued` preserve those queues. The literal `global` key keeps the existing agent-qualified `chat.abort` ownership rules and does not perform non-global followup or lane cleanup.
629-
- `sessions.patch` updates session metadata/overrides and reports the resolved canonical model plus effective `agentRuntime`. Spawn lineage (`spawnedBy`, `spawnedWorkspaceDir`, `spawnedCwd`, `spawnDepth`, `subagentRole`, `subagentControlScope`) is no longer publicly patchable; those facts are written once by trusted creation paths, and requests that still send them are rejected.
629+
- `sessions.patch` updates session metadata/overrides and reports the resolved canonical model plus effective `agentRuntime`. Session organization fields and the per-session `model` override require `operator.write`; thinking, fast, verbose, trace, reasoning, and other privileged overrides require `operator.admin`. Only an admin model selection can persist as the configured agent default. Spawn lineage (`spawnedBy`, `spawnedWorkspaceDir`, `spawnedCwd`, `spawnDepth`, `subagentRole`, `subagentControlScope`) is no longer publicly patchable; those facts are written once by trusted creation paths, and requests that still send them are rejected.
630630
- `sessions.reset`, `sessions.delete`, and `sessions.compact` perform session maintenance.
631631
- `sessions.get` returns the full stored session row.
632632
- Chat execution still uses `chat.history`, `chat.send`, `chat.abort`, and `chat.inject`. `chat.history` is display-normalized for UI clients: inline directive tags are stripped from visible text, plain-text tool-call XML payloads (`<tool_call>...</tool_call>`, `<function_call>...</function_call>`, `<tool_calls>...</tool_calls>`, `<function_calls>...</function_calls>`, and truncated tool-call blocks) and leaked ASCII/full-width model control tokens are stripped, pure silent-token assistant rows (exact `NO_REPLY` / `no_reply`) are omitted, and oversized rows can be replaced with placeholders.

‎src/gateway/method-scopes.test.ts‎

Lines changed: 20 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -468,18 +468,8 @@ describe("method scope resolution", () => {
468468
).toEqual({ allowed: false, missingScope: "operator.admin" });
469469
});
470470

471-
it.each([
472-
["model", { key: "agent:main:ios-1", model: "anthropic/claude-sonnet-5" }],
473-
["sendPolicy", { key: "agent:main:ios-1", sendPolicy: "deny" }],
474-
["inheritedToolAllow", { key: "agent:main:ios-1", inheritedToolAllow: ["exec"] }],
475-
["inheritedToolPolicyVersion", { key: "agent:main:ios-1", inheritedToolPolicyVersion: 1 }],
476-
[
477-
"completionOwnerSessionKey",
478-
{ key: "agent:main:ios-1", completionOwnerSessionKey: "agent:main:main" },
479-
],
480-
["mixed with safe fields", { key: "agent:main:ios-1", label: "x", execHost: "node-1" }],
481-
["unknown fields", { key: "agent:main:ios-1", futureField: true }],
482-
])("keeps sessions.patch admin-only when params include %s", (_name, params) => {
471+
it("delegates effort patches to the admin-scoped session policy", () => {
472+
const params = { key: "agent:main:ios-1", thinkingLevel: "high" };
483473
expect(resolveLeastPrivilegeOperatorScopesForMethod("sessions.patch", params)).toEqual([
484474
"operator.admin",
485475
]);
@@ -492,48 +482,37 @@ describe("method scope resolution", () => {
492482
});
493483
});
494484

495-
it("authorizes write-scoped sessions.patch for chat-organization fields and denies read scope", () => {
496-
const params = { key: "agent:main:ios-1", label: "Trip planning", pinned: true };
485+
it("delegates model patches to the write-scoped session policy", () => {
486+
const params = { key: "agent:main:ios-1", model: "anthropic/claude-sonnet-5" };
487+
expect(resolveLeastPrivilegeOperatorScopesForMethod("sessions.patch", params)).toEqual([
488+
"operator.write",
489+
]);
497490
expect(authorizeOperatorScopesForMethod("sessions.patch", ["operator.write"], params)).toEqual({
498491
allowed: true,
499492
});
500493
expect(authorizeOperatorScopesForMethod("sessions.patch", ["operator.read"], params)).toEqual({
501494
allowed: false,
502495
missingScope: "operator.write",
503496
});
497+
expect(authorizeOperatorScopesForMethod("sessions.patch", ["operator.admin"], params)).toEqual({
498+
allowed: true,
499+
});
504500
});
505501

506-
it("scopes sessions.patchMany only from patch mutation fields", () => {
507-
const targets = [
508-
{
509-
key: "agent:main:ios-1",
510-
agentId: "main",
511-
expectedSessionId: "session-1",
512-
expectedLifecycleRevision: "revision-1",
513-
},
514-
];
502+
it("delegates sessions.patchMany from its patch fields", () => {
515503
expect(
516504
resolveLeastPrivilegeOperatorScopesForMethod("sessions.patchMany", {
517-
targets,
518-
patch: { label: "Trip planning", unread: false },
505+
targets: [
506+
{
507+
key: "agent:main:ios-1",
508+
agentId: "main",
509+
expectedSessionId: "session-1",
510+
expectedLifecycleRevision: "revision-1",
511+
},
512+
],
513+
patch: { model: "openai/gpt-5.6-luna" },
519514
}),
520515
).toEqual(["operator.write"]);
521-
expect(
522-
resolveLeastPrivilegeOperatorScopesForMethod("sessions.patchMany", {
523-
targets,
524-
patch: { statusNote: "Working" },
525-
}),
526-
).toEqual(["operator.admin"]);
527-
expect(
528-
resolveLeastPrivilegeOperatorScopesForMethod("sessions.patchMany", {
529-
targets,
530-
patch: { futureField: true },
531-
}),
532-
).toEqual(["operator.admin"]);
533-
expect(authorizeOperatorScopesForMethod("sessions.patchMany", ["operator.write"])).toEqual({
534-
allowed: true,
535-
});
536-
expect(isGatewayMethodClassified("sessions.patchMany")).toBe(true);
537516
});
538517

539518
it("lets malformed sessions.patch params through to handler validation at write scope", () => {

‎src/gateway/methods/core-descriptors.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,9 +243,9 @@ const CORE_GATEWAY_METHOD_SPECS = [
243243
["sessions.create", "sessions-create", "dynamic", "<=2026.7", { startup: true }],
244244
["sessions.send", "sessions-messaging", "operator.write", "<=2026.7", { startup: true }],
245245
["sessions.abort", "sessions-abort", "operator.write", "<=2026.7", { startup: true }],
246-
// Params-aware: write scope may mutate chat-organization fields
247-
// (label/category/icon/pinned/archived/unread); every other patch field stays
248-
// admin-only. Policy lives in shared/session-method-scopes.ts.
246+
// Dynamic mutation scope policy, including write-scoped model overrides, lives
247+
// in shared/session-method-scopes.ts. The admin-only sticky configured-default
248+
// persistence guard lives in server-methods/sessions-mutations.ts.
249249
["sessions.patch", "sessions-mutations", "dynamic", "<=2026.7"],
250250
["sessions.pluginPatch", "sessions-mutations", "operator.admin", "<=2026.7"],
251251
["sessions.cleanup", "sessions-read", "operator.admin", "<=2026.7"],

‎src/gateway/server-methods/sessions-mutations.sticky-model.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ describe("sessions.patch sticky model persistence", () => {
133133
},
134134
);
135135

136-
it("keeps a non-admin model switch session-scoped", async () => {
136+
it("keeps a write-scoped model switch session-only without persisting the configured default", async () => {
137137
await withOpenClawTestState({ scenario: "minimal" }, async () => {
138138
const sessionKey = "agent:main:dm:non-admin";
139139
await upsertSessionEntry(

‎src/gateway/server.sessions.store-rpc.test.ts‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -764,7 +764,7 @@ test("sessions.list hides phantom agent store placeholder rows", async () => {
764764
});
765765

766766
test("write-scoped operators manage chat organization but not admin session settings", async () => {
767-
await createSessionStoreDir();
767+
const { storePath } = await createSessionStoreDir();
768768
const now = Date.now();
769769
await writeSessionStore({
770770
entries: {
@@ -779,14 +779,25 @@ test("write-scoped operators manage chat organization but not admin session sett
779779
},
780780
});
781781

782-
const { ws } = await openClient({ scopes: ["operator.read", "operator.write"] });
782+
agentDiscoveryMock.enabled = true;
783+
agentDiscoveryMock.models = [{ id: "gpt-test-a", name: "A", provider: "openai" }];
784+
785+
const { ws } = await openClient({ scopes: ["operator.write"] });
783786
try {
784-
const renamed = await rpcReq<{ ok: true; entry: { label?: string } }>(ws, "sessions.patch", {
787+
const renamed = await rpcReq<{
788+
ok: true;
789+
entry: { label?: string; modelOverride?: string; providerOverride?: string };
790+
}>(ws, "sessions.patch", {
785791
key: "agent:main:topic-a",
786792
label: "Trip planning",
793+
model: "openai/gpt-test-a",
787794
});
788795
expect(renamed.ok).toBe(true);
789-
expect(renamed.payload?.entry.label).toBe("Trip planning");
796+
expect(renamed.payload?.entry).toMatchObject({
797+
label: "Trip planning",
798+
modelOverride: "gpt-test-a",
799+
providerOverride: "openai",
800+
});
790801

791802
const pinned = await rpcReq<{ ok: true; entry: { pinnedAt?: number } }>(ws, "sessions.patch", {
792803
key: "agent:main:topic-a",
@@ -912,10 +923,18 @@ test("write-scoped operators manage chat organization but not admin session sett
912923
const mixedFieldsDenied = await rpcReq(ws, "sessions.patch", {
913924
key: "agent:main:topic-a",
914925
label: "Sneaky",
915-
model: "anthropic/claude-sonnet-5",
926+
model: null,
927+
thinkingLevel: "high",
916928
});
917929
expect(mixedFieldsDenied.ok).toBe(false);
918930
expect(mixedFieldsDenied.error?.message).toContain("missing scope: operator.admin");
931+
expect(loadSessionEntry({ sessionKey: "agent:main:topic-a", storePath })).toMatchObject({
932+
label: "Trip planning",
933+
modelOverride: "gpt-test-a",
934+
providerOverride: "openai",
935+
});
936+
// Sticky configured-default persistence is handler policy and is covered by
937+
// sessions-mutations.sticky-model.test.ts; this dispatch proof asserts session state only.
919938
} finally {
920939
ws.close();
921940
}

‎src/shared/session-method-scopes.test.ts‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,39 @@ describe("resolveDynamicSessionMutationRequiredScope", () => {
2424
);
2525
});
2626

27-
it("allows only organizational session patches with write scope", () => {
27+
it.each([
28+
{ name: "model set", patch: { model: "openai/gpt-5.6-luna" } },
29+
{ name: "model reset", patch: { model: null } },
30+
{
31+
name: "safe mixed patch",
32+
patch: { label: "Renamed", archived: true, model: "openai/gpt-5.6-luna" },
33+
},
34+
{
35+
name: "CAS envelope",
36+
patch: { expectedSessionId: "session-1", expectedLifecycleRevision: "revision-1" },
37+
},
38+
])("keeps $name write-scoped", ({ patch }) => {
2839
expect(
2940
resolveDynamicSessionMutationRequiredScope("sessions.patch", {
3041
key: "agent:main:thread",
31-
label: "Renamed",
32-
archived: true,
42+
agentId: "main",
43+
...patch,
3344
}),
3445
).toBe("operator.write");
46+
});
47+
48+
it.each([
49+
{ thinkingLevel: "high" },
50+
{ fastMode: true },
51+
{ verboseLevel: "full" },
52+
{ reasoningLevel: "high" },
53+
{ model: "openai/gpt-5.6-luna", thinkingLevel: "high" },
54+
{ model: null, futureField: true },
55+
])("keeps privileged or unknown patch fields admin-scoped %#", (patch) => {
3556
expect(
3657
resolveDynamicSessionMutationRequiredScope("sessions.patch", {
3758
key: "agent:main:thread",
38-
thinkingLevel: "high",
59+
...patch,
3960
}),
4061
).toBe("operator.admin");
4162
});
@@ -51,12 +72,19 @@ describe("resolveDynamicSessionMutationRequiredScope", () => {
5172
expectedLifecycleRevision: "revision-1",
5273
},
5374
],
54-
patch: { label: "Renamed", archived: true, unread: false },
75+
patch: { label: "Renamed", archived: true, unread: false, model: "openai/gpt-5.6-luna" },
76+
}),
77+
).toBe("operator.write");
78+
expect(
79+
resolveDynamicSessionMutationRequiredScope("sessions.patchMany", {
80+
targets: [{ key: "agent:main:thread" }],
81+
patch: { model: null },
5582
}),
5683
).toBe("operator.write");
5784
for (const patch of [
5885
{ statusNote: "Working" },
5986
{ thinkingLevel: "high" },
87+
{ model: "openai/gpt-5.6-luna", fastMode: true },
6088
{ futureField: true },
6189
]) {
6290
expect(

‎src/shared/session-method-scopes.ts‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,22 @@ import { isIncognitoSessionKey } from "./incognito-session-key.js";
33

44
export type SessionMutationOperatorScope = "operator.write" | "operator.admin";
55

6-
const SESSIONS_PATCH_WRITE_SCOPE_FIELDS: ReadonlySet<string> = new Set([
7-
"key",
8-
"agentId",
6+
const SESSIONS_PATCH_WRITE_SCOPE_MUTATIONS: ReadonlySet<string> = new Set([
97
"label",
108
"category",
119
"boardFace",
1210
"icon",
1311
"pinned",
1412
"archived",
1513
"unread",
14+
"model",
1615
]);
1716

18-
const SESSIONS_PATCH_MANY_WRITE_SCOPE_FIELDS: ReadonlySet<string> = new Set([
19-
"label",
20-
"category",
21-
"boardFace",
22-
"icon",
23-
"pinned",
24-
"archived",
25-
"unread",
17+
const SESSIONS_PATCH_WRITE_SCOPE_ENVELOPE_FIELDS: ReadonlySet<string> = new Set([
18+
"key",
19+
"agentId",
20+
"expectedSessionId",
21+
"expectedLifecycleRevision",
2622
]);
2723

2824
const SESSIONS_DELETE_WRITE_SCOPE_FIELDS: ReadonlySet<string> = new Set([
@@ -38,7 +34,11 @@ function resolveSessionsPatchRequiredScope(params: unknown): SessionMutationOper
3834
// precise validation error instead of a misleading missing-scope error.
3935
return "operator.write";
4036
}
41-
return Object.keys(params).every((key) => SESSIONS_PATCH_WRITE_SCOPE_FIELDS.has(key))
37+
return Object.keys(params).every(
38+
(key) =>
39+
SESSIONS_PATCH_WRITE_SCOPE_ENVELOPE_FIELDS.has(key) ||
40+
SESSIONS_PATCH_WRITE_SCOPE_MUTATIONS.has(key),
41+
)
4242
? "operator.write"
4343
: "operator.admin";
4444
}
@@ -49,7 +49,7 @@ function resolveSessionsPatchManyRequiredScope(params: unknown): SessionMutation
4949
// the exact closed/non-empty patch failure under the least privilege scope.
5050
return "operator.write";
5151
}
52-
return Object.keys(params.patch).every((key) => SESSIONS_PATCH_MANY_WRITE_SCOPE_FIELDS.has(key))
52+
return Object.keys(params.patch).every((key) => SESSIONS_PATCH_WRITE_SCOPE_MUTATIONS.has(key))
5353
? "operator.write"
5454
: "operator.admin";
5555
}

‎ui/src/lib/session-method-access.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,26 @@ describe("readSessionMethodAccess", () => {
4343
});
4444
});
4545

46+
it("keeps model and effort patch access independent", () => {
47+
const writeOnly = snapshot({ methods: ["sessions.patch"], scopes: ["operator.write"] });
48+
expect(
49+
readSessionMethodAccess(writeOnly, {
50+
method: "sessions.patch",
51+
params: { key: "agent:main:main", model: null },
52+
}),
53+
).toEqual({ allowed: true, requiredScope: "operator.write" });
54+
expect(
55+
readSessionMethodAccess(writeOnly, {
56+
method: "sessions.patch",
57+
params: { key: "agent:main:main", thinkingLevel: null },
58+
}),
59+
).toMatchObject({
60+
allowed: false,
61+
cause: "missing-scope",
62+
requiredScope: "operator.admin",
63+
});
64+
});
65+
4666
it("allows admin to satisfy write-scoped actions", () => {
4767
expect(
4868
readSessionMethodAccess(

‎ui/src/pages/chat/chat-command-executor.test.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,13 @@ function executeSlashCommand(
7373
function restrictedSnapshot(
7474
client: GatewayBrowserClient,
7575
methods: string[],
76+
scopes = ["operator.read"],
7677
): Pick<ApplicationGatewaySnapshot, "client" | "hello" | "phase"> {
7778
return {
7879
client,
7980
phase: "connected",
8081
hello: {
81-
auth: { role: "operator", scopes: ["operator.read"] },
82+
auth: { role: "operator", scopes },
8283
features: { methods },
8384
} as ApplicationGatewaySnapshot["hello"],
8485
};
@@ -140,17 +141,27 @@ describe("executeSlashCommand directives", () => {
140141
expectNoRequestCall(request, "sessions.compact");
141142
});
142143

143-
it("does not patch session settings without operator.admin", async () => {
144-
const request = vi.fn();
144+
it.each([
145+
{ name: "allows /model with operator.write", scopes: ["operator.write"], allowed: true },
146+
{ name: "rejects /model without operator.write", scopes: ["operator.read"], allowed: false },
147+
])("$name", async ({ scopes, allowed }) => {
148+
const request = vi.fn(async () => createResolvedModelPatch("gpt-5-mini", "openai"));
145149
const client = { request } as unknown as GatewayBrowserClient;
146150

147151
const result = await executeSlashCommand(client, "main", "model", "gpt-5-mini", {
148-
sessionAccessSnapshot: restrictedSnapshot(client, ["sessions.patch"]),
152+
sessionAccessSnapshot: restrictedSnapshot(client, ["sessions.patch"], scopes),
149153
chatModelCatalog: [{ id: "gpt-5-mini", name: "GPT-5 Mini", provider: "openai" }],
150154
});
151155

152-
expect(result.failed).toBe(true);
153-
expectNoRequestCall(request, "sessions.patch");
156+
expect(result.failed === true).toBe(!allowed);
157+
if (allowed) {
158+
expect(requireRequestCall(request, "sessions.patch").payload).toMatchObject({
159+
key: "main",
160+
model: "gpt-5-mini",
161+
});
162+
} else {
163+
expectNoRequestCall(request, "sessions.patch");
164+
}
154165
});
155166

156167
it("defers slash-command model cache publication to the captured chat owner", async () => {

0 commit comments

Comments
 (0)