refactor(agent)!: migrate to Pi Durable and embed the agent queue (#525)

* refactor(agent)!: migrate sessions to Pi Durable

Replace patched AgentHarness storage with per-session SQLite and PostgreSQL commit mirroring. Migrate legacy history automatically and run agent queues with the main server.

BREAKING CHANGE: Remove standalone agent workers and return native Pi entry records from chat history APIs.

* fix(agent): constrain session log dialog scrolling

Keep the header visible and wrap long output while log entries and expanded records scroll within the dialog. Cover desktop and narrow viewports through the dashboard Sessions flow.

* fix(agent): hide entry IDs from session log card headers

Retain internal entry IDs in expanded raw records for debugging. Verify that card headers omit the IDs while raw JSON preserves them.

* test(e2e): handle browser wheel limits in session log checks

Verify that a normal wheel event moves the viewport before explicitly scrolling to the final record. Keep the dialog bounds, fixed header, wrapping, and expanded-record assertions.

* fix(agent): select model providers without inheriting unrelated auth

* fix(webui): prevent resize feedback when toggling agent panel

* test(agent): reproduce concurrent comment session races

* fix(agent): serialize comment sessions and deduplicate history

* docs(changelog): consolidate Pi Durable changes into one entry
This commit is contained in:
Yiling-J
2026-11-11 16:05:18 +08:00
committed by GitHub
parent 843a56304c
commit 35a0e82284
120 changed files with 7593 additions and 5972 deletions
+8 -6
View File
@@ -8,9 +8,12 @@
* discovery/auth/status and for tools not in direct mode.
*/
import { Type } from '@sinclair/typebox'
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
import type {
ToolRegistration as AgentTool,
ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import '@shumai/db/src/prisma-json-types'
import { Type } from '@sinclair/typebox'
import type { ToolMetadata } from './mcp-tool-registry'
import { isToolAllowed } from './mcp-tool-registry'
import { toToolParameters } from './mcp-tool-schema'
@@ -24,7 +27,7 @@ export interface DirectToolCallOptions {
args: Record<string, unknown>,
): Promise<{
ok: boolean
content: AgentToolResult<Record<string, unknown>>['content']
content: NonNullable<AgentToolResult['output']>
}>
}
@@ -63,18 +66,17 @@ export function buildDirectTools(
const parameters = toToolParameters(tool.inputSchema)
tools.push({
name: tool.name,
label: tool.name,
description:
tool.description || `Call ${tool.originalName} on MCP server ${opts.serverName}.`,
parameters: parameters as unknown as import('typebox').TSchema,
execute: async (_toolCallId, args): Promise<AgentToolResult<Record<string, unknown>>> => {
execute: async (args): Promise<AgentToolResult> => {
const result = await opts.callTool(
opts.serverId,
tool.originalName,
args as Record<string, unknown>,
)
return {
content: result.content,
output: result.content,
details: { server: opts.serverName, tool: tool.originalName },
}
},
+13 -10
View File
@@ -7,12 +7,15 @@
* server(list) > status.
*/
import { Type } from '@sinclair/typebox'
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
import type {
ToolRegistration as AgentTool,
ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import { Type } from 'typebox'
import type { McpToolRegistry, ToolMetadata } from './mcp-tool-registry'
import { formatSchema } from './mcp-tool-schema'
type ProxyToolResult = AgentToolResult<Record<string, unknown>>
type ProxyToolResult = AgentToolResult
/** Truncated instructions head baked into the proxy tool description (L1). */
const INSTRUCTIONS_SNIPPET_LENGTH = 150
@@ -45,7 +48,7 @@ export type ConnectionOutcome =
export interface CallToolOutcome {
ok: boolean
content: AgentToolResult<Record<string, unknown>>['content']
content: NonNullable<AgentToolResult['output']>
}
export interface McpProxyToolContext {
@@ -167,7 +170,7 @@ function parseArgs(raw: unknown): Record<string, unknown> {
}
function contentText(text: string): ProxyToolResult {
return { content: [{ type: 'text', text }], details: {} }
return { output: [{ type: 'text', text }], details: {} }
}
/** Transform MCP content blocks into model content blocks. */
@@ -181,7 +184,7 @@ export function transformMcpContent(
uri?: string
name?: string
}>,
): AgentToolResult<Record<string, unknown>>['content'] {
): NonNullable<AgentToolResult['output']> {
return content.map((c) => {
if (c.type === 'text') {
return { type: 'text', text: c.text ?? '' }
@@ -331,10 +334,10 @@ function renderServerListing(
export function buildProxyTool(ctx: McpProxyToolContext): AgentTool<typeof proxyToolSchema> {
return {
name: 'mcp',
label: 'MCP Tools',
description: buildProxyDescription(ctx.servers),
parameters: proxyToolSchema,
execute: async (_toolCallId, params): Promise<ProxyToolResult> => {
execute: async (params): Promise<ProxyToolResult> => {
const action = params.action
const server = params.server
const tool = params.tool
@@ -396,10 +399,10 @@ export function buildProxyTool(ctx: McpProxyToolContext): AgentTool<typeof proxy
parseArgs(params.args),
)
if (outcome.ok) {
return { content: outcome.content, details: {} }
return { output: outcome.content, details: {} }
}
return {
content: outcome.content,
output: outcome.content,
details: { error: 'tool_call_failed', tool, server: resolved.serverId },
}
}
+26 -51
View File
@@ -1,11 +1,12 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import '@shumai/db/src/prisma-json-types'
import { setupTestDbHooks } from '@shumai/db/test'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { invokeTool } from '../agent/tool-test-utils'
import { McpService } from './mcp-service'
import {
startTestMcpServer,
standardTestTools,
startTestMcpServer,
type RunningTestMcpServer,
type TestMcpToolDef,
} from './mcp-test-server'
@@ -62,11 +63,6 @@ const AIRTABLE_TOOLS: TestMcpToolDef[] = [
},
]
type ProxyExecute = (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
describe('McpService', () => {
setupTestDbHooks()
@@ -199,7 +195,7 @@ describe('McpService', () => {
const agent = await seedAgentAndUser(teamId, 'Meta Name Agent')
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
const agentTools = await service.buildAgentTools(agent.id, teamId)
const search = await (agentTools[0].execute as ProxyExecute)('meta-1', { search: 'echo' })
const search = await invokeTool(agentTools[0], 'meta-1', { search: 'echo' })
expect(JSON.stringify(search.content)).toContain('Meta_Server_echo')
} finally {
await metaSrv.stop()
@@ -337,14 +333,14 @@ describe('McpService', () => {
expect(proxy.description).not.toContain(instructionsText)
// L2: longer preview at the end of the server listing + full-text hint.
const list = await (proxy.execute as ProxyExecute)('list-1', { server: 'inst-srv' })
const list = await invokeTool(proxy, 'list-1', { server: 'inst-srv' })
const listText = JSON.stringify(list.content)
expect(listText).toContain('Server instructions:')
expect(listText).toContain('for the full text')
expect(listText).not.toContain(instructionsText)
// L3: full text via the instructions mode.
const full = await (proxy.execute as ProxyExecute)('inst-1', { instructions: 'inst-srv' })
const full = await invokeTool(proxy, 'inst-1', { instructions: 'inst-srv' })
const fullText = JSON.stringify(full.content)
expect(fullText).toContain(instructionsText)
expect(fullText).toContain('inst-srv instructions:')
@@ -364,9 +360,9 @@ describe('McpService', () => {
// No L1 block, no L2 preview, and L3 says so explicitly.
expect(proxy.description).not.toContain('Server instructions (truncated')
const list = await (proxy.execute as ProxyExecute)('list-1', { server: 'test-mcp-server' })
const list = await invokeTool(proxy, 'list-1', { server: 'test-mcp-server' })
expect(JSON.stringify(list.content)).not.toContain('Server instructions:')
const full = await (proxy.execute as ProxyExecute)('inst-1', {
const full = await invokeTool(proxy, 'inst-1', {
instructions: 'test-mcp-server',
})
expect(JSON.stringify(full.content)).toContain('does not provide instructions')
@@ -386,7 +382,7 @@ describe('McpService', () => {
const agent = await seedAgentAndUser(teamId, 'Cache Agent')
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
const tools = await service.buildAgentTools(agent.id, teamId)
const full = await (tools[0].execute as ProxyExecute)('inst-1', {
const full = await invokeTool(tools[0], 'inst-1', {
instructions: 'cache-srv',
})
expect(JSON.stringify(full.content)).toContain('Always use the read-only API.')
@@ -661,12 +657,11 @@ describe('McpService', () => {
expect(tools[0].description).toContain('test-mcp-server')
// Executing the proxy's call mode hits the real server.
const result = await (
tools[0].execute as (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
)('call-1', { server: 'test-mcp-server', tool: 'echo', args: { text: 'via-proxy' } })
const result = await invokeTool(tools[0], 'call-1', {
server: 'test-mcp-server',
tool: 'echo',
args: { text: 'via-proxy' },
})
expect(JSON.stringify(result.content)).toContain('echo:via-proxy')
})
@@ -704,7 +699,7 @@ describe('McpService', () => {
try {
// The agent only has tavily assigned. Asking for a tool that does not
// exist on tavily must not surface airtable's tool names as suggestions.
const result = await (proxy.execute as ProxyExecute)('leak-1', {
const result = await invokeTool(proxy, 'leak-1', {
server: 'tavily-mcp',
tool: 'search',
})
@@ -721,7 +716,7 @@ describe('McpService', () => {
it('does not resolve, search or describe tools of unassigned servers', async () => {
const { proxy, tavilySrv, airtableSrv } = await seedAgentWithUnassignedServer()
try {
const execute = proxy.execute as ProxyExecute
const execute = (id: string, args: Record<string, unknown>) => invokeTool(proxy, id, args)
// 1. Direct tool call with the unassigned server's prefixed tool name
// (no server param) must not execute airtable's handler.
@@ -758,10 +753,10 @@ describe('McpService', () => {
where: { agentId: agent.id, mcpServerId: airtable.id },
})
tools = await service.buildAgentTools(agent.id, teamId)
const search = await (tools[0].execute as ProxyExecute)('leak-5', { search: 'records' })
const search = await invokeTool(tools[0], 'leak-5', { search: 'records' })
expect(JSON.stringify(search.content)).not.toContain('airtable')
const call = await (tools[0].execute as ProxyExecute)('leak-6', {
const call = await invokeTool(tools[0], 'leak-6', {
tool: 'airtable_mcp_server_search_records',
})
expect(JSON.stringify(call.content)).not.toContain('AIRTABLE-SECRET-DATA')
@@ -836,12 +831,7 @@ describe('McpService', () => {
// Direct tool executes through callMcpTool.
const echo = tools.find((t) => t.name === 'test_mcp_server_echo')!
const result = await (
echo.execute as (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
)('call-2', { text: 'direct' })
const result = await invokeTool(echo, 'call-2', { text: 'direct' })
expect(JSON.stringify(result.content)).toContain('echo:direct')
})
@@ -867,15 +857,15 @@ describe('McpService', () => {
)
expect(proxy.description).toContain('test-mcp-server (1 tools, status:')
const list = await (proxy.execute as ProxyExecute)('excl-list-1', {
const list = await invokeTool(proxy, 'excl-list-1', {
server: 'test-mcp-server',
})
expect(JSON.stringify(list.content)).not.toContain('test_mcp_server_add')
const search = await (proxy.execute as ProxyExecute)('excl-search-1', { search: 'add' })
const search = await invokeTool(proxy, 'excl-search-1', { search: 'add' })
expect(JSON.stringify(search.content)).not.toContain('test_mcp_server_add')
const call = await (proxy.execute as ProxyExecute)('excl-call-1', {
const call = await invokeTool(proxy, 'excl-call-1', {
server: 'test-mcp-server',
tool: 'add',
args: { a: 1, b: 2 },
@@ -987,29 +977,14 @@ describe('McpService', () => {
expect(tools.length).toBe(1) // only the proxy
const proxy = tools[0]
const callA = await (
proxy.execute as (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
)('c1', { server: 'srvA', tool: 'shared' })
const callA = await invokeTool(proxy, 'c1', { server: 'srvA', tool: 'shared' })
expect(JSON.stringify(callA.content)).toContain('from-A')
const callB = await (
proxy.execute as (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
)('c2', { server: 'srvB', tool: 'shared' })
const callB = await invokeTool(proxy, 'c2', { server: 'srvB', tool: 'shared' })
expect(JSON.stringify(callB.content)).toContain('from-B')
// Prefixed names also resolve without the server parameter.
const prefixed = await (
proxy.execute as (
id: string,
params: unknown,
) => Promise<{ content: Array<{ type: string; text?: string }> }>
)('c3', { tool: 'srvA_get' })
const prefixed = await invokeTool(proxy, 'c3', { tool: 'srvA_get' })
expect(JSON.stringify(prefixed.content)).toContain('A')
} finally {
await srvA.stop()
+9 -6
View File
@@ -2,8 +2,14 @@
* McpService — CRUD, discovery, OAuth, and agent integration for MCP servers.
*/
import type {
ToolRegistration as AgentTool,
ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import { auth } from '@modelcontextprotocol/client'
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { logger } from '@shumai/core/src/logger'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { prisma, type TeamMemberRole } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import type {
@@ -12,20 +18,17 @@ import type {
McpServerInfo,
UpdateMcpServerRequest,
} from '@shumai/dtos'
import { logger } from '@shumai/core/src/logger'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { mcpDbStore, type PendingAuth } from './mcp-db-store'
import { buildDirectTools, isDirectTool } from './mcp-direct-tools'
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
import { buildProxyTool, transformMcpContent, type McpProxyToolContext } from './mcp-proxy-tool'
import { McpServerManager, type McpServerDefinition } from './mcp-server-manager'
import {
formatToolName,
McpToolRegistry,
sanitizeServerPrefix,
type ToolMetadata,
} from './mcp-tool-registry'
import { McpServerManager, type McpServerDefinition } from './mcp-server-manager'
const ROLE_HIERARCHY: Record<string, number> = {
owner: 3,
@@ -39,7 +42,7 @@ export interface McpToolCallContext {
projectId?: string
}
export type McpToolCallContent = AgentToolResult<Record<string, unknown>>['content']
export type McpToolCallContent = NonNullable<AgentToolResult['output']>
export interface McpToolCallResult {
ok: boolean