Browse Source

fix: scope CLI session title review to managed providers

hetaoBackend 2 tháng trước cách đây
mục cha
commit
28835290be

+ 9 - 4
packages/local-runtime-v2/src/application/session/runtime-session-composition.ts

@@ -5,7 +5,7 @@ import type { GlobalEventInput } from '@mavis/shared/global-events';
 import type { V1SessionCompatibility } from '../../compat/v1/session.js';
 import { AgentServiceError, type LocalAgentService } from '../../service/agent/index.js';
 import type { BrowserUseService } from '../../service/browser-use/index.js';
-import { SAFETY_SCENE, type ContentSafetyService } from '../../service/content-safety/index.js';
+import type { ContentSafetyService } from '../../service/content-safety/index.js';
 import type { CronMetricsClient } from '../../service/cron/index.js';
 import type { ComposedInspector } from '../../service/llm-context-inspector/index.js';
 import {
@@ -54,6 +54,7 @@ import { ModelProviderApplication } from './model-provider-application.js';
 import { createRuntimeCompactionFactSink } from './runtime-compaction-facts.js';
 import { describeError } from './turn-message-delivery.js';
 import { queryCollapseSteeringProjection } from '../conversation/index.js';
+import { createSessionTitlePolicy } from './session-title-policy.js';
 
 export interface ProductionSessionComposition {
   readonly product: ProductionAgentProductCapabilities;
@@ -162,9 +163,13 @@ export function createProductionSessionComposition(
     agents: input.agentSessionPorts.directory,
     rootAgents: input.agentSessionPorts.roots,
     defaultWorkspaceDir: input.compatibility.workspace.defaultDirectory,
-    titlePolicy: {
-      blocks: (title) => input.safety.blocks(title, SAFETY_SCENE.ConfigField),
-    },
+    titlePolicy: createSessionTitlePolicy({
+      runtimeOwnerKind: input.runtimeOwnerKind,
+      config: input.modelConfig.read,
+      safety: input.safety,
+      readDefinition: (sessionId) =>
+        sessionSystem.repositories.sessions.getSessionAgentDefinition(sessionId),
+    }),
     resolveRequestedModel: (model) => resolveRequestedSessionModel(input.modelConfig.read(), model),
     backfillDiagnostics: createSessionBackfillDiagnostics({
       logger: input.logger,

+ 288 - 0
packages/local-runtime-v2/src/application/session/session-title-policy.test.ts

@@ -0,0 +1,288 @@
+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 { DatabaseClient } from "../../infra/db/client.js";
+import { initializeDatabase } from "../../infra/db/initialize.js";
+import {
+  ContentSafetyService,
+  type SafetyCheckResult,
+} from "../../service/content-safety/index.js";
+import type { LocalRuntimeConfig } from "../../service/model-system/index.js";
+import { createSessionRepository } from "../../service/session-system/sessions/repo/drizzle.js";
+import { SessionRecordService } from "../../service/session-system/sessions/lifecycle/record-service.js";
+import type {
+  SessionAgentDefinition,
+  SessionRecord,
+} from "../../service/session-system/index.js";
+import { createSessionTitlePolicy } from "./session-title-policy.js";
+
+const session: SessionRecord = {
+  sessionId: "rename-test",
+  agentName: "test-agent",
+  workspaceDir: "/synthetic",
+  runtime: "pi-agent",
+  sessionType: "branch",
+  sessionKind: "conversation",
+  status: "idle",
+  archived: false,
+  createdAtMs: 1,
+  updatedAtMs: 1,
+  title: "Original",
+  effectiveModel: "custom_provider:byok/test-model",
+};
+const config: LocalRuntimeConfig = {
+  dataDir: "/synthetic",
+  defaultModel: "minimax/MiniMax-M3",
+  provider: { minimax: { options: { authMode: "managed-login" } } },
+  custom_provider: { byok: { options: { baseURL: "https://example.com/v1" } } },
+};
+function fixture(
+  options: {
+    runtimeOwnerKind?: string;
+    config?: LocalRuntimeConfig;
+    definition?: SessionAgentDefinition;
+  } = {},
+) {
+  // Signed-out managed gateway. The BYOK path must never send the title here.
+  const review = vi.fn(async (): Promise<SafetyCheckResult> => ({
+    pass: false,
+    errorKind: "auth_error",
+  }));
+  const readDefinition = vi.fn(async () => options.definition);
+  const policy = createSessionTitlePolicy({
+    runtimeOwnerKind: options.runtimeOwnerKind ?? "tui",
+    config: () => options.config ?? config,
+    safety: new ContentSafetyService({ review }),
+    readDefinition,
+  });
+  return { policy, review, readDefinition };
+}
+
+const cleanup: Array<() => Promise<void> | void> = [];
+afterEach(async () => {
+  for (const close of cleanup.splice(0).reverse()) await close();
+});
+
+describe("CLI session title review", () => {
+  it("persists a signed-out BYOK rename through the real record service and SQLite", async () => {
+    const dataDir = await mkdtemp(join(tmpdir(), "session-title-review-"));
+    cleanup.push(() => rm(dataDir, { recursive: true, force: true }));
+    const database = new DatabaseClient({ dataDir });
+    cleanup.push(() => database.close());
+    await initializeDatabase({ database, dataDir });
+    const sessions = createSessionRepository({
+      db: database.db,
+      nowMs: () => 2,
+    });
+    await sessions.create(session);
+    const { policy, review } = fixture();
+    const records = new SessionRecordService({
+      sessions,
+      metadata: sessions,
+      agents: { getDefaults: async () => undefined },
+      runLocation: { resolve: async () => undefined },
+      titlePolicy: policy,
+      facts: { handle: vi.fn() },
+    });
+    await records.mutateSession(session.sessionId, {
+      title: "Renamed locally",
+    });
+    expect((await sessions.get(session.sessionId))?.title).toBe(
+      "Renamed locally",
+    );
+    expect(review).not.toHaveBeenCalled();
+
+    await sessions.update(session.sessionId, {
+      effectiveModel: "minimax/MiniMax-M3",
+    });
+    await expect(
+      records.mutateSession(session.sessionId, { title: "Must not persist" }),
+    ).rejects.toMatchObject({ reason: "content-policy-rejected" });
+    expect((await sessions.get(session.sessionId))?.title).toBe(
+      "Renamed locally",
+    );
+    expect(review).toHaveBeenCalledWith("Must not persist", 205);
+  });
+
+  it.each(["tui", "cli"])(
+    "uses the Session selection ahead of the runtime default in %s",
+    async (runtimeOwnerKind) => {
+      const { policy, review } = fixture({ runtimeOwnerKind });
+      await expect(policy.blocks("BYOK title", session)).resolves.toBe(false);
+      expect(review).not.toHaveBeenCalled();
+      await expect(
+        policy.blocks("Managed title", {
+          ...session,
+          effectiveModel: "minimax/MiniMax-M3",
+        }),
+      ).resolves.toBe(true);
+    },
+  );
+
+  it("reads the current default for an unselected Session without caching the route", async () => {
+    const current = {
+      ...config,
+      defaultModel: "custom_provider:byok/test-model",
+    };
+    const { policy, review } = fixture({ config: current });
+    await expect(
+      policy.blocks("Local", { ...session, effectiveModel: null }),
+    ).resolves.toBe(false);
+    current.defaultModel = "minimax/MiniMax-M3";
+    await expect(
+      policy.blocks("Managed", { ...session, effectiveModel: null }),
+    ).resolves.toBe(true);
+    expect(review).toHaveBeenCalledTimes(1);
+  });
+
+  it.each([
+    { pass: true },
+    { pass: false, errorKind: "rejected" },
+    { pass: false, errorKind: "auth_error" },
+    { pass: false, errorKind: "local_error" },
+    { pass: false, errorKind: "api_error" },
+    { pass: false },
+  ] satisfies SafetyCheckResult[])(
+    "preserves managed verdict semantics for %j",
+    async (verdict) => {
+      const { policy, review } = fixture();
+      review.mockResolvedValue(verdict);
+      await expect(
+        policy.blocks("Managed title", {
+          ...session,
+          effectiveModel: "minimax/MiniMax-M3",
+        }),
+      ).resolves.toBe(
+        !verdict.pass &&
+          ("errorKind" in verdict ? verdict.errorKind !== "api_error" : true),
+      );
+      expect(review).toHaveBeenCalledWith("Managed title", 205);
+    },
+  );
+
+  it("blocks unexpected review exceptions for managed providers", async () => {
+    const { policy, review } = fixture();
+    review.mockRejectedValue(new Error("local checker failure"));
+    await expect(
+      policy.blocks("Managed title", {
+        ...session,
+        effectiveModel: "minimax/MiniMax-M3",
+      }),
+    ).resolves.toBe(true);
+    await expect(policy.blocks("Local title", session)).resolves.toBe(false);
+    expect(review).toHaveBeenCalledTimes(1);
+  });
+
+  it.each([
+    "minimax_api/test-model",
+    "minimax/test-model",
+    "external/test-model",
+  ])("allows non-managed credentials on %s", async (effectiveModel) => {
+    const { policy, review } = fixture({
+      config: {
+        ...config,
+        minimaxModelSource: "minimax_api_key",
+        provider: {
+          ...config.provider,
+          external: { options: { authMode: "oauth" } },
+        },
+      },
+    });
+    await expect(
+      policy.blocks("Local title", { ...session, effectiveModel }),
+    ).resolves.toBe(false);
+    expect(review).not.toHaveBeenCalled();
+  });
+
+  it.each([
+    "missing/test",
+    "custom_provider:missing/test",
+    "custom_provider:minimax-legacy/test",
+    "malformed",
+  ])(
+    "retains review for unknown or legacy context %s",
+    async (effectiveModel) => {
+      const { policy } = fixture();
+      await expect(
+        policy.blocks("Title", { ...session, effectiveModel }),
+      ).resolves.toBe(true);
+    },
+  );
+
+  it("retains review for configured managed aliases and inferred managed URLs", async () => {
+    const { policy } = fixture({
+      config: {
+        ...config,
+        provider: {
+          alias: { options: { authMode: "managed-login" } },
+          inferred: { options: { baseURL: "https://agent.minimax.cn/v1" } },
+        },
+      },
+    });
+    for (const provider of ["alias", "inferred"]) {
+      await expect(
+        policy.blocks("Title", {
+          ...session,
+          effectiveModel: `${provider}/test`,
+        }),
+      ).resolves.toBe(true);
+    }
+  });
+
+  it.each(["minimax", "custom_provider:byok"])(
+    "uses the frozen Task provider %s",
+    async (providerId) => {
+      const { policy, review } = fixture({
+        definition: {
+          sessionId: session.sessionId,
+          definition: {
+            definitionVersion: 2,
+            exactOwnerName: "test-agent",
+            systemPrompt: "",
+            capabilities: {
+              tools: [],
+              mcpServers: [],
+              skills: [],
+              extensionSkills: [],
+            },
+            model: { providerId, modelId: "test-model" },
+            project: { workspaceDir: "/synthetic", isDefaultWorkspace: false },
+          },
+        },
+      });
+      await expect(
+        policy.blocks("Task title", {
+          ...session,
+          sessionKind: "task",
+          effectiveModel: "minimax/MiniMax-M3",
+        }),
+      ).resolves.toBe(providerId === "minimax");
+      expect(review).toHaveBeenCalledTimes(providerId === "minimax" ? 1 : 0);
+    },
+  );
+
+  it("retains review when a Task definition is missing and propagates storage errors", async () => {
+    const { policy, readDefinition } = fixture();
+    const task = { ...session, sessionKind: "task" as const };
+    await expect(policy.blocks("Task title", task)).resolves.toBe(true);
+    readDefinition.mockRejectedValue(new Error("storage unavailable"));
+    await expect(policy.blocks("Task title", task)).rejects.toThrow(
+      "storage unavailable",
+    );
+  });
+
+  it("preserves non-CLI policy and skips blank titles before any lookup", async () => {
+    const { policy, review, readDefinition } = fixture({
+      runtimeOwnerKind: "electron",
+    });
+    await expect(policy.blocks("Local title", session)).resolves.toBe(true);
+    review.mockClear();
+    await expect(
+      policy.blocks("   ", { ...session, sessionKind: "task" }),
+    ).resolves.toBe(false);
+    expect(review).not.toHaveBeenCalled();
+    expect(readDefinition).not.toHaveBeenCalled();
+  });
+});

+ 87 - 0
packages/local-runtime-v2/src/application/session/session-title-policy.ts

@@ -0,0 +1,87 @@
+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 {
+  SessionAgentDefinition,
+  SessionRecord,
+  SessionRecordServiceDeps,
+} from "../../service/session-system/index.js";
+
+/** Local CLI metadata follows the selected provider, without requiring inference credentials. */
+export function createSessionTitlePolicy(input: {
+  readonly runtimeOwnerKind?: string;
+  readonly config: () => LocalRuntimeConfig;
+  readonly safety: ContentSafetyService;
+  readonly readDefinition: (
+    sessionId: string,
+  ) => Promise<SessionAgentDefinition | undefined>;
+}): SessionRecordServiceDeps["titlePolicy"] {
+  return {
+    blocks: async (title, session) => {
+      if (!title.trim()) return false;
+      if (
+        input.runtimeOwnerKind === "tui" ||
+        input.runtimeOwnerKind === "cli"
+      ) {
+        const config = input.config();
+        const model = await selectedModel(
+          session,
+          config,
+          input.readDefinition,
+        );
+        if (model && isUnmanagedProvider(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.
+      return input.safety.blocks(title, SAFETY_SCENE.ConfigField);
+    },
+  };
+}
+
+async function selectedModel(
+  session: SessionRecord,
+  config: LocalRuntimeConfig,
+  readDefinition: (
+    sessionId: string,
+  ) => Promise<SessionAgentDefinition | undefined>,
+): Promise<ReturnType<typeof parseSourceQualifiedModelKey>> {
+  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;
+  }
+  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"
+  );
+}

+ 2 - 2
packages/local-runtime-v2/src/service/session-system/sessions/lifecycle/record-service.ts

@@ -206,7 +206,7 @@ export interface SessionRecordServiceDeps {
   readonly runLocation: {
     resolve(input: unknown, workspaceDir: string): Promise<SessionRecord['runLocation']>;
   };
-  readonly titlePolicy: { blocks(title: string): Promise<boolean> };
+  readonly titlePolicy: { blocks(title: string, session: SessionRecord): Promise<boolean> };
   readonly artifacts?: {
     initialize(sessionId: string): Promise<void>;
     delete(sessionId: string): Promise<void>;
@@ -813,7 +813,7 @@ export class SessionRecordService
     if (
       fields.title !== undefined &&
       fields.title !== null &&
-      (await this.deps.titlePolicy.blocks(fields.title))
+      (await this.deps.titlePolicy.blocks(fields.title, current))
     ) {
       throw new SessionServiceError('content-policy-rejected', 'Content validation failed');
     }

+ 25 - 0
packages/local-runtime-v2/src/services.test.ts

@@ -2356,6 +2356,31 @@ describe("runtime services agent profile composition", () => {
   });
 });
 
+describe("production Session title policy wiring", () => {
+  it("skips the signed-out gateway only for the selected BYOK Session", async () => {
+    const compatibility = defaultCompatibility();
+    const review = vi.mocked(compatibility.safety.review);
+    review.mockResolvedValue({ pass: false, errorKind: "auth_error" });
+    await createRuntimeServices({
+      db: {} as AppDb, dataDir: "/data", logger: noopLogger,
+      eventBus: new EventBus<GlobalEvent>(), compatibility,
+      agentService: localAgentService, runtimeOwnerKind: "tui", capabilityProfile: "cli",
+    });
+    const policy = mocked.sessionOptions?.["titlePolicy"] as import("./service/session-system/index.js").SessionRecordServiceDeps["titlePolicy"];
+    const session: import("./service/session-system/index.js").SessionRecord = {
+      sessionId: "rename", agentName: "test", workspaceDir: "/data",
+      runtime: "pi-agent", sessionType: "branch", sessionKind: "conversation",
+      archived: false, status: "idle", createdAtMs: 1, updatedAtMs: 1,
+      effectiveModel: "custom_provider:openai-work/test-model",
+    };
+    review.mockClear();
+    await expect(policy.blocks("Local rename", session)).resolves.toBe(false);
+    expect(review).not.toHaveBeenCalled();
+    await expect(policy.blocks("Managed rename", { ...session, effectiveModel: "minimax/MiniMax-M3" })).resolves.toBe(true);
+    expect(review).toHaveBeenCalledWith("Managed rename", 205);
+  });
+});
+
 describe("runtime startup preserves Session model selections", () => {
   it.each(["tui", "electron"] as const)(
     "does not scan or rewrite shared Sessions for %s",

+ 2 - 0
release/public-source.json

@@ -624,6 +624,8 @@
     "packages/local-runtime-v2/src/application/session/runtime-session-composition.ts",
     "packages/local-runtime-v2/src/application/session/runtime-skill-application.ts",
     "packages/local-runtime-v2/src/application/session/runtime-user-applications.ts",
+    "packages/local-runtime-v2/src/application/session/session-title-policy.test.ts",
+    "packages/local-runtime-v2/src/application/session/session-title-policy.ts",
     "packages/local-runtime-v2/src/application/session/task-agent-binding-capture.ts",
     "packages/local-runtime-v2/src/application/session/task-agent-ready-inventory.ts",
     "packages/local-runtime-v2/src/application/session/turn-lifecycle-event-observer.ts",

+ 1 - 0
test/vitest-suites.json

@@ -95,6 +95,7 @@
       "packages/agent-core/test/unit/pi-turn-runner/llm-retry.test.ts",
       "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/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",