Forráskód Böngészése

fix: scope Agent configuration review to its model provider

hetaoBackend 2 hónapja
szülő
commit
20033c7470

+ 16 - 0
docs/tui-capabilities.md

@@ -21,6 +21,22 @@ The evidence column summarizes the historical TUI 0.3.11 restoration record from
 | Files, shell, subagents, sessions, headless, ACP | Actual runtime retained | BYOK, file reads, session resume, ACP, sandbox, and status protocol tests |
 | Built-in skills, MCP, plugin tools | Original TUI assets and activation conditions retained | Asset build, plugin, and MCP tests; no claim that every skill has passed a real task |
 
+## Agent configuration review
+
+In CLI/TUI runtimes, Agent creation, import, identity updates and full configuration
+saves do not require MiniMax account review when the target Agent resolves to a
+known unmanaged provider. The Agent's configured model takes precedence; an omitted
+model inherits the current runtime default. This decision does not use the active
+conversation's model. Changing a configuration to a managed model reviews the
+candidate document before saving. Managed, unresolved and non-CLI contexts retain
+the existing review policy.
+
+Custom Agent persona/system instructions are edited through the canonical
+`agent.md` configuration. Legacy persona/system-prompt field patches remain
+unsupported. Model validation and configuration revision/owner checks still apply.
+Offline application tests cover real SQLite/file persistence with synthetic review
+verdicts; they do not establish live-gateway or native-terminal acceptance.
+
 ## ACP Skill commands
 
 ACP clients receive enabled Skills alongside built-in slash commands when a session

+ 85 - 13
packages/local-runtime-v2/src/application/agent/agent-application.ts

