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
+18 -11
View File
@@ -1,14 +1,15 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { vi } from 'vitest'
vi.mock('fs')
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { createGenerateImageTool } from './generate-image'
import * as downloadAsset from './download-asset'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import * as downloadAsset from './download-asset'
import { createGenerateImageTool } from './generate-image'
describe('generate_image tool', () => {
const enabledModels: EnabledMediaModel[] = [
@@ -60,7 +61,6 @@ describe('generate_image tool', () => {
it('creates tool with correct metadata and provider-prefixed model schema', () => {
const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1')
expect(tool.name).toBe('generate_image')
expect(tool.label).toBe('Generate Image')
expect(tool.description).toContain('Generate an image')
const modelDesc = (tool.parameters as { properties: { model: { description: string } } })
.properties.model.description
@@ -78,7 +78,8 @@ describe('generate_image tool', () => {
})
const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
const result = await tool.execute(
const result = await invokeTool(
tool,
'call-1',
{
prompt: 'A futuristic city skyline at dusk',
@@ -129,7 +130,8 @@ describe('generate_image tool', () => {
})
// Invoke azure:dall-e-3
await tool.execute(
await invokeTool(
tool,
'call-azure',
{
prompt: 'Azure generation',
@@ -153,7 +155,8 @@ describe('generate_image tool', () => {
)
// Invoke openai:dall-e-3
await tool.execute(
await invokeTool(
tool,
'call-openai',
{
prompt: 'OpenAI generation',
@@ -186,7 +189,8 @@ describe('generate_image tool', () => {
mimeType: 'image/png',
})
await tool.execute(
await invokeTool(
tool,
'call-2',
{
prompt: 'A cute cat',
@@ -224,7 +228,8 @@ describe('generate_image tool', () => {
mimeType: 'image/png',
}))
await tool.execute(
await invokeTool(
tool,
'call-3',
{
prompt: 'Transform into watercolor',
@@ -257,7 +262,8 @@ describe('generate_image tool', () => {
const tool = createGenerateImageTool(enabledModels, {}, 'user-1') // No keys configured
await expect(
tool.execute(
invokeTool(
tool,
'call-4',
{
prompt: 'A sunset',
@@ -278,7 +284,8 @@ describe('generate_image tool', () => {
const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1')
await expect(
tool.execute(
invokeTool(
tool,
'call-5',
{
prompt: 'A sunset',
+6 -6
View File
@@ -1,10 +1,10 @@
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { EnabledMediaModel } from '@shumai/dtos'
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { Type, type Static, type TSchema } from 'typebox'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { Type, type Static, type TSchema } from 'typebox'
import { ulid } from 'ulid'
import { resolveS3MediaBuffer } from './download-asset'
@@ -83,11 +83,11 @@ export function createGenerateImageTool(
return {
name: 'generate_image',
label: 'Generate Image',
description:
'Generate an image using a configured image model. Supports text-to-image, reference images (image-to-image using S3 keys from read_asset), and inpainting (using a mask image S3 key from read_asset). The generated file is saved in the local .pi/ directory.',
parameters: generateImageSchema,
execute: async (_toolCallId, params) => {
execute: async (params) => {
const p = params as GenerateImageParams
const defaultModel = `${enabledModels[0].provider}:${enabledModels[0].modelId}`
@@ -161,7 +161,7 @@ export function createGenerateImageTool(
fs.writeFileSync(targetPath, buffer)
return {
content: [
output: [
{
type: 'text',
text: `Successfully generated image using model "${modelConfig.modelId}" (${modelConfig.provider}). Saved to "${relativePath}". Size: ${(buffer.length / 1024).toFixed(1)} KB.`,
+18 -11
View File
@@ -1,14 +1,15 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { vi } from 'vitest'
vi.mock('fs')
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { createGenerateVideoTool } from './generate-video'
import * as downloadAsset from './download-asset'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import * as downloadAsset from './download-asset'
import { createGenerateVideoTool } from './generate-video'
describe('generate_video tool', () => {
const enabledModels: EnabledMediaModel[] = [
@@ -60,7 +61,6 @@ describe('generate_video tool', () => {
it('creates tool with correct metadata and provider-prefixed model schema', () => {
const tool = createGenerateVideoTool(enabledModels, providerKeys, 'user-1')
expect(tool.name).toBe('generate_video')
expect(tool.label).toBe('Generate Video')
expect(tool.description).toContain('Generate a video')
const modelDesc = (tool.parameters as { properties: { model: { description: string } } })
.properties.model.description
@@ -78,7 +78,8 @@ describe('generate_video tool', () => {
})
const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
const result = await tool.execute(
const result = await invokeTool(
tool,
'call-vid-1',
{
mode: 'text_to_video',
@@ -140,7 +141,8 @@ describe('generate_video tool', () => {
})
// Select fal:kling-v1-standard
await tool.execute(
await invokeTool(
tool,
'call-fal',
{
mode: 'text_to_video',
@@ -169,7 +171,8 @@ describe('generate_video tool', () => {
)
// Select klingai:kling-v1-standard
await tool.execute(
await invokeTool(
tool,
'call-klingai',
{
mode: 'text_to_video',
@@ -211,7 +214,8 @@ describe('generate_video tool', () => {
mimeType: 'image/png',
})
await tool.execute(
await invokeTool(
tool,
'call-vid-2',
{
mode: 'image_to_video',
@@ -257,7 +261,8 @@ describe('generate_video tool', () => {
mimeType: 'image/png',
}))
await tool.execute(
await invokeTool(
tool,
'call-vid-3',
{
mode: 'first_last_frame',
@@ -304,7 +309,8 @@ describe('generate_video tool', () => {
mimeType: 'image/png',
}))
await tool.execute(
await invokeTool(
tool,
'call-vid-4',
{
mode: 'reference_to_video',
@@ -343,7 +349,8 @@ describe('generate_video tool', () => {
const tool = createGenerateVideoTool(enabledModels, {}, 'user-1')
await expect(
tool.execute(
invokeTool(
tool,
'call-vid-5',
{
mode: 'text_to_video',
+6 -6
View File
@@ -1,10 +1,10 @@
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { EnabledMediaModel } from '@shumai/dtos'
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { Type, type Static, type TSchema } from 'typebox'
import { EnabledMediaModel } from '@shumai/dtos'
import * as fs from 'fs'
import * as path from 'path'
import { Type, type Static, type TSchema } from 'typebox'
import { ulid } from 'ulid'
import { resolveS3MediaBuffer } from './download-asset'
@@ -162,11 +162,11 @@ export function createGenerateVideoTool(
return {
name: 'generate_video',
label: 'Generate Video',
description:
'Generate a video using a configured video model. Supports text-to-video, image-to-video (using an S3 image key from read_asset), first/last frame (using S3 image keys from read_asset), and reference-to-video (using S3 image keys from read_asset). The generated file is saved in the local .pi/ directory.',
parameters: generateVideoSchema,
execute: async (_toolCallId, params) => {
execute: async (params) => {
const p = params as GenerateVideoParams
const defaultModel = `${enabledModels[0].provider}:${enabledModels[0].modelId}`
@@ -280,7 +280,7 @@ export function createGenerateVideoTool(
fs.writeFileSync(targetPath, buffer)
return {
content: [
output: [
{
type: 'text',
text: `Successfully generated video using model "${modelConfig.modelId}" (${modelConfig.provider}) in mode "${p.mode}". Saved to "${relativePath}". Size: ${(buffer.length / (1024 * 1024)).toFixed(2)} MB.`,
+34 -19
View File
@@ -1,15 +1,16 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { vi } from 'vitest'
vi.mock('@shumai/core/src/s3/s3')
vi.mock('fs')
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { createReadSkillTool } from './read-skill'
import { s3Service } from '@shumai/core/src/s3/s3'
import AdmZip from 'adm-zip'
import * as fs from 'fs'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createReadSkillTool } from './read-skill'
describe('readSkillTool', () => {
setupTestDbHooks()
@@ -21,7 +22,7 @@ describe('readSkillTool', () => {
it('should throw error if skill not found', async () => {
const readSkillTool = createReadSkillTool(undefined, () => {})
await expect(
readSkillTool.execute('1', { skillId: 'non-existent' }, undefined, undefined),
invokeTool(readSkillTool, '1', { skillId: 'non-existent' }, undefined, undefined),
).rejects.toThrow('not found')
})
@@ -45,7 +46,7 @@ describe('readSkillTool', () => {
})
const readSkillTool = createReadSkillTool(undefined, () => {})
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
const result = await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Test Skill Content')
@@ -97,7 +98,7 @@ describe('readSkillTool', () => {
})
const readSkillTool = createReadSkillTool(undefined, () => {})
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
const result = await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Extracted Content')
@@ -144,7 +145,7 @@ describe('readSkillTool', () => {
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
CONFIGURED_VAR: 'user-val',
@@ -179,7 +180,7 @@ describe('readSkillTool', () => {
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
OVERRIDDEN_VAR: 'user-val',
@@ -214,7 +215,7 @@ describe('readSkillTool', () => {
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
FALLBACK_VAR: 'host-val',
@@ -249,7 +250,7 @@ describe('readSkillTool', () => {
const readSkillTool = createReadSkillTool(undefined, (envs) => {
capturedEnvs = { ...capturedEnvs, ...envs }
})
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(capturedEnvs).toEqual({
FALLBACK_VAR_UNDEF: 'host-val2',
@@ -293,7 +294,8 @@ describe('readSkillTool', () => {
})
const ownerTool = createReadSkillTool(ownerUser.id, () => {})
const resultOwner = await ownerTool.execute(
const resultOwner = await invokeTool(
ownerTool,
'1',
{ skillId: ownerSkill.id },
undefined,
@@ -304,7 +306,7 @@ describe('readSkillTool', () => {
const reviewerTool = createReadSkillTool(reviewerUser.id, () => {})
await expect(
reviewerTool.execute('1', { skillId: ownerSkill.id }, undefined, undefined),
invokeTool(reviewerTool, '1', { skillId: ownerSkill.id }, undefined, undefined),
).rejects.toThrow('Permission denied')
})
@@ -340,7 +342,7 @@ describe('readSkillTool', () => {
project.id,
)
await expect(
demotedTool.execute('1', { skillId: editorSkill.id }, undefined, undefined),
invokeTool(demotedTool, '1', { skillId: editorSkill.id }, undefined, undefined),
).rejects.toThrow('Permission denied')
// Project-scoped member invited as editor: allowed
@@ -369,7 +371,8 @@ describe('readSkillTool', () => {
undefined,
project.id,
)
const result = await projEditorTool.execute(
const result = await invokeTool(
projEditorTool,
'1',
{ skillId: editorSkill.id },
undefined,
@@ -402,7 +405,7 @@ describe('readSkillTool', () => {
const onSkillLoaded = vi.fn()
const readSkillTool = createReadSkillTool(undefined, () => {}, onSkillLoaded)
await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
expect(onSkillLoaded).toHaveBeenCalledTimes(1)
})
@@ -428,7 +431,7 @@ describe('readSkillTool', () => {
const onSkillLoaded = vi.fn()
const reviewerTool = createReadSkillTool(reviewerUser.id, () => {}, onSkillLoaded)
await expect(
reviewerTool.execute('1', { skillId: ownerSkill.id }, undefined, undefined),
invokeTool(reviewerTool, '1', { skillId: ownerSkill.id }, undefined, undefined),
).rejects.toThrow('Permission denied')
expect(onSkillLoaded).not.toHaveBeenCalled()
@@ -451,7 +454,7 @@ describe('readSkillTool', () => {
'some-other-enabled-skill',
])
await expect(
readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined),
invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined),
).rejects.toThrow('not enabled for this agent')
})
@@ -475,7 +478,13 @@ describe('readSkillTool', () => {
})
const readSkillTool = createReadSkillTool(undefined, () => {}, undefined, [skill.id])
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
const result = await invokeTool(
readSkillTool,
'1',
{ skillId: skill.id },
undefined,
undefined,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Enabled For Agent Skill')
})
@@ -500,7 +509,13 @@ describe('readSkillTool', () => {
})
const readSkillTool = createReadSkillTool(undefined, () => {})
const result = await readSkillTool.execute('1', { skillId: skill.id }, undefined, undefined)
const result = await invokeTool(
readSkillTool,
'1',
{ skillId: skill.id },
undefined,
undefined,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# No Filter Skill')
})
+6 -6
View File
@@ -1,8 +1,8 @@
import { prisma } from '@shumai/db'
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { agentService } from '@shumai/core/src/agent/agent'
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { prisma } from '@shumai/db'
import { Type } from 'typebox'
const readSkillSchema = Type.Object({
skillId: Type.String({ description: 'The ID of the skill to read' }),
@@ -22,10 +22,10 @@ export const createReadSkillTool = (
projectId?: string,
): AgentTool<typeof readSkillSchema, { skillId: string }> => ({
name: 'read_skill',
label: 'Read Agent Skill',
description: 'Downloads and reads an agent skill to understand how to use it.',
parameters: readSkillSchema,
execute: async (_toolCallId, params) => {
execute: async (params) => {
const skill = await prisma.skill.findUnique({
where: { id: params.skillId },
})
@@ -71,7 +71,7 @@ export const createReadSkillTool = (
await onSkillLoaded?.()
return {
content: [{ type: 'text', text: skillMdContent }],
output: [{ type: 'text', text: skillMdContent }],
details: { skillId: params.skillId },
}
},
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { describe, expect, it } from 'vitest'
import { createReadThreadTool } from './read-thread'
/**
@@ -45,7 +46,7 @@ describe('read_thread authorization', () => {
const a = await seedTeamWithThread('a')
const tool = createReadThreadTool({ userId: a.author.id, teamId: a.team.id })
const result = await tool.execute('call-1', { threadId: a.thread.id })
const result = await invokeTool(tool, 'call-1', { threadId: a.thread.id })
const text = (result.content[0] as { text: string }).text
expect(text).toContain('secret message a')
@@ -58,7 +59,7 @@ describe('read_thread authorization', () => {
const tool = createReadThreadTool({ userId: a.author.id, teamId: a.team.id })
await expect(tool.execute('call-1', { threadId: b.thread.id })).rejects.toThrow(
await expect(invokeTool(tool, 'call-1', { threadId: b.thread.id })).rejects.toThrow(
'User is not a member of the team',
)
})
@@ -74,7 +75,7 @@ describe('read_thread authorization', () => {
const tool = createReadThreadTool({ userId: outsider.id, teamId: b.team.id })
await expect(tool.execute('call-1', { threadId: b.thread.id })).rejects.toThrow()
await expect(invokeTool(tool, 'call-1', { threadId: b.thread.id })).rejects.toThrow()
})
it('confines a system agent (no user) to threads in its own team', async () => {
@@ -83,9 +84,11 @@ describe('read_thread authorization', () => {
const tool = createReadThreadTool({ teamId: a.team.id })
const own = await tool.execute('call-1', { threadId: a.thread.id })
const own = await invokeTool(tool, 'call-1', { threadId: a.thread.id })
expect((own.content[0] as { text: string }).text).toContain('secret message a')
await expect(tool.execute('call-2', { threadId: b.thread.id })).rejects.toThrow('Access denied')
await expect(invokeTool(tool, 'call-2', { threadId: b.thread.id })).rejects.toThrow(
'Access denied',
)
})
})
+10 -9
View File
@@ -1,7 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createReadThreadTool } from './read-thread'
import { prisma } from '@shumai/db'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { authzService } from '@shumai/core/src/authz/authz'
import { prisma } from '@shumai/db'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createReadThreadTool } from './read-thread'
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
@@ -37,7 +38,7 @@ describe('createReadThreadTool', () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-1', { threadId: 'non-existent' })
const result = await invokeTool(tool, 'call-1', { threadId: 'non-existent' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain('Comment thread with ID "non-existent" not found.')
@@ -49,7 +50,7 @@ describe('createReadThreadTool', () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue({ id: 'asset-1' } as any)
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-asset', { threadId: 'asset-1' })
const result = await invokeTool(tool, 'call-asset', { threadId: 'asset-1' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain('ID "asset-1" is an Asset ID, not a Comment Thread ID')
@@ -68,7 +69,7 @@ describe('createReadThreadTool', () => {
vi.mocked(prisma.assetComment.findMany).mockResolvedValue([])
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-2', { threadId: 'root-1' })
const result = await invokeTool(tool, 'call-2', { threadId: 'root-1' })
const textContent = (result.content[0] as { text: string }).text
expect(authzService.hasPermission).toHaveBeenCalledWith({
@@ -107,7 +108,7 @@ describe('createReadThreadTool', () => {
] as any)
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-3', { threadId: 'root-1' })
const result = await invokeTool(tool, 'call-3', { threadId: 'root-1' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain(
@@ -139,7 +140,7 @@ describe('createReadThreadTool', () => {
] as any)
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-agent', { threadId: 'root-1' })
const result = await invokeTool(tool, 'call-agent', { threadId: 'root-1' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain('- [Ai Agent] (id: reply-1, has_markup: false): Agent answer')
@@ -170,7 +171,7 @@ describe('createReadThreadTool', () => {
] as any)
const tool = createReadThreadTool({ userId: 'user-1', teamId: 'team-1' })
const result = await tool.execute('call-3d', { threadId: 'root-3d' })
const result = await invokeTool(tool, 'call-3d', { threadId: 'root-3d' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain(
+8 -8
View File
@@ -1,10 +1,10 @@
import { prisma, type User } from '@shumai/db'
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { secondToDegree } from '@shumai/core/src/utils/model3d'
import { getProxyType } from '@shumai/core/src/utils/mime'
import { secondToDegree } from '@shumai/core/src/utils/model3d'
import { prisma, type User } from '@shumai/db'
import { Type } from 'typebox'
const readThreadSchema = Type.Object({
threadId: Type.String({
@@ -67,10 +67,10 @@ export const createReadThreadTool = (
ctx: ReadThreadToolContext,
): AgentTool<typeof readThreadSchema, { threadId: string }> => ({
name: 'read_thread',
label: 'Read Comment Thread',
description: 'Reads all comments and replies inside a specific comment thread.',
parameters: readThreadSchema,
execute: async (_toolCallId, params) => {
execute: async (params) => {
const rootComment = await prisma.assetComment.findUnique({
where: { id: params.threadId },
include: {
@@ -89,7 +89,7 @@ export const createReadThreadTool = (
: `Comment thread with ID "${params.threadId}" not found.`
return {
content: [{ type: 'text', text: errorText }],
output: [{ type: 'text', text: errorText }],
details: { threadId: params.threadId },
}
}
@@ -127,7 +127,7 @@ export const createReadThreadTool = (
}
return {
content: [{ type: 'text', text: output }],
output: [{ type: 'text', text: output }],
details: { threadId: params.threadId },
}
},
+25 -12
View File
@@ -1,9 +1,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createSandboxedBashTool } from './sandboxed-bash'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { spawn } from 'node:child_process'
import { EventEmitter } from 'node:events'
import { readFile } from 'node:fs/promises'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createSandboxedBashTool } from './sandboxed-bash'
vi.mock('@anthropic-ai/sandbox-runtime')
vi.mock('node:child_process')
@@ -57,7 +58,8 @@ describe('createSandboxedBashTool', () => {
const signal = createMockSignal()
// pi-coding-agent AgentTool.execute signature: (toolCallId, params, signal?, onUpdate?)
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'echo hello', source: 'user' },
signal,
@@ -97,7 +99,7 @@ describe('createSandboxedBashTool', () => {
const signal = createMockSignal()
await expect(
tool.execute('1', { command: 'echo hack', source: 'user' }, signal, createMockOnUpdate()),
invokeTool(tool, '1', { command: 'echo hack', source: 'user' }, signal, createMockOnUpdate()),
).rejects.toThrow(/not permitted for your role/)
expect(spawn).not.toHaveBeenCalled()
@@ -119,7 +121,7 @@ describe('createSandboxedBashTool', () => {
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute('1', { command: 'echo skill', source: 'skill' }, signal)
const executePromise = invokeTool(tool, '1', { command: 'echo skill', source: 'skill' }, signal)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
expect(SandboxManager.wrapWithSandbox).toHaveBeenCalledWith(
@@ -145,7 +147,8 @@ describe('createSandboxedBashTool', () => {
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'fail', source: 'user' },
signal,
@@ -169,7 +172,8 @@ describe('createSandboxedBashTool', () => {
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'exit 1', source: 'user' },
signal,
@@ -198,7 +202,8 @@ describe('createSandboxedBashTool', () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'sleep 10', timeout: 2, source: 'user' },
signal,
@@ -232,7 +237,8 @@ describe('createSandboxedBashTool', () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'long-run', source: 'user' },
signal,
@@ -266,7 +272,12 @@ describe('createSandboxedBashTool', () => {
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute('1', { command: 'generate lines', source: 'user' }, signal)
const executePromise = invokeTool(
tool,
'1',
{ command: 'generate lines', source: 'user' },
signal,
)
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
@@ -308,7 +319,8 @@ describe('createSandboxedBashTool', () => {
;(spawn as any).mockReturnValue(mockChild)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'long single line', source: 'user' },
signal,
@@ -342,7 +354,8 @@ describe('createSandboxedBashTool', () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
const signal = createMockSignal()
const executePromise = tool.execute(
const executePromise = invokeTool(
tool,
'1',
{ command: 'slow', timeout: 1, source: 'user' },
signal,
+16 -59
View File
@@ -1,8 +1,13 @@
import {
type ToolRegistration as AgentTool,
type ToolExecutionResult as AgentToolResult,
} from '@earendil-works/pi-durable'
import { logger } from '@shumai/core/src/logger'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
import { Type } from 'typebox'
import type { TeamMemberRole } from '@shumai/db'
import { spawn } from 'node:child_process'
import { Type } from 'typebox'
import { OutputAccumulator } from '../utils/output-accumulator'
import {
DEFAULT_MAX_BYTES,
@@ -10,8 +15,6 @@ import {
formatSize,
type TruncationResult,
} from '../utils/truncate'
import { quotaService } from '@shumai/core/src/quota/quota-service'
import type { TeamMemberRole } from '@shumai/db'
const BashSource = Type.String({
enum: ['user', 'skill'],
@@ -28,7 +31,7 @@ const BashParameters = Type.Object({
source: BashSource,
})
export interface BashDetails {
export type BashDetails = {
exitCode: number | null
truncation?: TruncationResult
fullOutputPath?: string
@@ -47,8 +50,6 @@ export interface SandboxedBashOptions {
restrictedUser?: boolean
}
const BASH_UPDATE_THROTTLE_MS = 100
export const createSandboxedBashTool = (
cwd: string,
skillEnvs: Record<string, string> = {},
@@ -57,14 +58,15 @@ export const createSandboxedBashTool = (
return {
name: 'bash',
description: `Execute a bash command in a sandboxed environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds. When in a restricted (non-owner) user context, only commands required by a skill loaded via the read_skill tool are allowed, and you must set source="skill".`,
label: 'Executing bash command',
parameters: BashParameters,
outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' },
execute: async (
toolCallId,
{ command, timeout, source },
signal,
onUpdate,
api,
context,
): Promise<AgentToolResult<BashDetails>> => {
const toolCallId = api.callId
const signal = context.abortSignal
if (options?.restrictedUser && source !== 'skill') {
throw new Error(
'Bash commands requested directly by the user (source="user") are not permitted for your role. ' +
@@ -88,62 +90,17 @@ export const createSandboxedBashTool = (
const output = new OutputAccumulator({ tempFilePrefix: 'shumai-bash' })
let acceptingOutput = true
let updateTimer: NodeJS.Timeout | undefined
let updateDirty = false
let lastUpdateAt = 0
const emitOutputUpdate = () => {
if (!onUpdate || !updateDirty) return
updateDirty = false
lastUpdateAt = Date.now()
const snapshot = output.snapshot({ persistIfTruncated: true })
onUpdate({
content: [{ type: 'text', text: snapshot.content || '' }],
details: {
exitCode: null,
truncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,
fullOutputPath: snapshot.fullOutputPath,
},
})
}
const clearUpdateTimer = () => {
if (updateTimer) {
clearTimeout(updateTimer)
updateTimer = undefined
}
}
const scheduleOutputUpdate = () => {
if (!onUpdate) return
updateDirty = true
const delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt)
if (delay <= 0) {
clearUpdateTimer()
emitOutputUpdate()
return
}
updateTimer ??= setTimeout(() => {
updateTimer = undefined
emitOutputUpdate()
}, delay)
}
if (onUpdate) {
onUpdate({ content: [], details: { exitCode: null } })
}
await api.details({ exitCode: null }, context)
const handleData = (data: Buffer) => {
if (!acceptingOutput) return
output.append(data)
scheduleOutputUpdate()
api.output(data)
}
const finishOutput = async () => {
acceptingOutput = false
output.finish()
clearUpdateTimer()
emitOutputUpdate()
const snapshot = output.snapshot({ persistIfTruncated: true })
await output.closeTempFile()
return snapshot
@@ -284,7 +241,7 @@ export const createSandboxedBashTool = (
)
} else {
resolve({
content: [
output: [
{
type: 'text',
text: outputText,