Skip to content

Commit 59e2383

Browse files
authored
fix(gateway): restore the subagent model policy endpoint (#387)
## Requirement or Bug The web app calls `GET/PUT/DELETE /api/v1/config/subagent-model-policy`. The server answers 404, so the subagent model section in Settings → Agent is hidden (`SettingsDialog.vue` renders it only when the policy loads) with no error shown. ## Root Cause #323 (upstream reconcile through 99eaa993b) replaced `packages/agent-gateway` files wholesale and dropped this local feature from #236: the route file, its registration, its three schemas, the API snapshot entries and the gateway and core tests. The PR body does not mention the feature, so it was collateral. The core service (`ISubagentModelPolicyService`) is still registered and used. #323 also changed the stale-version error in `subagentModelPolicyService.ts` from `CONFIG_VERSION_CONFLICT` to `VALIDATION_FAILED`, which would map an `If-Match` conflict to the wrong status. ## Code Changes - Restore `packages/agent-gateway/src/routes/subagentModelPolicy.ts`, its registration in `registerApiV1Routes.ts`, and the request/wire/response schemas in `protocol/rest-config.ts` from `96d1a0c7a^`. - Restore `ErrorCodes.CONFIG_VERSION_CONFLICT` for a stale policy version (412 + `41201` again). - Re-export the `CanonicalSubagentModelPolicy` type from `@pymodel/agent-core-v2` (only the type; the rest of `policy.ts` is already exported elsewhere). - Restore `test/subagentModelPolicy.test.ts` (gateway) and `test/session/subagent/subagentModelPolicyService.test.ts` (core), with import paths updated for the `kosong` → `llm-adapter` move. - API snapshot: adds exactly the three routes. ## Behavior Changes and Affected Users | Behavior | Before | After | Who relies on the old behavior | Escape hatch | | --- | --- | --- | --- | --- | | `/api/v1/config/subagent-model-policy` | 404 | GET/PUT/DELETE as in #236 | Nobody: clients treated 404 as "older server" | n/a | | Stale `If-Match` on the policy | `VALIDATION_FAILED` | `CONFIG_VERSION_CONFLICT` (412) | Nobody: no route exposed it | n/a | | Web Settings → Agent | Subagent model section hidden | Section shows and saves | Web users | n/a | Contract files touched: the `apiSurface` snapshot (3 routes added back). Consumers: the web app (already calls these routes), desktop, inspector. Older clients that do not call the route are unaffected. Coverage: gateway 1434 tests and core subagent/app 1029 tests pass. Putting back `VALIDATION_FAILED` fails 2 gateway and 2 core tests. Lint passes. Not in this PR: `POST /config` still writes `secondary_model` directly instead of through `prepareLegacyMutation`; the web app does not send that field. ## Checklist - [x] I have read the [CONTRIBUTING](https://github.com/PyModel/pythinker-code/blob/main/CONTRIBUTING.md) document. - [ ] I have linked a related issue (external PRs: issue must have a maintainer's `/approve`). - [x] I have added tests that prove my feature works. - [x] The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR. - [x] Ran `gen-changesets` skill, or this PR needs no changeset. - [x] Ran `gen-docs` skill, or this PR needs no doc update. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for viewing and managing subagent model policies, including inherited, default, pool, and forced model settings. * Policy details now include configured and effective settings, and changes can be checked against the latest saved version. * **Bug Fixes** * Corrected conflict handling when a policy update is based on an outdated version, helping prevent stale changes from overwriting newer settings. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent a5a9cd3 commit 59e2383

9 files changed

Lines changed: 720 additions & 1 deletion

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@pymodel/pythinker-code": patch
3+
---
4+
5+
Fix the subagent model settings in web Settings → Agent, which were hidden because the server no longer answered their requests.

‎packages/agent-core-v2/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,7 @@ export * from '#/session/subagent/spawn';
493493
import '#/session/subagent/flag';
494494
export * from '#/session/subagent/subagentModelsValidation';
495495
import '#/session/subagent/subagentModelsValidationService';
496+
export type { CanonicalSubagentModelPolicy } from '#/session/subagent/policy';
496497
export * from '#/session/subagent/subagentModelPolicy';
497498
import '#/session/subagent/subagentModelPolicyService';
498499
export * from '#/agent/tools/agent/subagent-task';

‎packages/agent-core-v2/src/session/subagent/subagentModelPolicyService.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ export class SubagentModelPolicyService implements ISubagentModelPolicyService {
164164
const currentVersion = subagentPolicyResourceVersion(this.persisted());
165165
if (currentVersion !== expectedVersion) {
166166
throw new Error2(
167-
ErrorCodes.VALIDATION_FAILED,
167+
ErrorCodes.CONFIG_VERSION_CONFLICT,
168168
'The subagent model policy changed since it was read; reload and retry.',
169169
{ details: { section: SECONDARY_MODEL_SECTION, expectedVersion, currentVersion } },
170170
);
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2+
3+
import { SyncDescriptor } from '#/_base/di/descriptors';
4+
import { DisposableStore } from '#/_base/di/lifecycle';
5+
import { TestInstantiationService } from '#/_base/di/test';
6+
import { IConfigService } from '#/app/config/config';
7+
import { THINKING_SECTION } from '#/app/kosongConfig/configSection';
8+
import { ErrorCodes, Error2, isError2 } from '#/errors';
9+
import { UNKNOWN_CAPABILITY } from '#/llm-adapter/contract/capability';
10+
import { IModelCatalog, type Model } from '#/llm-adapter/model/catalog';
11+
import { SECONDARY_MODEL_SECTION } from '#/session/subagent/policy';
12+
import {
13+
ISubagentModelPolicyService,
14+
type SubagentModelPolicySnapshot,
15+
} from '#/session/subagent/subagentModelPolicy';
16+
import { SubagentModelPolicyService } from '#/session/subagent/subagentModelPolicyService';
17+
18+
import { StubConfigService } from '../../stubs';
19+
20+
function testModel(id: string, extra: Partial<Model> = {}): Model {
21+
return {
22+
id,
23+
name: id,
24+
aliases: [],
25+
protocol: 'openai',
26+
headers: {},
27+
capabilities: UNKNOWN_CAPABILITY,
28+
maxContextSize: 128_000,
29+
alwaysThinking: false,
30+
providerName: 'acme',
31+
...extra,
32+
};
33+
}
34+
35+
describe('SubagentModelPolicyService', () => {
36+
let disposables: DisposableStore;
37+
let ix: TestInstantiationService;
38+
let config: StubConfigService;
39+
let models: Map<string, Model>;
40+
41+
beforeEach(() => {
42+
disposables = new DisposableStore();
43+
ix = disposables.add(new TestInstantiationService());
44+
models = new Map([
45+
['acme/sol', testModel('acme/sol', { supportEfforts: ['low', 'high'], defaultEffort: 'high' })],
46+
['acme/luna', testModel('acme/luna', { supportEfforts: ['low', 'high'] })],
47+
]);
48+
});
49+
afterEach(() => disposables.dispose());
50+
51+
function setup(sections: Record<string, unknown>): ISubagentModelPolicyService {
52+
config = new StubConfigService(sections);
53+
ix.stub(IConfigService, config);
54+
ix.stub(IModelCatalog, {
55+
_serviceBrand: undefined,
56+
get: (id: string) => {
57+
const model = models.get(id);
58+
if (model === undefined) {
59+
throw new Error2(ErrorCodes.CONFIG_INVALID, `Model "${id}" is not configured in config.toml.`, {
60+
details: { model: id },
61+
});
62+
}
63+
return model;
64+
},
65+
});
66+
ix.set(ISubagentModelPolicyService, new SyncDescriptor(SubagentModelPolicyService));
67+
return ix.get(ISubagentModelPolicyService);
68+
}
69+
70+
async function codeOf(fn: () => Promise<unknown> | unknown): Promise<string | undefined> {
71+
try {
72+
await fn();
73+
return undefined;
74+
} catch (error) {
75+
return isError2(error) ? error.code : 'not-error2';
76+
}
77+
}
78+
79+
it('reads the persisted policy with a resource version and reports inherit for an absent section', () => {
80+
const service = setup({});
81+
const snapshot = service.get();
82+
expect(snapshot.policy).toEqual({ mode: 'inherit' });
83+
expect(snapshot.resourceVersion).toMatch(/^subagent-policy-v1:/);
84+
});
85+
86+
it('set validates against the live catalog and persists the canonical section', async () => {
87+
const service = setup({});
88+
await expect(
89+
service.set({ mode: 'default', defaultModel: 'acme/nope' }),
90+
).rejects.toMatchObject({ code: ErrorCodes.CONFIG_INVALID });
91+
expect(config.get(SECONDARY_MODEL_SECTION)).toBeUndefined();
92+
93+
const snapshot = await service.set({ mode: 'force', defaultModel: 'acme/sol', defaultEffort: 'low' });
94+
expect(snapshot.policy).toEqual({ mode: 'force', defaultModel: 'acme/sol', defaultEffort: 'low' });
95+
expect(config.get(SECONDARY_MODEL_SECTION)).toEqual({
96+
defaultModel: 'acme/sol',
97+
force: true,
98+
defaultEffort: 'low',
99+
});
100+
101+
await service.set({ mode: 'default', defaultModel: 'acme/luna' });
102+
expect(config.get(SECONDARY_MODEL_SECTION)).toEqual({
103+
defaultModel: 'acme/luna',
104+
defaultEffort: undefined,
105+
});
106+
});
107+
108+
it('clear removes the section and expectedVersion guards both set and clear', async () => {
109+
const service = setup({ [SECONDARY_MODEL_SECTION]: { defaultModel: 'acme/sol' } });
110+
const before = service.get().resourceVersion;
111+
expect(await codeOf(() => service.set({ mode: 'inherit' }, 'subagent-policy-v1:stale'))).toBe(
112+
ErrorCodes.CONFIG_VERSION_CONFLICT,
113+
);
114+
expect(config.get(SECONDARY_MODEL_SECTION)).toEqual({ defaultModel: 'acme/sol' });
115+
const cleared = await service.clear(before);
116+
expect(cleared.policy).toEqual({ mode: 'inherit' });
117+
expect(config.get(SECONDARY_MODEL_SECTION)).toBeUndefined();
118+
expect(cleared.resourceVersion).not.toBe(before);
119+
expect(await codeOf(() => service.clear(before))).toBe(ErrorCodes.CONFIG_VERSION_CONFLICT);
120+
});
121+
122+
it('serializes concurrent commits so a stale expectedVersion cannot slip past the version check', async () => {
123+
const service = setup({ [SECONDARY_MODEL_SECTION]: { defaultModel: 'acme/sol' } });
124+
const replace = config.replace.bind(config);
125+
config.replace = async (domain, value) => {
126+
await new Promise((resolve) => setTimeout(resolve, 0));
127+
await replace(domain, value);
128+
};
129+
const version = service.get().resourceVersion;
130+
const [first, second] = await Promise.allSettled([
131+
service.set({ mode: 'default', defaultModel: 'acme/luna' }, version),
132+
service.set({ mode: 'force', defaultModel: 'acme/sol' }, version),
133+
]);
134+
expect(first.status).toBe('fulfilled');
135+
expect(second.status).toBe('rejected');
136+
expect((second as PromiseRejectedResult).reason).toMatchObject({
137+
code: ErrorCodes.CONFIG_VERSION_CONFLICT,
138+
});
139+
expect(config.get(SECONDARY_MODEL_SECTION)).toEqual({ defaultModel: 'acme/luna', defaultEffort: undefined });
140+
const recovered = await service.set(
141+
{ mode: 'force', defaultModel: 'acme/sol' },
142+
(first as PromiseFulfilledResult<SubagentModelPolicySnapshot>).value.resourceVersion,
143+
);
144+
expect(recovered.policy).toEqual({ mode: 'force', defaultModel: 'acme/sol' });
145+
expect(config.get(SECONDARY_MODEL_SECTION)).toEqual({ defaultModel: 'acme/sol', force: true, defaultEffort: undefined });
146+
});
147+
148+
it('prepareLegacyMutation validates against the supplied prospective context, not the live catalog', () => {
149+
const service = setup({});
150+
const prospective = {
151+
resolveModel: (alias: string) => (alias === 'acme/future' ? { id: alias } : undefined),
152+
};
153+
const prepared = service.prepareLegacyMutation(
154+
{ defaultModel: 'acme/future', models: { 'acme/future': 'soon' } },
155+
prospective,
156+
);
157+
expect(prepared.policy).toEqual({
158+
mode: 'pool',
159+
defaultModel: 'acme/future',
160+
models: { 'acme/future': 'soon' },
161+
defaultEffort: undefined,
162+
});
163+
expect(prepared.section).toEqual({
164+
defaultModel: 'acme/future',
165+
models: { 'acme/future': 'soon' },
166+
defaultEffort: undefined,
167+
});
168+
expect(config.get(SECONDARY_MODEL_SECTION)).toBeUndefined();
169+
expect(() => service.prepareLegacyMutation({ defaultModel: 'acme/sol' }, prospective)).toThrow();
170+
expect(() => service.prepareLegacyMutation({ defaultModel: 'acme/sol' })).not.toThrow();
171+
expect(service.prepareLegacyMutation(null)).toEqual({ policy: { mode: 'inherit' }, section: undefined });
172+
expect(() => service.prepareLegacyMutation({ defaultModel: 42 })).toThrow();
173+
});
174+
175+
it('resolveRevision changes only with ambient routing inputs', async () => {
176+
const service = setup({ [SECONDARY_MODEL_SECTION]: { defaultModel: 'acme/luna' } });
177+
const caller = { modelAlias: 'acme/sol', thinkingLevel: 'high' };
178+
const a = service.resolveRevision(caller);
179+
expect(a).toMatch(/^route-env:v1:/);
180+
expect(service.resolveRevision({ ...caller })).toBe(a);
181+
expect(service.resolveRevision({ modelAlias: 'acme/luna', thinkingLevel: 'high' })).not.toBe(a);
182+
await config.replace(THINKING_SECTION, { enabled: false });
183+
expect(service.resolveRevision(caller)).not.toBe(a);
184+
});
185+
});

‎packages/agent-gateway/src/protocol/rest-config.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,47 @@ export const configResponseSchema = z
3636
.passthrough();
3737
export type ConfigResponse = z.infer<typeof configResponseSchema>;
3838

39+
const policyModelAlias = z.string().min(1);
40+
const policyEffort = z.string().min(1).optional();
41+
42+
export const subagentModelPolicyRequestSchema = z.discriminatedUnion('mode', [
43+
z.object({ mode: z.literal('inherit') }).strict(),
44+
z.object({ mode: z.literal('default'), default_model: policyModelAlias, default_effort: policyEffort }).strict(),
45+
z
46+
.object({
47+
mode: z.literal('pool'),
48+
default_model: policyModelAlias,
49+
models: z.record(z.string(), z.string()),
50+
default_effort: policyEffort,
51+
})
52+
.strict(),
53+
z.object({ mode: z.literal('force'), default_model: policyModelAlias, default_effort: policyEffort }).strict(),
54+
]);
55+
export type SubagentModelPolicyRequest = z.infer<typeof subagentModelPolicyRequestSchema>;
56+
57+
export const subagentModelPolicyWireSchema = z.object({
58+
mode: z.enum(['inherit', 'default', 'pool', 'force']),
59+
default_model: z.string().optional(),
60+
models: z.record(z.string(), z.string()).optional(),
61+
default_effort: z.string().optional(),
62+
});
63+
export type SubagentModelPolicyWire = z.infer<typeof subagentModelPolicyWireSchema>;
64+
65+
export const subagentModelPolicyResponseSchema = z.object({
66+
policy: subagentModelPolicyWireSchema,
67+
resource_version: z.string().min(1),
68+
effective: z.object({
69+
configured_policy: subagentModelPolicyWireSchema,
70+
effective_policy: subagentModelPolicyWireSchema,
71+
policy_source: z.enum(['config', 'default']),
72+
feature: z.object({
73+
enabled: z.boolean(),
74+
source: z.enum(['master-env', 'env', 'config', 'default']),
75+
}),
76+
}),
77+
});
78+
export type SubagentModelPolicyResponse = z.infer<typeof subagentModelPolicyResponseSchema>;
79+
3980
export const patchConfigRequestSchema = z.object({
4081
providers: z.record(z.string(), z.unknown()).optional(),
4182
default_provider: z.string().optional(),

‎packages/agent-gateway/src/routes/registerApiV1Routes.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { registerAuthRoute } from './auth';
1515
import { registerCodexLoginRoutes } from './codex';
1616
import { registerCapabilitiesRoutes } from './capabilities';
1717
import { registerConfigRoutes } from './config';
18+
import { registerSubagentModelPolicyRoutes } from './subagentModelPolicy';
1819
import { registerConnectionsRoutes } from './connections';
1920
import { registerFileHistoryRoutes } from './fileHistory';
2021
import { registerFilesRoutes } from './files';
@@ -114,6 +115,10 @@ export async function registerApiV1Routes(
114115
registerAuthRoute(apiV1 as unknown as Parameters<typeof registerAuthRoute>[0], core);
115116
registerCodexLoginRoutes(apiV1 as unknown as Parameters<typeof registerCodexLoginRoutes>[0], core);
116117
registerConfigRoutes(apiV1 as unknown as Parameters<typeof registerConfigRoutes>[0], core);
118+
registerSubagentModelPolicyRoutes(
119+
apiV1 as unknown as Parameters<typeof registerSubagentModelPolicyRoutes>[0],
120+
core,
121+
);
117122
registerModelCatalogRoutes(
118123
apiV1 as unknown as Parameters<typeof registerModelCatalogRoutes>[0],
119124
core,

0 commit comments

Comments
 (0)