@@ -27,6 +27,20 @@ import {
 import { SAFETY_SCENE, type ContentSafetyService } from '../../service/content-safety/index.js';
 import { type GlobalEventPublisher, publishBestEffort } from '../events.js';
 import type { PinService } from '../../service/pin/index.js';
+import {
+  previewAgentModelSelection,
+  type LocalRuntimeConfig,
+} from '../../service/model-system/index.js';
+import { parseCanonicalAgentMarkdown } from '../../service/agent/storage/canonical-agent-config.js';
+import { asAgentConfigServiceError } from '../../service/agent/application/agent-profile.js';
+import { isUnmanagedConfigModel } from '../config-field-review-policy.js';
+import { isCommandLineRuntimeOwner } from './profile-source.js';
+
+/** The Agent being saved owns this selection; the active Session is irrelevant. */
+type AgentConfigReviewTarget =
+  | { readonly kind: 'definition'; readonly model?: string }
+  | { readonly kind: 'document'; readonly content: string; readonly requestRef: string }
+  | { readonly kind: 'existing'; readonly requestRef: string };
 
 /** The only Session-facing Agent read/write surface assembled by V2. */
 export interface AgentSessionPorts {
@@ -49,7 +63,10 @@ export interface AgentApplicationOptions {
   readonly deleteAgentCronTasks?: (agentName: string) => Promise<void>;
   readonly removeAgentPin?: (agentName: string) => Promise<void>;
   /** Compatibility content-safety gate for persisted, user-controlled fields. */
-  readonly reviewConfigFields?: (values: ReadonlyArray<string | null | undefined>) => Promise<void>;
+  readonly reviewConfigFields?: (
+    values: ReadonlyArray<string | null | undefined>,
+    target: AgentConfigReviewTarget,
+  ) => Promise<void>;
   readonly greeting?: {
     readonly enabled: boolean;
     readonly canSend?: () => boolean;
@@ -69,12 +86,14 @@ interface RuntimeAgentApplicationCompositionInput {
   readonly pinService: Pick<PinService, 'removeAgent'>;
   readonly agentService: LocalAgentService;
   readonly safety: ContentSafetyService;
+  readonly config: () => LocalRuntimeConfig;
   readonly writeGlobalEvent: GlobalEventPublisher;
   readonly internalTurnPromptReads: InternalTurnPromptReadRegistry;
   readonly product: {
     readonly promptSnapshots?: PromptSnapshotSource;
   };
   readonly options: {
+    readonly runtimeOwnerKind?: string;
     readonly greetingEnabled?: boolean;
     readonly compatibility: {
       readonly cron: {
@@ -108,7 +127,29 @@ export function createRuntimeAgentApplication(
     publish: input.writeGlobalEvent,
     deleteAgentCronTasks: (agentName) => options.compatibility.cron.deleteAgentTasks(agentName),
     removeAgentPin: (agentName) => input.pinService.removeAgent(agentName),
-    reviewConfigFields: (values) => reviewAgentConfigFields(safety, values),
+    reviewConfigFields: async (values, target) => {
+      if (
+        isCommandLineRuntimeOwner(options.runtimeOwnerKind) &&
+        values.some((value) => value?.trim())
+      ) {
+        const configuredModel = await agentConfigReviewModel(input.agentService, target);
+        const config = input.config();
+        const model = previewAgentModelSelection({
+          config,
+          sources: configuredModel === undefined ? [] : [
+            {
+              source: 'agent-config-review',
+              selection: { model: configuredModel },
+              requireCatalog: true,
+              allowCustomProviderPrefixFallback: true,
+              defaultMissingEffortOff: true,
+            },
+          ],
+        });
+        if (model && isUnmanagedConfigModel(config, `${model.providerId}/${model.modelId}`)) return;
+      }
+      await reviewAgentConfigFields(safety, values);
+    },
     greeting: {
       enabled: options.greetingEnabled === true,
       canSend: () => options.compatibility.greeting.canSend(),
@@ -166,7 +207,11 @@ export class AgentApplication {
   async putConfigDocument(
     input: Parameters<LocalAgentService['putConfigDocument']>[0],
   ): ReturnType<LocalAgentService['putConfigDocument']> {
-    await this.reviewConfigFields([input.content]);
+    await this.reviewConfigFields([input.content], {
+      kind: 'document',
+      content: input.content,
+      requestRef: input.requestRef,
+    });
     return this.options.service.putConfigDocument(input);
   }
 
@@ -188,7 +233,10 @@ export class AgentApplication {
    * chooses Chat.
    */
   async createDefinition(input: AgentCreateInput): Promise<AgentView> {
-    await this.reviewConfigFields(createDefinitionReviewFields(input));
+    await this.reviewConfigFields(createDefinitionReviewFields(input), {
+      kind: 'definition',
+      model: input.initialDefinition?.model,
+    });
     const created = await this.options.service.create(input);
     publishBestEffort(this.options.publish ?? (() => undefined), {
       type: 'agent.created',
@@ -210,7 +258,10 @@ export class AgentApplication {
     readonly acceptedIssueIds?: readonly string[];
   }): Promise<{ readonly agent: AgentView; readonly config: AgentConfigDocument }> {
     const preview = new AgentImportService().create(input);
-    await this.reviewConfigFields([preview.canonicalContent]);
+    await this.reviewConfigFields([preview.canonicalContent], {
+      kind: 'definition',
+      model: preview.candidate.model,
+    });
     const created = await this.options.service.create({
       name: preview.proposedName,
       displayName: preview.candidate.name,
@@ -247,13 +298,16 @@ export class AgentApplication {
   }
 
   async update(input: AgentUpdateInput): Promise<AgentView> {
-    await this.reviewConfigFields([
-      input.displayName,
-      input.description,
-      input.persona,
-      input.systemPrompt,
-      ...(isNonTextAgentAvatar(input.avatar) ? [] : [input.avatar]),
-    ]);
+    await this.reviewConfigFields(
+      [
+        input.displayName,
+        input.description,
+        input.persona,
+        input.systemPrompt,
+        ...(isNonTextAgentAvatar(input.avatar) ? [] : [input.avatar]),
+      ],
+      { kind: 'existing', requestRef: input.requestRef },
+    );
     return this.options.service.update(input);
   }
 
@@ -366,8 +420,9 @@ export class AgentApplication {
 
   private async reviewConfigFields(
     values: ReadonlyArray<string | null | undefined>,
+    target: AgentConfigReviewTarget,
   ): Promise<void> {
-    await this.options.reviewConfigFields?.(values);
+    await this.options.reviewConfigFields?.(values, target);
   }
 
   private async scheduleGreeting(agent: AgentView): Promise<void> {
@@ -530,6 +585,23 @@ function reviewableAvatar(
 
 class GreetingDispatchClosedError extends Error {}
 
+async function agentConfigReviewModel(
+  service: LocalAgentService,
+  target: AgentConfigReviewTarget,
+): Promise<string | undefined> {
+  if (target.kind === 'definition') return target.model;
+  if (target.kind === 'existing') {
+    return (await service.getConfigDocument(target.requestRef)).configured.model;
+  }
+  try {
+    // Review the candidate, including model changes/removal, rather than the
+    // persisted definition or its cached effective-model preview.
+    return parseCanonicalAgentMarkdown(target.content, target.requestRef).model;
+  } catch (error) {
+    throw asAgentConfigServiceError(error);
+  }
+}
+
 async function reviewAgentConfigFields(
   safety: ContentSafetyService,
   values: ReadonlyArray<string | null | undefined>,

+ 263 - 0
packages/local-runtime-v2/src/application/agent/agent-config-review.test.ts

@@ -0,0 +1,263 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { BoundedInternalTurnPromptReadRegistry } from '@mavis/agent-runtime';
+
+import { DatabaseClient } from '../../infra/db/client.js';
+import { initializeDatabase } from '../../infra/db/initialize.js';
+import { AgentImportService } from '../../service/agent/index.js';
+import { DrizzleAgentRepository } from '../../service/agent/storage/agent.repository.js';
+import { ContentSafetyService, type SafetyCheckResult } from '../../service/content-safety/index.js';
+import { type LocalRuntimeConfig } from '../../service/model-system/index.js';
+import { createTestAgentService } from '../../../test/helpers/agent-service.js';
+import { createRuntimeAgentApplication } from './agent-application.js';
+
+const BYOK = 'custom_provider:local/test-model';
+const MANAGED = 'minimax/MiniMax-M3';
+const cleanup: Array<() => Promise<void> | void> = [];
+afterEach(async () => {
+  for (const dispose of cleanup.splice(0).reverse()) await dispose();
+});
+
+async function fixture(runtimeOwnerKind: string | undefined = 'tui') {
+  const dataDir = await mkdtemp(join(tmpdir(), 'agent-config-review-'));
+  cleanup.push(() => rm(dataDir, { recursive: true, force: true }));
+  const database = new DatabaseClient({ dataDir });
+  cleanup.push(() => database.close());
+  await initializeDatabase({ database, dataDir });
+  const repository = new DrizzleAgentRepository({ db: database.db, dataDir });
+  const service = createTestAgentService({ repository, nowMs: () => 10 });
+  cleanup.push(() => service.close());
+  const config: LocalRuntimeConfig = {
+    dataDir,
+    defaultModel: BYOK,
+    provider: {
+      minimax: {
+        options: { authMode: 'managed-login' },
+        models: { 'MiniMax-M3': {} },
+      },
+    },
+    custom_provider: {
+      local: {
+        options: { baseURL: 'https://example.test/v1' },
+        models: { 'test-model': {} },
+      },
+    },
+  };
+  const review = vi.fn(async (): Promise<SafetyCheckResult> => ({
+    pass: false, errorKind: 'auth_error',
+  }));
+  const application = createRuntimeAgentApplication({
+    agentService: service,
+    config: () => config,
+    pinService: { removeAgent: vi.fn() },
+    safety: new ContentSafetyService({ review }),
+    writeGlobalEvent: vi.fn(),
+    internalTurnPromptReads: new BoundedInternalTurnPromptReadRegistry(),
+    product: {},
+    options: {
+      runtimeOwnerKind,
+      compatibility: {
+        cron: { deleteAgentTasks: vi.fn(async () => undefined) },
+        greeting: { canSend: () => false, sendSystemReminder: vi.fn(async () => 'finished' as const) },
+      },
+    },
+  }, { session: { root: { getRootSessionByAgent: vi.fn() } } });
+  cleanup.push(() => application.close());
+  return { application, service, config, review };
+}
+
+function definition(name: string, model?: string) {
+  return { name, description: 'Synthetic agent', model, systemPrompt: 'Write clearly.' };
+}
+
+function markdown(name: string, model?: string) {
+  return `---\nname: ${name}\ndescription: Synthetic agent\n${model ? `model: ${model}\n` : ''}---\nWrite carefully.\n`;
+}
+
+type Fixture = Awaited<ReturnType<typeof fixture>>;
+type Operation = 'create' | 'update' | 'document' | 'import';
+const operations: Operation[] = ['create', 'update', 'document', 'import'];
+
+async function operation(f: Fixture, kind: Operation, model?: string) {
+  const name = `${kind}-agent`;
+  if (kind === 'create') {
+    await f.application.createDefinition({ name, initialDefinition: definition(name, model) });
+  } else if (kind === 'import') {
+    const content = markdown(name, model);
+    const preview = new AgentImportService().preview('claude-code', content);
+    await f.application.createImportedDefinition({
+      format: 'claude-code', content, expectedDigest: preview.sourceDigest, targetName: name,
+    });
+  } else {
+    await f.service.create({ name, initialDefinition: definition(name, model) });
+    if (kind === 'update') {
+      await f.application.update({
+        requestRef: `agent:${name}`, displayName: 'Renamed agent',
+        description: 'New description',
+      });
+    } else {
+      const current = await f.service.getConfigDocument(`agent:${name}`);
+      await f.application.putConfigDocument({
+        requestRef: `agent:${name}`, content: markdown(name, model),
+        expectedRevision: current.revision, expectedOwnerInstanceId: current.ownerInstanceId,
+      });
+    }
+  }
+  return f.service.getConfigDocument(`agent:${name}`);
+}
+
+describe('production Agent configuration review', () => {
+  it.each(operations)('persists signed-out BYOK %s without calling the managed gateway', async (kind) => {
+    const f = await fixture();
+    const saved = await operation(f, kind, BYOK);
+    expect(saved.configured.model).toBe(BYOK);
+    expect(saved.configured.systemPrompt).toContain(
+      kind === 'create' || kind === 'update' ? 'Write clearly.' : 'Write carefully.',
+    );
+    if (kind === 'update') {
+      expect((await f.service.get('agent:update-agent')).displayName).toBe('Renamed agent');
+    }
+    expect(f.review).not.toHaveBeenCalled();
+  });
+
+  it.each(operations)('uses the runtime default only when %s has no explicit Agent model', async (kind) => {
+    const f = await fixture();
+    await operation(f, kind);
+    expect(f.review).not.toHaveBeenCalled();
+  });
+
+  it.each(operations)('retains managed review for %s even with a BYOK runtime default', async (kind) => {
+    const f = await fixture();
+    await expect(operation(f, kind, MANAGED)).rejects.toMatchObject({ code: 'CONTENT_POLICY_VIOLATION' });
+    expect(f.review).toHaveBeenCalled();
+    if (kind === 'create' || kind === 'import') {
+      await expect(f.service.get(`agent:${kind}-agent`)).rejects.toMatchObject({ code: 'AGENT_NOT_FOUND' });
+    } else {
+      const saved = await f.service.getConfigDocument(`agent:${kind}-agent`);
+      expect(saved.configured.systemPrompt).toBe('Write clearly.');
+      expect((await f.service.get(`agent:${kind}-agent`)).displayName).not.toBe('Renamed agent');
+    }
+  });
+
+  it.each(['cli', 'tui'])('uses the explicit BYOK Agent model over a managed default in %s', async (owner) => {
+    const f = await fixture(owner);
+    f.config.defaultModel = MANAGED;
+    await operation(f, 'update', BYOK);
+    expect(f.review).not.toHaveBeenCalled();
+  });
+
+  it.each(['electron', 'unknown'])('preserves %s configuration review for BYOK', async (owner) => {
+    const f = await fixture(owner);
+    await expect(operation(f, 'create', BYOK)).rejects.toMatchObject({ code: 'CONTENT_POLICY_VIOLATION' });
+    expect(f.review).toHaveBeenCalled();
+  });
+
+  it('resolves bare custom-provider keys using the Agent catalog rules', async () => {
+    const f = await fixture();
+    await operation(f, 'create', 'local/test-model');
+    expect(f.review).not.toHaveBeenCalled();
+  });
+
+  it('does not mistake a managed provider with the same key for a custom provider', async () => {
+    const f = await fixture();
+    f.config.provider.local = { options: { authMode: 'managed-login' }, models: { 'test-model': {} } };
+    await expect(operation(f, 'create', 'local/test-model')).rejects.toMatchObject({ code: 'CONTENT_POLICY_VIOLATION' });
+  });
+
+  it.each(['missing/test-model', 'custom_provider:local/missing', 'malformed'])('keeps the gate for unresolved model %s', async (model) => {
+    const f = await fixture();
+    await expect(operation(f, 'create', model)).rejects.toMatchObject({ code: 'CONTENT_POLICY_VIOLATION' });
+    expect(f.review).toHaveBeenCalled();
+  });
+
+  it('keeps the gate for a disabled custom provider', async () => {
+    const f = await fixture();
+    f.config.custom_provider!.local!.enabled = false;
+    await expect(operation(f, 'create', BYOK)).rejects.toMatchObject({ code: 'CONTENT_POLICY_VIOLATION' });
+  });
+
+  it.each([MANAGED, undefined])('reviews the candidate when a BYOK document changes its model to %s', async (model) => {
+    const f = await fixture();
+    await f.application.createDefinition({ name: 'writer', initialDefinition: definition('writer', BYOK) });
+    const current = await f.service.getConfigDocument('agent:writer');
+    f.config.defaultModel = MANAGED;
+    const content = markdown('writer', model);
+    await expect(f.application.putConfigDocument({
+      requestRef: 'agent:writer', content, expectedRevision: current.revision,
+      expectedOwnerInstanceId: current.ownerInstanceId,
+    })).rejects.toMatchObject({ code: 'CONTENT_POLICY_VIOLATION' });
+    expect(f.review).toHaveBeenCalledWith(content.trim(), 205);
+    expect((await f.service.getConfigDocument('agent:writer')).revision).toBe(current.revision);
+  });
+
+  it('can explicitly switch a managed document to BYOK without a managed login', async () => {
+    const f = await fixture();
+    await f.service.create({ name: 'writer', initialDefinition: definition('writer', MANAGED) });
+    const current = await f.service.getConfigDocument('agent:writer');
+    await f.application.putConfigDocument({
+      requestRef: 'agent:writer', content: markdown('writer', BYOK),
+      expectedRevision: current.revision, expectedOwnerInstanceId: current.ownerInstanceId,
+    });
+    expect((await f.service.getConfigDocument('agent:writer')).configured.model).toBe(BYOK);
+    expect(f.review).not.toHaveBeenCalled();
+  });
+
+  it('reads current inherited defaults again on every edit', async () => {
+    const f = await fixture();
+    await f.application.createDefinition({ name: 'writer', displayName: 'Original' });
+    await f.application.update({ requestRef: 'agent:writer', displayName: 'Local name' });
+    f.config.defaultModel = MANAGED;
+    await expect(f.application.update({ requestRef: 'agent:writer', displayName: 'Blocked name' }))
+      .rejects.toMatchObject({ code: 'CONTENT_POLICY_VIOLATION' });
+    expect((await f.service.get('agent:writer')).displayName).toBe('Local name');
+  });
+
+  it.each([
+    { pass: true }, { pass: false, errorKind: 'api_error' },
+    { pass: false, errorKind: 'rejected' }, { pass: false, errorKind: 'auth_error' },
+    { pass: false, errorKind: 'local_error' }, { pass: false },
+  ] satisfies SafetyCheckResult[])('preserves managed verdict semantics for %j', async (verdict) => {
+    const f = await fixture();
+    f.review.mockResolvedValue(verdict);
+    const save = operation(f, 'create', MANAGED);
+    if (verdict.pass || ('errorKind' in verdict && verdict.errorKind === 'api_error')) await save;
+    else await expect(save).rejects.toMatchObject({ code: 'CONTENT_POLICY_VIOLATION' });
+    expect(f.review).toHaveBeenCalled();
+  });
+
+  it('preserves model validation and canonical document conflict checks', async () => {
+    const f = await fixture();
+    await operation(f, 'create', BYOK);
+    const current = await f.service.getConfigDocument('agent:create-agent');
+    await expect(f.application.putConfigDocument({
+      requestRef: 'agent:create-agent', content: markdown('create-agent', BYOK),
+      expectedRevision: 'stale-revision', expectedOwnerInstanceId: current.ownerInstanceId,
+    })).rejects.toMatchObject({ code: 'AGENT_CONFIG_REVISION_CONFLICT' });
+    f.service.bindCandidateModelValidator(async () => ({ ok: false, reason: 'unavailable' }));
+    await expect(f.application.update({ requestRef: 'agent:create-agent', displayName: 'Blocked' }))
+      .rejects.toMatchObject({ code: 'AGENT_CONFIG_INVALID' });
+    expect(f.review).not.toHaveBeenCalled();
+  });
+
+  it('rejects malformed documents without persistence or an unrelated managed request', async () => {
+    const f = await fixture();
+    await operation(f, 'create', BYOK);
+    const current = await f.service.getConfigDocument('agent:create-agent');
+    await expect(f.application.putConfigDocument({
+      requestRef: 'agent:create-agent', content: '---\nname: [\n---\nInvalid',
+      expectedRevision: current.revision, expectedOwnerInstanceId: current.ownerInstanceId,
+    })).rejects.toMatchObject({ code: 'AGENT_CONFIG_INVALID' });
+    expect((await f.service.getConfigDocument('agent:create-agent')).revision).toBe(current.revision);
+    expect(f.review).not.toHaveBeenCalled();
+  });
+
+  it.each(['persona', 'systemPrompt'] as const)('keeps the canonical editing requirement for legacy %s patches', async (field) => {
+    const f = await fixture();
+    await operation(f, 'create', BYOK);
+    await expect(f.application.update({ requestRef: 'agent:create-agent', [field]: 'New instructions' }))
+      .rejects.toMatchObject({ code: 'AGENT_CONFIG_INVALID' });
+    expect(f.review).not.toHaveBeenCalled();
+  });
+});

+ 29 - 0
packages/local-runtime-v2/src/application/config-field-review-policy.ts

@@ -0,0 +1,29 @@
+import { resolveProviderAuthMode } from '@mavis/config';
+
+import {
+  isLegacyMinimaxProvider,
+  parseSourceQualifiedModelKey,
+  type LocalRuntimeConfig,
+} from '../service/model-system/index.js';
+
+/** Only a known unmanaged route exempts local CLI configuration from managed review. */
+export function isUnmanagedConfigModel(
+  config: LocalRuntimeConfig,
+  modelKey: string | undefined,
+): boolean {
+  const model = parseSourceQualifiedModelKey(modelKey);
+  if (!model || isLegacyMinimaxProvider(config, model.providerId)) return false;
+  if (model.source === 'minimax_api') return true;
+  if (model.source === 'custom_provider') {
+    const provider = config.custom_provider?.[model.providerKey];
+    return provider !== undefined && provider.enabled !== false;
+  }
+  if (model.providerId === 'minimax' && config.minimaxModelSource === 'minimax_api_key') {
+    return true;
+  }
+  const provider = config.provider?.[model.providerId];
+  return (
+    provider !== undefined &&
+    resolveProviderAuthMode(provider.options).authMode !== 'managed-login'
+  );
+}

+ 6 - 35
packages/local-runtime-v2/src/application/session/session-title-policy.ts

@@ -1,19 +1,14 @@
-import { resolveProviderAuthMode } from "@mavis/config";
-
 import {
   SAFETY_SCENE,
   type ContentSafetyService,
 } from "../../service/content-safety/index.js";
-import {
-  isLegacyMinimaxProvider,
-  parseSourceQualifiedModelKey,
-  type LocalRuntimeConfig,
-} from "../../service/model-system/index.js";
+import type { LocalRuntimeConfig } from "../../service/model-system/index.js";
 import type {
   SessionAgentDefinition,
   SessionRecord,
   SessionRecordServiceDeps,
 } from "../../service/session-system/index.js";
+import { isUnmanagedConfigModel } from "../config-field-review-policy.js";
 
 /** Local CLI metadata follows the selected provider, without requiring inference credentials. */
 export function createSessionTitlePolicy(input: {
@@ -37,7 +32,7 @@ export function createSessionTitlePolicy(input: {
           config,
           input.readDefinition,
         );
-        if (model && isUnmanagedProvider(config, model)) return false;
+        if (isUnmanagedConfigModel(config, model)) return false;
       }
       // Missing/ambiguous provider context retains the existing gate, as do all
       // managed routes. In particular, auth and local errors still block.
@@ -52,36 +47,12 @@ async function selectedModel(
   readDefinition: (
     sessionId: string,
   ) => Promise<SessionAgentDefinition | undefined>,
-): Promise<ReturnType<typeof parseSourceQualifiedModelKey>> {
+): Promise<string | undefined> {
   if (session.sessionKind === "task") {
     const binding = await readDefinition(session.sessionId);
     if (binding?.definition.definitionVersion !== 2) return undefined;
     const { providerId, modelId } = binding.definition.model;
-    return parseSourceQualifiedModelKey(`${providerId}/${modelId}`);
-  }
-  return parseSourceQualifiedModelKey(
-    session.effectiveModel ?? config.defaultModel,
-  );
-}
-
-function isUnmanagedProvider(
-  config: LocalRuntimeConfig,
-  model: NonNullable<ReturnType<typeof parseSourceQualifiedModelKey>>,
-): boolean {
-  if (isLegacyMinimaxProvider(config, model.providerId)) return false;
-  if (model.source === "minimax_api") return true;
-  if (model.source === "custom_provider") {
-    const provider = config.custom_provider?.[model.providerKey];
-    return provider !== undefined && provider.enabled !== false;
+    return `${providerId}/${modelId}`;
   }
-  if (
-    model.providerId === "minimax" &&
-    config.minimaxModelSource === "minimax_api_key"
-  )
-    return true;
-  const provider = config.provider?.[model.providerId];
-  return (
-    provider !== undefined &&
-    resolveProviderAuthMode(provider.options).authMode !== "managed-login"
-  );
+  return session.effectiveModel ?? config.defaultModel;
 }

+ 7 - 1
packages/local-runtime-v2/src/services.ts

@@ -1208,7 +1208,13 @@ async function initializeSessionApplications(
         failure,
       ),
   });
-  const agentApplication = createRuntimeAgentApplication(input, applications);
+  const agentApplication = createRuntimeAgentApplication(
+    {
+      ...input,
+      config: input.options.compatibility.agentHost.preparation.configBuilder.config,
+    },
+    applications,
+  );
   const runtimeConversation = composeV1Conversation({
     attachmentRegistration: input.options.compatibility.attachmentRegistration,
     rootAgents: input.agentSessionPorts.roots,

+ 2 - 0
release/public-source.json

@@ -552,6 +552,7 @@
     "packages/local-runtime-v2/docs/project-mcp.md",
     "packages/local-runtime-v2/package.json",
     "packages/local-runtime-v2/src/application/agent/agent-application.ts",
+    "packages/local-runtime-v2/src/application/agent/agent-config-review.test.ts",
     "packages/local-runtime-v2/src/application/agent/execution-source.ts",
     "packages/local-runtime-v2/src/application/agent/goal-budget-summary-reminder.ts",
     "packages/local-runtime-v2/src/application/agent/goal-budget-tool-policy.ts",
@@ -565,6 +566,7 @@
     "packages/local-runtime-v2/src/application/agent/runtime-agent-product.ts",
     "packages/local-runtime-v2/src/application/agent/runtime-browser-use-composition.ts",
     "packages/local-runtime-v2/src/application/agent/source-reference-extension.ts",
+    "packages/local-runtime-v2/src/application/config-field-review-policy.ts",
     "packages/local-runtime-v2/src/application/context.ts",
     "packages/local-runtime-v2/src/application/conversation/attachment-registration.ts",
     "packages/local-runtime-v2/src/application/conversation/conversation-application.ts",

+ 1 - 0
test/vitest-suites.json

@@ -98,6 +98,7 @@
       "packages/local-runtime-v2/src/service/turn-system/agent-host/execution/executor.test.ts",
       "packages/local-runtime-v2/src/services.test.ts",
       "packages/local-runtime-v2/src/application/session/session-title-policy.test.ts",
+      "packages/local-runtime-v2/src/application/agent/agent-config-review.test.ts",
       "packages/local-runtime-v2/test/unit/agent/builtin/catalog.test.ts",
       "packages/local-runtime-v2/test/unit/agent/storage/agent.repository.test.ts",
       "packages/local-runtime-v2/test/unit/agent/storage/canonical-agent-config.test.ts",