2026-11-11 16:05:18 +08:00
import type { ToolExecutionResult as AgentToolResult } from '@earendil-works/pi-durable'
2026-10-27 14:37:26 +08:00
import { storageBucket } from '@shumai/core/src/asset-read'
import { completeUploadOp , runOperation } from '@shumai/core/src/operations'
2026-11-18 15:58:57 +08:00
import { runnerService } from '@shumai/core/src/runner'
2026-10-27 14:37:26 +08:00
import { s3Service } from '@shumai/core/src/s3/s3'
2026-11-18 15:58:57 +08:00
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
2026-11-11 16:05:18 +08:00
import { createFile , type StartedUploadOutput } from '@shumai/operations'
import * as path from 'path'
import { Type } from 'typebox'
import { z } from 'zod'
2026-10-27 14:37:26 +08:00
import {
registerAgentToolExtension ,
type AgentOperationContext ,
type AgentToolExtension ,
type AgentToolOptions ,
type ToolParametersSchema ,
} from '../operation-tools'
const METADATA_HINT =
'The optional "metadata" parameter accepts only the CREATION_CONTEXT fields declared in its schema; never invent field keys, and use null for fields you do not know.'
/**
* The agent gets the conversation project's Creation Context fields as a strict schema
* (so it knows exactly what to fill in) instead of the open record MCP clients see. Without
* such fields the parameter is left out.
*/
function setCreationMetadata ( schema : ToolParametersSchema , options : AgentToolOptions ) : void {
if ( options . creationMetadataSchema ) {
schema . properties . metadata = Type . Union ([ options . creationMetadataSchema , Type . Null ()])
} else {
delete schema . properties . metadata
}
}
2026-11-18 15:58:57 +08:00
function resolveGeneratedStorageKey ( rawPath : string ) : {
storageKey : string
explicitStorageRef : boolean
} | null {
const cleaned = rawPath . replace ( /\\/g , '/' ). replace ( /^\.\// , '' )
if ( cleaned . includes ( '..' )) return null
if ( cleaned . startsWith ( '.pi/generated/' )) {
const rest = cleaned . slice ( '.pi/generated/' . length )
return rest ? { storageKey : `temp/generated/ ${ rest } ` , explicitStorageRef : false } : null
}
if ( cleaned . startsWith ( 'temp/generated/' )) {
const rest = cleaned . slice ( 'temp/generated/' . length )
return rest ? { storageKey : cleaned , explicitStorageRef : true } : null
}
return null
}
function normalizeRunnerPath ( rawPath : string ) : string | null {
const cleaned = rawPath . replace ( /\\/g , '/' ). replace ( /^\.\// , '' )
if ( ! cleaned || cleaned . startsWith ( '/' ) || cleaned . includes ( '..' )) {
return null
}
const normalized = path . posix . normalize ( cleaned )
if ( normalized . startsWith ( '..' ) || normalized . startsWith ( '/' )) {
return null
}
if ( normalized === '.pi' || normalized . startsWith ( '.pi/' )) {
return normalized
}
return `.pi/ ${ normalized } `
}
async function resolveTargetRunnerId ( ctx? : AgentOperationContext ) : Promise < string > {
if ( ctx ? . runnerId && ! ctx . teamId ) {
if ( ! runnerService . isRunnerConnected ( ctx . runnerId )) {
throw new Error (
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.' ,
)
}
return ctx . runnerId
}
const runner = await runnerService . requireOnlineRunner ( ctx ? . teamId || '' , ctx ? . runnerId )
return runner . id
}
async function resolveStorageGeneratedSource ( storageKey : string ) : Promise < {
kind : 'generated'
storageKey : string
name : string
contentType : string
} | null > {
const head = await s3Service . headObject ( storageBucket (), storageKey ). catch (() => null )
if ( ! head ) {
return null
}
const name = path . posix . basename ( storageKey )
const contentType =
head . contentType && head . contentType !== 'application/octet-stream'
? head.contentType
: getFileMimeType ( null , name )
return { kind : 'generated' , storageKey , name , contentType }
}
async function resolvePathSource (
localPath : string ,
ctx? : AgentOperationContext ,
) : Promise <
| { kind : 'generated' ; storageKey : string ; name : string ; contentType : string }
| { kind : 'runner' ; runnerId : string ; runnerPath : string ; name : string ; contentType : string }
> {
const generatedRef = resolveGeneratedStorageKey ( localPath )
if ( generatedRef ? . explicitStorageRef ) {
const source = await resolveStorageGeneratedSource ( generatedRef . storageKey )
if ( ! source ) {
throw new Error ( `Local file not found at path: ${ localPath } ` )
}
return source
}
const runnerPath = normalizeRunnerPath ( localPath )
if ( ! runnerPath ) {
2026-10-27 14:37:26 +08:00
throw new Error ( `Local file not found at path: ${ localPath } ` )
}
2026-11-18 15:58:57 +08:00
let runnerError : unknown
try {
const runnerId = await resolveTargetRunnerId ( ctx )
const stat = await runnerService . statOnRunner ( runnerId , runnerPath )
if ( stat . ok && stat . exists && stat . isFile !== false ) {
const name = path . posix . basename ( runnerPath )
const contentType =
stat . mimeType && stat . mimeType !== 'application/octet-stream'
? stat.mimeType
: getFileMimeType ( null , name )
return { kind : 'runner' , runnerId , runnerPath , name , contentType }
}
} catch ( err ) {
if ( ! generatedRef ) {
throw err
}
runnerError = err
}
// Fallback for unstaged generated files stored in temporary S3
if ( generatedRef ) {
const source = await resolveStorageGeneratedSource ( generatedRef . storageKey )
if ( source ) {
return source
}
if ( runnerError ) {
throw runnerError
}
}
throw new Error ( `Local file not found at path: ${ localPath } ` )
2026-10-27 14:37:26 +08:00
}
/**
2026-11-18 15:58:57 +08:00
* Transfers the file from either temporary generated storage or the remote runner workspace
* into the upload's storage key, then completes the upload as the agent.
2026-10-27 14:37:26 +08:00
*/
async function uploadAndComplete (
raw : unknown ,
extra : Record < string , unknown >,
ctx : AgentOperationContext ,
2026-11-11 16:05:18 +08:00
) : Promise < AgentToolResult > {
2026-10-27 14:37:26 +08:00
const started = raw as StartedUploadOutput
if ( ! started . key ) throw new Error ( 'The upload did not return a storage key' )
if ( typeof extra . path === 'string' ) {
2026-11-18 15:58:57 +08:00
const source =
( extra . __resolvedSource as Awaited < ReturnType < typeof resolvePathSource >> | undefined ) ??
( await resolvePathSource ( extra . path , ctx ))
if ( source . kind === 'generated' ) {
const obj = await s3Service . getObject ( storageBucket (), source . storageKey )
await s3Service . putObject (
storageBucket (),
started . key ,
obj . buffer ,
obj . buffer . length ,
source . contentType ,
)
} else {
const uploadRes = await runnerService . uploadFromRunner ( source . runnerId , {
srcPath : source.runnerPath ,
url : started.uploadUrl ,
contentType : source.contentType ,
})
if ( ! uploadRes . ok ) {
throw new Error ( uploadRes . error || `Failed to upload file " ${ extra . path } " from runner` )
}
}
2026-10-27 14:37:26 +08:00
} else {
const content = Buffer . from ( typeof extra . content === 'string' ? extra . content : '' , 'utf-8' )
// The key ends with the file name, which gives the same type as the upload's.
const contentType = getFileMimeType ( null , started . key , 'text/plain' )
await s3Service . putObject (
storageBucket (),
started . key ,
content ,
content . byteLength ,
contentType ,
)
}
const asset = await runOperation (
completeUploadOp ,
{ ... ctx , via : 'agent' },
{ uploadId : started.uploadId },
)
2026-11-11 16:05:18 +08:00
return { output : [{ type : 'text' , text : JSON.stringify ( asset , null , 2 ) }], details : {} }
2026-10-27 14:37:26 +08:00
}
const createFileExtension : AgentToolExtension = {
description :
'Create a new file in a folder. Choose exactly ONE source: ' +
2026-11-18 15:58:57 +08:00
'(1) "path" to upload a file from .pi (e.g. a generated file in .pi/generated/... or a file created in .pi on the runner), OR ' +
2026-10-27 14:37:26 +08:00
'(2) "name" and "content" to create a text file with that content. ' +
METADATA_HINT ,
parameterOverrides : z.object ({
name : createFile.input.shape.name
. optional ()
. describe (
'File name including its extension (e.g. "notes.md"). Required with "content"; defaults to the local file\'s name with "path".' ,
),
}),
extraParameters : z.object ({
path : z
. string ()
. min ( 1 )
. optional ()
2026-11-18 15:58:57 +08:00
. describe (
'Path of a file in .pi (e.g. ".pi/generated/..." or ".pi/output.mp4") to upload. Omit when using "content".' ,
),
2026-10-27 14:37:26 +08:00
content : z
. string ()
. optional ()
. describe ( 'Full text content of a new text file. Requires "name"; omit when using "path".' ),
}),
hiddenParameters : [ 'contentType' ],
adjustParameters : setCreationMetadata ,
2026-11-18 15:58:57 +08:00
async toInput ( input , extra , ctx ) {
2026-10-27 14:37:26 +08:00
const hasPath = typeof extra . path === 'string'
const hasContent = typeof extra . content === 'string'
if ( hasPath === hasContent ) {
throw new Error ( 'Provide exactly one of "path" (a local file) or "content" (with "name").' )
}
if ( hasPath ) {
2026-11-18 15:58:57 +08:00
const source = await resolvePathSource ( extra . path as string , ctx )
extra . __resolvedSource = source
2026-10-27 14:37:26 +08:00
return {
... input ,
2026-11-18 15:58:57 +08:00
name : input.name ?? source . name ,
contentType : source.contentType ,
2026-10-27 14:37:26 +08:00
}
}
if ( typeof input . name !== 'string' || ! input . name . trim ()) {
throw new Error ( '"name" is required when creating a file from "content".' )
}
return { ... input , contentType : getFileMimeType ( null , input . name , 'text/plain' ) }
},
present : uploadAndComplete ,
}
const createVersionExtension : AgentToolExtension = {
description :
2026-11-18 15:58:57 +08:00
'Create a new version of an existing file (or version stack) from a file path in .pi. ' +
2026-10-27 14:37:26 +08:00
'The new version becomes the current one. ' +
METADATA_HINT ,
extraParameters : z.object ({
path : z
. string ()
. min ( 1 )
2026-11-18 15:58:57 +08:00
. describe (
'Path of the file in .pi (e.g. ".pi/generated/..." or ".pi/output.mp4") to upload as the new version.' ,
),
2026-10-27 14:37:26 +08:00
}),
hiddenParameters : [ 'name' , 'contentType' ],
adjustParameters : setCreationMetadata ,
2026-11-18 15:58:57 +08:00
async toInput ( input , extra , ctx ) {
const source = await resolvePathSource ( extra . path as string , ctx )
extra . __resolvedSource = source
2026-10-27 14:37:26 +08:00
return {
... input ,
2026-11-18 15:58:57 +08:00
name : source.name ,
contentType : source.contentType ,
2026-10-27 14:37:26 +08:00
}
},
present : uploadAndComplete ,
}
registerAgentToolExtension ( 'create_file' , createFileExtension )
registerAgentToolExtension ( 'create_version' , createVersionExtension )